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 "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 // Disable the smallest fractional LMUL types if ELEN is less than 116 // RVVBitsPerBlock. 117 unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN(); 118 if (VT.getVectorMinNumElements() < MinElts) 119 return; 120 121 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 122 const TargetRegisterClass *RC; 123 if (Size <= RISCV::RVVBitsPerBlock) 124 RC = &RISCV::VRRegClass; 125 else if (Size == 2 * RISCV::RVVBitsPerBlock) 126 RC = &RISCV::VRM2RegClass; 127 else if (Size == 4 * RISCV::RVVBitsPerBlock) 128 RC = &RISCV::VRM4RegClass; 129 else if (Size == 8 * RISCV::RVVBitsPerBlock) 130 RC = &RISCV::VRM8RegClass; 131 else 132 llvm_unreachable("Unexpected size"); 133 134 addRegisterClass(VT, RC); 135 }; 136 137 for (MVT VT : BoolVecVTs) 138 addRegClassForRVV(VT); 139 for (MVT VT : IntVecVTs) { 140 if (VT.getVectorElementType() == MVT::i64 && 141 !Subtarget.hasVInstructionsI64()) 142 continue; 143 addRegClassForRVV(VT); 144 } 145 146 if (Subtarget.hasVInstructionsF16()) 147 for (MVT VT : F16VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.hasVInstructionsF32()) 151 for (MVT VT : F32VecVTs) 152 addRegClassForRVV(VT); 153 154 if (Subtarget.hasVInstructionsF64()) 155 for (MVT VT : F64VecVTs) 156 addRegClassForRVV(VT); 157 158 if (Subtarget.useRVVForFixedLengthVectors()) { 159 auto addRegClassForFixedVectors = [this](MVT VT) { 160 MVT ContainerVT = getContainerForFixedLengthVector(VT); 161 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 162 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 163 addRegisterClass(VT, TRI.getRegClass(RCID)); 164 }; 165 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 166 if (useRVVForFixedLengthVectorVT(VT)) 167 addRegClassForFixedVectors(VT); 168 169 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 170 if (useRVVForFixedLengthVectorVT(VT)) 171 addRegClassForFixedVectors(VT); 172 } 173 } 174 175 // Compute derived properties from the register classes. 176 computeRegisterProperties(STI.getRegisterInfo()); 177 178 setStackPointerRegisterToSaveRestore(RISCV::X2); 179 180 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT, 181 MVT::i1, Promote); 182 183 // TODO: add all necessary setOperationAction calls. 184 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 185 186 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 187 setOperationAction(ISD::BR_CC, XLenVT, Expand); 188 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 189 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 190 191 setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand); 192 193 setOperationAction(ISD::VASTART, MVT::Other, Custom); 194 setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand); 195 196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 197 198 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 199 200 if (!Subtarget.hasStdExtZbb()) 201 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 202 203 if (Subtarget.is64Bit()) { 204 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 205 206 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 207 MVT::i32, Custom); 208 209 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 210 MVT::i32, Custom); 211 } else { 212 setLibcallName( 213 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 214 nullptr); 215 setLibcallName(RTLIB::MULO_I64, nullptr); 216 } 217 218 if (!Subtarget.hasStdExtM()) { 219 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 220 ISD::SREM, ISD::UREM}, 221 XLenVT, Expand); 222 } else { 223 if (Subtarget.is64Bit()) { 224 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 225 226 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 227 {MVT::i8, MVT::i16, MVT::i32}, Custom); 228 } else { 229 setOperationAction(ISD::MUL, MVT::i64, Custom); 230 } 231 } 232 233 setOperationAction( 234 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 235 Expand); 236 237 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 238 Custom); 239 240 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 241 Subtarget.hasStdExtZbkb()) { 242 if (Subtarget.is64Bit()) 243 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 244 } else { 245 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 246 } 247 248 if (Subtarget.hasStdExtZbp()) { 249 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 250 // more combining. 251 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 252 253 // BSWAP i8 doesn't exist. 254 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 255 256 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 257 258 if (Subtarget.is64Bit()) 259 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 260 } else { 261 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 262 // pattern match it directly in isel. 263 setOperationAction(ISD::BSWAP, XLenVT, 264 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 265 ? Legal 266 : Expand); 267 // Zbkb can use rev8+brev8 to implement bitreverse. 268 setOperationAction(ISD::BITREVERSE, XLenVT, 269 Subtarget.hasStdExtZbkb() ? Custom : Expand); 270 } 271 272 if (Subtarget.hasStdExtZbb()) { 273 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 274 Legal); 275 276 if (Subtarget.is64Bit()) 277 setOperationAction( 278 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 279 MVT::i32, Custom); 280 } else { 281 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 282 283 if (Subtarget.is64Bit()) 284 setOperationAction(ISD::ABS, MVT::i32, Custom); 285 } 286 287 if (Subtarget.hasStdExtZbt()) { 288 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 289 setOperationAction(ISD::SELECT, XLenVT, Legal); 290 291 if (Subtarget.is64Bit()) 292 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 293 } else { 294 setOperationAction(ISD::SELECT, XLenVT, Custom); 295 } 296 297 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 298 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 299 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 300 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 301 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 302 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 303 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 304 305 static const ISD::CondCode FPCCToExpand[] = { 306 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 307 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 308 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 309 310 static const ISD::NodeType FPOpToExpand[] = { 311 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 312 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 313 314 if (Subtarget.hasStdExtZfh()) 315 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 316 317 if (Subtarget.hasStdExtZfh()) { 318 for (auto NT : FPLegalNodeTypes) 319 setOperationAction(NT, MVT::f16, Legal); 320 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 321 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 322 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 323 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 324 setOperationAction(ISD::SELECT, MVT::f16, Custom); 325 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 326 327 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 328 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 329 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 330 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 331 ISD::FLOG2, ISD::FLOG10}, 332 MVT::f16, Promote); 333 334 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 335 // complete support for all operations in LegalizeDAG. 336 337 // We need to custom promote this. 338 if (Subtarget.is64Bit()) 339 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 340 } 341 342 if (Subtarget.hasStdExtF()) { 343 for (auto NT : FPLegalNodeTypes) 344 setOperationAction(NT, MVT::f32, Legal); 345 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 346 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 347 setOperationAction(ISD::SELECT, MVT::f32, Custom); 348 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 349 for (auto Op : FPOpToExpand) 350 setOperationAction(Op, MVT::f32, Expand); 351 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 352 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 353 } 354 355 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 356 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 357 358 if (Subtarget.hasStdExtD()) { 359 for (auto NT : FPLegalNodeTypes) 360 setOperationAction(NT, MVT::f64, Legal); 361 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 362 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 363 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 364 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 365 setOperationAction(ISD::SELECT, MVT::f64, Custom); 366 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 367 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 368 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 369 for (auto Op : FPOpToExpand) 370 setOperationAction(Op, MVT::f64, Expand); 371 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 372 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 373 } 374 375 if (Subtarget.is64Bit()) 376 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 377 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 378 MVT::i32, Custom); 379 380 if (Subtarget.hasStdExtF()) { 381 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 382 Custom); 383 384 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 385 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 386 XLenVT, Legal); 387 388 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 389 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 390 } 391 392 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 393 ISD::JumpTable}, 394 XLenVT, Custom); 395 396 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 397 398 if (Subtarget.is64Bit()) 399 setOperationAction(ISD::Constant, MVT::i64, Custom); 400 401 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 402 // Unfortunately this can't be determined just from the ISA naming string. 403 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 404 Subtarget.is64Bit() ? Legal : Custom); 405 406 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 407 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 408 if (Subtarget.is64Bit()) 409 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 410 411 if (Subtarget.hasStdExtA()) { 412 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 413 setMinCmpXchgSizeInBits(32); 414 } else { 415 setMaxAtomicSizeInBitsSupported(0); 416 } 417 418 setBooleanContents(ZeroOrOneBooleanContent); 419 420 if (Subtarget.hasVInstructions()) { 421 setBooleanVectorContents(ZeroOrOneBooleanContent); 422 423 setOperationAction(ISD::VSCALE, XLenVT, Custom); 424 425 // RVV intrinsics may have illegal operands. 426 // We also need to custom legalize vmv.x.s. 427 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 428 {MVT::i8, MVT::i16}, Custom); 429 if (Subtarget.is64Bit()) 430 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 431 else 432 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 433 MVT::i64, Custom); 434 435 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 436 MVT::Other, Custom); 437 438 static const unsigned IntegerVPOps[] = { 439 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 440 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 441 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 442 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 443 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 444 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 445 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 446 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 447 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 448 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 449 450 static const unsigned FloatingPointVPOps[] = { 451 ISD::VP_FADD, ISD::VP_FSUB, 452 ISD::VP_FMUL, ISD::VP_FDIV, 453 ISD::VP_FNEG, ISD::VP_FMA, 454 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 455 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 456 ISD::VP_MERGE, ISD::VP_SELECT, 457 ISD::VP_SITOFP, ISD::VP_UITOFP, 458 ISD::VP_SETCC, ISD::VP_FP_ROUND, 459 ISD::VP_FP_EXTEND}; 460 461 if (!Subtarget.is64Bit()) { 462 // We must custom-lower certain vXi64 operations on RV32 due to the vector 463 // element type being illegal. 464 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 465 MVT::i64, Custom); 466 467 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 468 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 469 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 470 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 471 MVT::i64, Custom); 472 473 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 474 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 475 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 476 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 477 MVT::i64, Custom); 478 } 479 480 for (MVT VT : BoolVecVTs) { 481 if (!isTypeLegal(VT)) 482 continue; 483 484 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 485 486 // Mask VTs are custom-expanded into a series of standard nodes 487 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 488 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 489 VT, Custom); 490 491 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 492 Custom); 493 494 setOperationAction(ISD::SELECT, VT, Custom); 495 setOperationAction( 496 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 497 Expand); 498 499 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 500 501 setOperationAction( 502 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 503 Custom); 504 505 setOperationAction( 506 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 507 Custom); 508 509 // RVV has native int->float & float->int conversions where the 510 // element type sizes are within one power-of-two of each other. Any 511 // wider distances between type sizes have to be lowered as sequences 512 // which progressively narrow the gap in stages. 513 setOperationAction( 514 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 515 VT, Custom); 516 517 // Expand all extending loads to types larger than this, and truncating 518 // stores from types larger than this. 519 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 520 setTruncStoreAction(OtherVT, VT, Expand); 521 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 522 VT, Expand); 523 } 524 525 setOperationAction( 526 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 527 Custom); 528 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 529 530 setOperationPromotedToType( 531 ISD::VECTOR_SPLICE, VT, 532 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount())); 533 } 534 535 for (MVT VT : IntVecVTs) { 536 if (!isTypeLegal(VT)) 537 continue; 538 539 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 540 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 541 542 // Vectors implement MULHS/MULHU. 543 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 544 545 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 546 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 547 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 548 549 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 550 Legal); 551 552 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 553 554 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 555 Expand); 556 557 setOperationAction(ISD::BSWAP, VT, Expand); 558 559 // Custom-lower extensions and truncations from/to mask types. 560 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 561 VT, Custom); 562 563 // RVV has native int->float & float->int conversions where the 564 // element type sizes are within one power-of-two of each other. Any 565 // wider distances between type sizes have to be lowered as sequences 566 // which progressively narrow the gap in stages. 567 setOperationAction( 568 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 569 VT, Custom); 570 571 setOperationAction( 572 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 573 574 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 575 // nodes which truncate by one power of two at a time. 576 setOperationAction(ISD::TRUNCATE, VT, Custom); 577 578 // Custom-lower insert/extract operations to simplify patterns. 579 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 580 Custom); 581 582 // Custom-lower reduction operations to set up the corresponding custom 583 // nodes' operands. 584 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 585 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 586 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 587 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 588 VT, Custom); 589 590 setOperationAction(IntegerVPOps, VT, Custom); 591 592 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 593 594 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 595 VT, Custom); 596 597 setOperationAction( 598 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 599 Custom); 600 601 setOperationAction( 602 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 603 VT, Custom); 604 605 setOperationAction(ISD::SELECT, VT, Custom); 606 setOperationAction(ISD::SELECT_CC, VT, Expand); 607 608 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 609 610 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 611 setTruncStoreAction(VT, OtherVT, Expand); 612 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 613 VT, Expand); 614 } 615 616 // Splice 617 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 618 619 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 620 // type that can represent the value exactly. 621 if (VT.getVectorElementType() != MVT::i64) { 622 MVT FloatEltVT = 623 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 624 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 625 if (isTypeLegal(FloatVT)) { 626 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 627 Custom); 628 } 629 } 630 } 631 632 // Expand various CCs to best match the RVV ISA, which natively supports UNE 633 // but no other unordered comparisons, and supports all ordered comparisons 634 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 635 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 636 // and we pattern-match those back to the "original", swapping operands once 637 // more. This way we catch both operations and both "vf" and "fv" forms with 638 // fewer patterns. 639 static const ISD::CondCode VFPCCToExpand[] = { 640 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 641 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 642 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 643 }; 644 645 // Sets common operation actions on RVV floating-point vector types. 646 const auto SetCommonVFPActions = [&](MVT VT) { 647 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 648 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 649 // sizes are within one power-of-two of each other. Therefore conversions 650 // between vXf16 and vXf64 must be lowered as sequences which convert via 651 // vXf32. 652 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 653 // Custom-lower insert/extract operations to simplify patterns. 654 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 655 Custom); 656 // Expand various condition codes (explained above). 657 setCondCodeAction(VFPCCToExpand, VT, Expand); 658 659 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 660 661 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 662 VT, Custom); 663 664 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 665 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 666 VT, Custom); 667 668 // Expand FP operations that need libcalls. 669 setOperationAction(ISD::FREM, VT, Expand); 670 setOperationAction(ISD::FPOW, VT, Expand); 671 setOperationAction(ISD::FCOS, VT, Expand); 672 setOperationAction(ISD::FSIN, VT, Expand); 673 setOperationAction(ISD::FSINCOS, VT, Expand); 674 setOperationAction(ISD::FEXP, VT, Expand); 675 setOperationAction(ISD::FEXP2, VT, Expand); 676 setOperationAction(ISD::FLOG, VT, Expand); 677 setOperationAction(ISD::FLOG2, VT, Expand); 678 setOperationAction(ISD::FLOG10, VT, Expand); 679 setOperationAction(ISD::FRINT, VT, Expand); 680 setOperationAction(ISD::FNEARBYINT, VT, Expand); 681 682 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 683 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 684 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 685 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 686 687 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 688 689 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 690 691 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 692 VT, Custom); 693 694 setOperationAction( 695 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 696 Custom); 697 698 setOperationAction(ISD::SELECT, VT, Custom); 699 setOperationAction(ISD::SELECT_CC, VT, Expand); 700 701 setOperationAction( 702 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 703 VT, Custom); 704 705 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 706 707 setOperationAction(FloatingPointVPOps, VT, Custom); 708 }; 709 710 // Sets common extload/truncstore actions on RVV floating-point vector 711 // types. 712 const auto SetCommonVFPExtLoadTruncStoreActions = 713 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 714 for (auto SmallVT : SmallerVTs) { 715 setTruncStoreAction(VT, SmallVT, Expand); 716 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 717 } 718 }; 719 720 if (Subtarget.hasVInstructionsF16()) { 721 for (MVT VT : F16VecVTs) { 722 if (!isTypeLegal(VT)) 723 continue; 724 SetCommonVFPActions(VT); 725 } 726 } 727 728 if (Subtarget.hasVInstructionsF32()) { 729 for (MVT VT : F32VecVTs) { 730 if (!isTypeLegal(VT)) 731 continue; 732 SetCommonVFPActions(VT); 733 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 734 } 735 } 736 737 if (Subtarget.hasVInstructionsF64()) { 738 for (MVT VT : F64VecVTs) { 739 if (!isTypeLegal(VT)) 740 continue; 741 SetCommonVFPActions(VT); 742 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 743 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 744 } 745 } 746 747 if (Subtarget.useRVVForFixedLengthVectors()) { 748 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 749 if (!useRVVForFixedLengthVectorVT(VT)) 750 continue; 751 752 // By default everything must be expanded. 753 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 754 setOperationAction(Op, VT, Expand); 755 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 756 setTruncStoreAction(VT, OtherVT, Expand); 757 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 758 OtherVT, VT, Expand); 759 } 760 761 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 762 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 763 Custom); 764 765 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 766 Custom); 767 768 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 769 VT, Custom); 770 771 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 772 773 setOperationAction(ISD::SETCC, VT, Custom); 774 775 setOperationAction(ISD::SELECT, VT, Custom); 776 777 setOperationAction(ISD::TRUNCATE, VT, Custom); 778 779 setOperationAction(ISD::BITCAST, VT, Custom); 780 781 setOperationAction( 782 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 783 Custom); 784 785 setOperationAction( 786 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 787 Custom); 788 789 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 790 ISD::FP_TO_UINT}, 791 VT, Custom); 792 793 // Operations below are different for between masks and other vectors. 794 if (VT.getVectorElementType() == MVT::i1) { 795 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 796 ISD::OR, ISD::XOR}, 797 VT, Custom); 798 799 setOperationAction( 800 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 801 VT, Custom); 802 continue; 803 } 804 805 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 806 // it before type legalization for i64 vectors on RV32. It will then be 807 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 808 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 809 // improvements first. 810 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 811 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 812 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 813 } 814 815 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 817 818 setOperationAction( 819 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 820 821 setOperationAction( 822 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 823 Custom); 824 825 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 826 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 827 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 828 VT, Custom); 829 830 setOperationAction( 831 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 832 833 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 834 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 835 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 836 837 setOperationAction( 838 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 839 Custom); 840 841 setOperationAction(ISD::VSELECT, VT, Custom); 842 setOperationAction(ISD::SELECT_CC, VT, Expand); 843 844 setOperationAction( 845 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 846 847 // Custom-lower reduction operations to set up the corresponding custom 848 // nodes' operands. 849 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 850 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 851 ISD::VECREDUCE_UMIN}, 852 VT, Custom); 853 854 setOperationAction(IntegerVPOps, VT, Custom); 855 856 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 857 // type that can represent the value exactly. 858 if (VT.getVectorElementType() != MVT::i64) { 859 MVT FloatEltVT = 860 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 861 EVT FloatVT = 862 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 863 if (isTypeLegal(FloatVT)) 864 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 865 Custom); 866 } 867 } 868 869 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 870 if (!useRVVForFixedLengthVectorVT(VT)) 871 continue; 872 873 // By default everything must be expanded. 874 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 875 setOperationAction(Op, VT, Expand); 876 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 877 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 878 setTruncStoreAction(VT, OtherVT, Expand); 879 } 880 881 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 882 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 883 Custom); 884 885 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 886 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 887 ISD::EXTRACT_VECTOR_ELT}, 888 VT, Custom); 889 890 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 891 ISD::MGATHER, ISD::MSCATTER}, 892 VT, Custom); 893 894 setOperationAction( 895 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 896 Custom); 897 898 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 899 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 900 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 901 VT, Custom); 902 903 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 904 905 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 906 VT, Custom); 907 908 for (auto CC : VFPCCToExpand) 909 setCondCodeAction(CC, VT, Expand); 910 911 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 912 setOperationAction(ISD::SELECT_CC, VT, Expand); 913 914 setOperationAction(ISD::BITCAST, VT, Custom); 915 916 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 917 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 918 VT, Custom); 919 920 setOperationAction(FloatingPointVPOps, VT, Custom); 921 } 922 923 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 924 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 925 Custom); 926 if (Subtarget.hasStdExtZfh()) 927 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 928 if (Subtarget.hasStdExtF()) 929 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 930 if (Subtarget.hasStdExtD()) 931 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 932 } 933 } 934 935 // Function alignments. 936 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 937 setMinFunctionAlignment(FunctionAlignment); 938 setPrefFunctionAlignment(FunctionAlignment); 939 940 setMinimumJumpTableEntries(5); 941 942 // Jumps are expensive, compared to logic 943 setJumpIsExpensive(); 944 945 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 946 ISD::OR, ISD::XOR}); 947 if (Subtarget.is64Bit()) 948 setTargetDAGCombine(ISD::SRA); 949 950 if (Subtarget.hasStdExtF()) 951 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 952 953 if (Subtarget.hasStdExtZbp()) 954 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 955 956 if (Subtarget.hasStdExtZbb()) 957 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 958 959 if (Subtarget.hasStdExtZbkb()) 960 setTargetDAGCombine(ISD::BITREVERSE); 961 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 962 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 963 if (Subtarget.hasStdExtF()) 964 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 965 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 966 if (Subtarget.hasVInstructions()) 967 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 968 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 969 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 970 if (Subtarget.useRVVForFixedLengthVectors()) 971 setTargetDAGCombine(ISD::BITCAST); 972 973 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 974 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 975 } 976 977 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 978 LLVMContext &Context, 979 EVT VT) const { 980 if (!VT.isVector()) 981 return getPointerTy(DL); 982 if (Subtarget.hasVInstructions() && 983 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 984 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 985 return VT.changeVectorElementTypeToInteger(); 986 } 987 988 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 989 return Subtarget.getXLenVT(); 990 } 991 992 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 993 const CallInst &I, 994 MachineFunction &MF, 995 unsigned Intrinsic) const { 996 auto &DL = I.getModule()->getDataLayout(); 997 switch (Intrinsic) { 998 default: 999 return false; 1000 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1001 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1002 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1003 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1004 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1005 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1006 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1007 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1008 case Intrinsic::riscv_masked_cmpxchg_i32: 1009 Info.opc = ISD::INTRINSIC_W_CHAIN; 1010 Info.memVT = MVT::i32; 1011 Info.ptrVal = I.getArgOperand(0); 1012 Info.offset = 0; 1013 Info.align = Align(4); 1014 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1015 MachineMemOperand::MOVolatile; 1016 return true; 1017 case Intrinsic::riscv_masked_strided_load: 1018 Info.opc = ISD::INTRINSIC_W_CHAIN; 1019 Info.ptrVal = I.getArgOperand(1); 1020 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1021 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1022 Info.size = MemoryLocation::UnknownSize; 1023 Info.flags |= MachineMemOperand::MOLoad; 1024 return true; 1025 case Intrinsic::riscv_masked_strided_store: 1026 Info.opc = ISD::INTRINSIC_VOID; 1027 Info.ptrVal = I.getArgOperand(1); 1028 Info.memVT = 1029 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1030 Info.align = Align( 1031 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1032 8); 1033 Info.size = MemoryLocation::UnknownSize; 1034 Info.flags |= MachineMemOperand::MOStore; 1035 return true; 1036 case Intrinsic::riscv_seg2_load: 1037 case Intrinsic::riscv_seg3_load: 1038 case Intrinsic::riscv_seg4_load: 1039 case Intrinsic::riscv_seg5_load: 1040 case Intrinsic::riscv_seg6_load: 1041 case Intrinsic::riscv_seg7_load: 1042 case Intrinsic::riscv_seg8_load: 1043 Info.opc = ISD::INTRINSIC_W_CHAIN; 1044 Info.ptrVal = I.getArgOperand(0); 1045 Info.memVT = 1046 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1047 Info.align = 1048 Align(DL.getTypeSizeInBits( 1049 I.getType()->getStructElementType(0)->getScalarType()) / 1050 8); 1051 Info.size = MemoryLocation::UnknownSize; 1052 Info.flags |= MachineMemOperand::MOLoad; 1053 return true; 1054 } 1055 } 1056 1057 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1058 const AddrMode &AM, Type *Ty, 1059 unsigned AS, 1060 Instruction *I) const { 1061 // No global is ever allowed as a base. 1062 if (AM.BaseGV) 1063 return false; 1064 1065 // RVV instructions only support register addressing. 1066 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1067 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1068 1069 // Require a 12-bit signed offset. 1070 if (!isInt<12>(AM.BaseOffs)) 1071 return false; 1072 1073 switch (AM.Scale) { 1074 case 0: // "r+i" or just "i", depending on HasBaseReg. 1075 break; 1076 case 1: 1077 if (!AM.HasBaseReg) // allow "r+i". 1078 break; 1079 return false; // disallow "r+r" or "r+r+i". 1080 default: 1081 return false; 1082 } 1083 1084 return true; 1085 } 1086 1087 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1088 return isInt<12>(Imm); 1089 } 1090 1091 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1092 return isInt<12>(Imm); 1093 } 1094 1095 // On RV32, 64-bit integers are split into their high and low parts and held 1096 // in two different registers, so the trunc is free since the low register can 1097 // just be used. 1098 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1099 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1100 return false; 1101 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1102 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1103 return (SrcBits == 64 && DestBits == 32); 1104 } 1105 1106 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1107 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1108 !SrcVT.isInteger() || !DstVT.isInteger()) 1109 return false; 1110 unsigned SrcBits = SrcVT.getSizeInBits(); 1111 unsigned DestBits = DstVT.getSizeInBits(); 1112 return (SrcBits == 64 && DestBits == 32); 1113 } 1114 1115 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1116 // Zexts are free if they can be combined with a load. 1117 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1118 // poorly with type legalization of compares preferring sext. 1119 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1120 EVT MemVT = LD->getMemoryVT(); 1121 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1122 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1123 LD->getExtensionType() == ISD::ZEXTLOAD)) 1124 return true; 1125 } 1126 1127 return TargetLowering::isZExtFree(Val, VT2); 1128 } 1129 1130 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1131 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1132 } 1133 1134 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1135 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1136 } 1137 1138 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1139 return Subtarget.hasStdExtZbb(); 1140 } 1141 1142 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1143 return Subtarget.hasStdExtZbb(); 1144 } 1145 1146 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1147 EVT VT = Y.getValueType(); 1148 1149 // FIXME: Support vectors once we have tests. 1150 if (VT.isVector()) 1151 return false; 1152 1153 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1154 Subtarget.hasStdExtZbkb()) && 1155 !isa<ConstantSDNode>(Y); 1156 } 1157 1158 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1159 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1160 auto *C = dyn_cast<ConstantSDNode>(Y); 1161 return C && C->getAPIntValue().ule(10); 1162 } 1163 1164 bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1165 Type *Ty) const { 1166 assert(Ty->isIntegerTy()); 1167 1168 unsigned BitSize = Ty->getIntegerBitWidth(); 1169 if (BitSize > Subtarget.getXLen()) 1170 return false; 1171 1172 // Fast path, assume 32-bit immediates are cheap. 1173 int64_t Val = Imm.getSExtValue(); 1174 if (isInt<32>(Val)) 1175 return true; 1176 1177 // A constant pool entry may be more aligned thant he load we're trying to 1178 // replace. If we don't support unaligned scalar mem, prefer the constant 1179 // pool. 1180 // TODO: Can the caller pass down the alignment? 1181 if (!Subtarget.enableUnalignedScalarMem()) 1182 return true; 1183 1184 // Prefer to keep the load if it would require many instructions. 1185 // This uses the same threshold we use for constant pools but doesn't 1186 // check useConstantPoolForLargeInts. 1187 // TODO: Should we keep the load only when we're definitely going to emit a 1188 // constant pool? 1189 1190 RISCVMatInt::InstSeq Seq = 1191 RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits()); 1192 return Seq.size() <= Subtarget.getMaxBuildIntsCost(); 1193 } 1194 1195 bool RISCVTargetLowering:: 1196 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1197 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1198 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1199 SelectionDAG &DAG) const { 1200 // One interesting pattern that we'd want to form is 'bit extract': 1201 // ((1 >> Y) & 1) ==/!= 0 1202 // But we also need to be careful not to try to reverse that fold. 1203 1204 // Is this '((1 >> Y) & 1)'? 1205 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1206 return false; // Keep the 'bit extract' pattern. 1207 1208 // Will this be '((1 >> Y) & 1)' after the transform? 1209 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1210 return true; // Do form the 'bit extract' pattern. 1211 1212 // If 'X' is a constant, and we transform, then we will immediately 1213 // try to undo the fold, thus causing endless combine loop. 1214 // So only do the transform if X is not a constant. This matches the default 1215 // implementation of this function. 1216 return !XC; 1217 } 1218 1219 /// Check if sinking \p I's operands to I's basic block is profitable, because 1220 /// the operands can be folded into a target instruction, e.g. 1221 /// splats of scalars can fold into vector instructions. 1222 bool RISCVTargetLowering::shouldSinkOperands( 1223 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1224 using namespace llvm::PatternMatch; 1225 1226 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1227 return false; 1228 1229 auto IsSinker = [&](Instruction *I, int Operand) { 1230 switch (I->getOpcode()) { 1231 case Instruction::Add: 1232 case Instruction::Sub: 1233 case Instruction::Mul: 1234 case Instruction::And: 1235 case Instruction::Or: 1236 case Instruction::Xor: 1237 case Instruction::FAdd: 1238 case Instruction::FSub: 1239 case Instruction::FMul: 1240 case Instruction::FDiv: 1241 case Instruction::ICmp: 1242 case Instruction::FCmp: 1243 return true; 1244 case Instruction::Shl: 1245 case Instruction::LShr: 1246 case Instruction::AShr: 1247 case Instruction::UDiv: 1248 case Instruction::SDiv: 1249 case Instruction::URem: 1250 case Instruction::SRem: 1251 return Operand == 1; 1252 case Instruction::Call: 1253 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1254 switch (II->getIntrinsicID()) { 1255 case Intrinsic::fma: 1256 case Intrinsic::vp_fma: 1257 return Operand == 0 || Operand == 1; 1258 // FIXME: Our patterns can only match vx/vf instructions when the splat 1259 // it on the RHS, because TableGen doesn't recognize our VP operations 1260 // as commutative. 1261 case Intrinsic::vp_add: 1262 case Intrinsic::vp_mul: 1263 case Intrinsic::vp_and: 1264 case Intrinsic::vp_or: 1265 case Intrinsic::vp_xor: 1266 case Intrinsic::vp_fadd: 1267 case Intrinsic::vp_fmul: 1268 case Intrinsic::vp_shl: 1269 case Intrinsic::vp_lshr: 1270 case Intrinsic::vp_ashr: 1271 case Intrinsic::vp_udiv: 1272 case Intrinsic::vp_sdiv: 1273 case Intrinsic::vp_urem: 1274 case Intrinsic::vp_srem: 1275 return Operand == 1; 1276 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1277 // explicit patterns for both LHS and RHS (as 'vr' versions). 1278 case Intrinsic::vp_sub: 1279 case Intrinsic::vp_fsub: 1280 case Intrinsic::vp_fdiv: 1281 return Operand == 0 || Operand == 1; 1282 default: 1283 return false; 1284 } 1285 } 1286 return false; 1287 default: 1288 return false; 1289 } 1290 }; 1291 1292 for (auto OpIdx : enumerate(I->operands())) { 1293 if (!IsSinker(I, OpIdx.index())) 1294 continue; 1295 1296 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1297 // Make sure we are not already sinking this operand 1298 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1299 continue; 1300 1301 // We are looking for a splat that can be sunk. 1302 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1303 m_Undef(), m_ZeroMask()))) 1304 continue; 1305 1306 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1307 // and vector registers 1308 for (Use &U : Op->uses()) { 1309 Instruction *Insn = cast<Instruction>(U.getUser()); 1310 if (!IsSinker(Insn, U.getOperandNo())) 1311 return false; 1312 } 1313 1314 Ops.push_back(&Op->getOperandUse(0)); 1315 Ops.push_back(&OpIdx.value()); 1316 } 1317 return true; 1318 } 1319 1320 bool RISCVTargetLowering::isOffsetFoldingLegal( 1321 const GlobalAddressSDNode *GA) const { 1322 // In order to maximise the opportunity for common subexpression elimination, 1323 // keep a separate ADD node for the global address offset instead of folding 1324 // it in the global address node. Later peephole optimisations may choose to 1325 // fold it back in when profitable. 1326 return false; 1327 } 1328 1329 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1330 bool ForCodeSize) const { 1331 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1332 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1333 return false; 1334 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1335 return false; 1336 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1337 return false; 1338 return Imm.isZero(); 1339 } 1340 1341 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1342 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1343 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1344 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1345 } 1346 1347 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1348 CallingConv::ID CC, 1349 EVT VT) const { 1350 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1351 // We might still end up using a GPR but that will be decided based on ABI. 1352 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1353 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1354 return MVT::f32; 1355 1356 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1357 } 1358 1359 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1360 CallingConv::ID CC, 1361 EVT VT) const { 1362 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1363 // We might still end up using a GPR but that will be decided based on ABI. 1364 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1365 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1366 return 1; 1367 1368 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1369 } 1370 1371 // Changes the condition code and swaps operands if necessary, so the SetCC 1372 // operation matches one of the comparisons supported directly by branches 1373 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1374 // with 1/-1. 1375 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1376 ISD::CondCode &CC, SelectionDAG &DAG) { 1377 // Convert X > -1 to X >= 0. 1378 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1379 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1380 CC = ISD::SETGE; 1381 return; 1382 } 1383 // Convert X < 1 to 0 >= X. 1384 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1385 RHS = LHS; 1386 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1387 CC = ISD::SETGE; 1388 return; 1389 } 1390 1391 switch (CC) { 1392 default: 1393 break; 1394 case ISD::SETGT: 1395 case ISD::SETLE: 1396 case ISD::SETUGT: 1397 case ISD::SETULE: 1398 CC = ISD::getSetCCSwappedOperands(CC); 1399 std::swap(LHS, RHS); 1400 break; 1401 } 1402 } 1403 1404 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1405 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1406 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1407 if (VT.getVectorElementType() == MVT::i1) 1408 KnownSize *= 8; 1409 1410 switch (KnownSize) { 1411 default: 1412 llvm_unreachable("Invalid LMUL."); 1413 case 8: 1414 return RISCVII::VLMUL::LMUL_F8; 1415 case 16: 1416 return RISCVII::VLMUL::LMUL_F4; 1417 case 32: 1418 return RISCVII::VLMUL::LMUL_F2; 1419 case 64: 1420 return RISCVII::VLMUL::LMUL_1; 1421 case 128: 1422 return RISCVII::VLMUL::LMUL_2; 1423 case 256: 1424 return RISCVII::VLMUL::LMUL_4; 1425 case 512: 1426 return RISCVII::VLMUL::LMUL_8; 1427 } 1428 } 1429 1430 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1431 switch (LMul) { 1432 default: 1433 llvm_unreachable("Invalid LMUL."); 1434 case RISCVII::VLMUL::LMUL_F8: 1435 case RISCVII::VLMUL::LMUL_F4: 1436 case RISCVII::VLMUL::LMUL_F2: 1437 case RISCVII::VLMUL::LMUL_1: 1438 return RISCV::VRRegClassID; 1439 case RISCVII::VLMUL::LMUL_2: 1440 return RISCV::VRM2RegClassID; 1441 case RISCVII::VLMUL::LMUL_4: 1442 return RISCV::VRM4RegClassID; 1443 case RISCVII::VLMUL::LMUL_8: 1444 return RISCV::VRM8RegClassID; 1445 } 1446 } 1447 1448 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1449 RISCVII::VLMUL LMUL = getLMUL(VT); 1450 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1451 LMUL == RISCVII::VLMUL::LMUL_F4 || 1452 LMUL == RISCVII::VLMUL::LMUL_F2 || 1453 LMUL == RISCVII::VLMUL::LMUL_1) { 1454 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1455 "Unexpected subreg numbering"); 1456 return RISCV::sub_vrm1_0 + Index; 1457 } 1458 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1459 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1460 "Unexpected subreg numbering"); 1461 return RISCV::sub_vrm2_0 + Index; 1462 } 1463 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1464 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1465 "Unexpected subreg numbering"); 1466 return RISCV::sub_vrm4_0 + Index; 1467 } 1468 llvm_unreachable("Invalid vector type."); 1469 } 1470 1471 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1472 if (VT.getVectorElementType() == MVT::i1) 1473 return RISCV::VRRegClassID; 1474 return getRegClassIDForLMUL(getLMUL(VT)); 1475 } 1476 1477 // Attempt to decompose a subvector insert/extract between VecVT and 1478 // SubVecVT via subregister indices. Returns the subregister index that 1479 // can perform the subvector insert/extract with the given element index, as 1480 // well as the index corresponding to any leftover subvectors that must be 1481 // further inserted/extracted within the register class for SubVecVT. 1482 std::pair<unsigned, unsigned> 1483 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1484 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1485 const RISCVRegisterInfo *TRI) { 1486 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1487 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1488 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1489 "Register classes not ordered"); 1490 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1491 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1492 // Try to compose a subregister index that takes us from the incoming 1493 // LMUL>1 register class down to the outgoing one. At each step we half 1494 // the LMUL: 1495 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1496 // Note that this is not guaranteed to find a subregister index, such as 1497 // when we are extracting from one VR type to another. 1498 unsigned SubRegIdx = RISCV::NoSubRegister; 1499 for (const unsigned RCID : 1500 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1501 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1502 VecVT = VecVT.getHalfNumVectorElementsVT(); 1503 bool IsHi = 1504 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1505 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1506 getSubregIndexByMVT(VecVT, IsHi)); 1507 if (IsHi) 1508 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1509 } 1510 return {SubRegIdx, InsertExtractIdx}; 1511 } 1512 1513 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1514 // stores for those types. 1515 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1516 return !Subtarget.useRVVForFixedLengthVectors() || 1517 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1518 } 1519 1520 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1521 if (ScalarTy->isPointerTy()) 1522 return true; 1523 1524 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1525 ScalarTy->isIntegerTy(32)) 1526 return true; 1527 1528 if (ScalarTy->isIntegerTy(64)) 1529 return Subtarget.hasVInstructionsI64(); 1530 1531 if (ScalarTy->isHalfTy()) 1532 return Subtarget.hasVInstructionsF16(); 1533 if (ScalarTy->isFloatTy()) 1534 return Subtarget.hasVInstructionsF32(); 1535 if (ScalarTy->isDoubleTy()) 1536 return Subtarget.hasVInstructionsF64(); 1537 1538 return false; 1539 } 1540 1541 static SDValue getVLOperand(SDValue Op) { 1542 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1543 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1544 "Unexpected opcode"); 1545 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1546 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1547 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1548 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1549 if (!II) 1550 return SDValue(); 1551 return Op.getOperand(II->VLOperand + 1 + HasChain); 1552 } 1553 1554 static bool useRVVForFixedLengthVectorVT(MVT VT, 1555 const RISCVSubtarget &Subtarget) { 1556 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1557 if (!Subtarget.useRVVForFixedLengthVectors()) 1558 return false; 1559 1560 // We only support a set of vector types with a consistent maximum fixed size 1561 // across all supported vector element types to avoid legalization issues. 1562 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1563 // fixed-length vector type we support is 1024 bytes. 1564 if (VT.getFixedSizeInBits() > 1024 * 8) 1565 return false; 1566 1567 unsigned MinVLen = Subtarget.getRealMinVLen(); 1568 1569 MVT EltVT = VT.getVectorElementType(); 1570 1571 // Don't use RVV for vectors we cannot scalarize if required. 1572 switch (EltVT.SimpleTy) { 1573 // i1 is supported but has different rules. 1574 default: 1575 return false; 1576 case MVT::i1: 1577 // Masks can only use a single register. 1578 if (VT.getVectorNumElements() > MinVLen) 1579 return false; 1580 MinVLen /= 8; 1581 break; 1582 case MVT::i8: 1583 case MVT::i16: 1584 case MVT::i32: 1585 break; 1586 case MVT::i64: 1587 if (!Subtarget.hasVInstructionsI64()) 1588 return false; 1589 break; 1590 case MVT::f16: 1591 if (!Subtarget.hasVInstructionsF16()) 1592 return false; 1593 break; 1594 case MVT::f32: 1595 if (!Subtarget.hasVInstructionsF32()) 1596 return false; 1597 break; 1598 case MVT::f64: 1599 if (!Subtarget.hasVInstructionsF64()) 1600 return false; 1601 break; 1602 } 1603 1604 // Reject elements larger than ELEN. 1605 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1606 return false; 1607 1608 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1609 // Don't use RVV for types that don't fit. 1610 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1611 return false; 1612 1613 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1614 // the base fixed length RVV support in place. 1615 if (!VT.isPow2VectorType()) 1616 return false; 1617 1618 return true; 1619 } 1620 1621 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1622 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1623 } 1624 1625 // Return the largest legal scalable vector type that matches VT's element type. 1626 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1627 const RISCVSubtarget &Subtarget) { 1628 // This may be called before legal types are setup. 1629 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1630 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1631 "Expected legal fixed length vector!"); 1632 1633 unsigned MinVLen = Subtarget.getRealMinVLen(); 1634 unsigned MaxELen = Subtarget.getELEN(); 1635 1636 MVT EltVT = VT.getVectorElementType(); 1637 switch (EltVT.SimpleTy) { 1638 default: 1639 llvm_unreachable("unexpected element type for RVV container"); 1640 case MVT::i1: 1641 case MVT::i8: 1642 case MVT::i16: 1643 case MVT::i32: 1644 case MVT::i64: 1645 case MVT::f16: 1646 case MVT::f32: 1647 case MVT::f64: { 1648 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1649 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1650 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1651 unsigned NumElts = 1652 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1653 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1654 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1655 return MVT::getScalableVectorVT(EltVT, NumElts); 1656 } 1657 } 1658 } 1659 1660 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1661 const RISCVSubtarget &Subtarget) { 1662 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1663 Subtarget); 1664 } 1665 1666 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1667 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1668 } 1669 1670 // Grow V to consume an entire RVV register. 1671 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1672 const RISCVSubtarget &Subtarget) { 1673 assert(VT.isScalableVector() && 1674 "Expected to convert into a scalable vector!"); 1675 assert(V.getValueType().isFixedLengthVector() && 1676 "Expected a fixed length vector operand!"); 1677 SDLoc DL(V); 1678 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1679 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1680 } 1681 1682 // Shrink V so it's just big enough to maintain a VT's worth of data. 1683 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1684 const RISCVSubtarget &Subtarget) { 1685 assert(VT.isFixedLengthVector() && 1686 "Expected to convert into a fixed length vector!"); 1687 assert(V.getValueType().isScalableVector() && 1688 "Expected a scalable vector operand!"); 1689 SDLoc DL(V); 1690 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1691 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1692 } 1693 1694 /// Return the type of the mask type suitable for masking the provided 1695 /// vector type. This is simply an i1 element type vector of the same 1696 /// (possibly scalable) length. 1697 static MVT getMaskTypeFor(MVT VecVT) { 1698 assert(VecVT.isVector()); 1699 ElementCount EC = VecVT.getVectorElementCount(); 1700 return MVT::getVectorVT(MVT::i1, EC); 1701 } 1702 1703 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1704 /// vector length VL. . 1705 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1706 SelectionDAG &DAG) { 1707 MVT MaskVT = getMaskTypeFor(VecVT); 1708 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1709 } 1710 1711 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1712 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1713 // the vector type that it is contained in. 1714 static std::pair<SDValue, SDValue> 1715 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1716 const RISCVSubtarget &Subtarget) { 1717 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1718 MVT XLenVT = Subtarget.getXLenVT(); 1719 SDValue VL = VecVT.isFixedLengthVector() 1720 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1721 : DAG.getRegister(RISCV::X0, XLenVT); 1722 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1723 return {Mask, VL}; 1724 } 1725 1726 // As above but assuming the given type is a scalable vector type. 1727 static std::pair<SDValue, SDValue> 1728 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1729 const RISCVSubtarget &Subtarget) { 1730 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1731 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1732 } 1733 1734 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1735 // of either is (currently) supported. This can get us into an infinite loop 1736 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1737 // as a ..., etc. 1738 // Until either (or both) of these can reliably lower any node, reporting that 1739 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1740 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1741 // which is not desirable. 1742 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1743 EVT VT, unsigned DefinedValues) const { 1744 return false; 1745 } 1746 1747 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1748 const RISCVSubtarget &Subtarget) { 1749 // RISCV FP-to-int conversions saturate to the destination register size, but 1750 // don't produce 0 for nan. We can use a conversion instruction and fix the 1751 // nan case with a compare and a select. 1752 SDValue Src = Op.getOperand(0); 1753 1754 EVT DstVT = Op.getValueType(); 1755 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1756 1757 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1758 unsigned Opc; 1759 if (SatVT == DstVT) 1760 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1761 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1762 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1763 else 1764 return SDValue(); 1765 // FIXME: Support other SatVTs by clamping before or after the conversion. 1766 1767 SDLoc DL(Op); 1768 SDValue FpToInt = DAG.getNode( 1769 Opc, DL, DstVT, Src, 1770 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1771 1772 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1773 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1774 } 1775 1776 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1777 // and back. Taking care to avoid converting values that are nan or already 1778 // correct. 1779 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1780 // have FRM dependencies modeled yet. 1781 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1782 MVT VT = Op.getSimpleValueType(); 1783 assert(VT.isVector() && "Unexpected type"); 1784 1785 SDLoc DL(Op); 1786 1787 // Freeze the source since we are increasing the number of uses. 1788 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1789 1790 // Truncate to integer and convert back to FP. 1791 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1792 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1793 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1794 1795 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1796 1797 if (Op.getOpcode() == ISD::FCEIL) { 1798 // If the truncated value is the greater than or equal to the original 1799 // value, we've computed the ceil. Otherwise, we went the wrong way and 1800 // need to increase by 1. 1801 // FIXME: This should use a masked operation. Handle here or in isel? 1802 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1803 DAG.getConstantFP(1.0, DL, VT)); 1804 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1805 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1806 } else if (Op.getOpcode() == ISD::FFLOOR) { 1807 // If the truncated value is the less than or equal to the original value, 1808 // we've computed the floor. Otherwise, we went the wrong way and need to 1809 // decrease by 1. 1810 // FIXME: This should use a masked operation. Handle here or in isel? 1811 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1812 DAG.getConstantFP(1.0, DL, VT)); 1813 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1814 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1815 } 1816 1817 // Restore the original sign so that -0.0 is preserved. 1818 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1819 1820 // Determine the largest integer that can be represented exactly. This and 1821 // values larger than it don't have any fractional bits so don't need to 1822 // be converted. 1823 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1824 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1825 APFloat MaxVal = APFloat(FltSem); 1826 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1827 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1828 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1829 1830 // If abs(Src) was larger than MaxVal or nan, keep it. 1831 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1832 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1833 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1834 } 1835 1836 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1837 // This mode isn't supported in vector hardware on RISCV. But as long as we 1838 // aren't compiling with trapping math, we can emulate this with 1839 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1840 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1841 // dependencies modeled yet. 1842 // FIXME: Use masked operations to avoid final merge. 1843 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1844 MVT VT = Op.getSimpleValueType(); 1845 assert(VT.isVector() && "Unexpected type"); 1846 1847 SDLoc DL(Op); 1848 1849 // Freeze the source since we are increasing the number of uses. 1850 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1851 1852 // We do the conversion on the absolute value and fix the sign at the end. 1853 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1854 1855 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1856 bool Ignored; 1857 APFloat Point5Pred = APFloat(0.5f); 1858 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1859 Point5Pred.next(/*nextDown*/ true); 1860 1861 // Add the adjustment. 1862 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1863 DAG.getConstantFP(Point5Pred, DL, VT)); 1864 1865 // Truncate to integer and convert back to fp. 1866 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1867 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1868 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1869 1870 // Restore the original sign. 1871 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1872 1873 // Determine the largest integer that can be represented exactly. This and 1874 // values larger than it don't have any fractional bits so don't need to 1875 // be converted. 1876 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1877 APFloat MaxVal = APFloat(FltSem); 1878 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1879 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1880 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1881 1882 // If abs(Src) was larger than MaxVal or nan, keep it. 1883 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1884 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1885 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1886 } 1887 1888 struct VIDSequence { 1889 int64_t StepNumerator; 1890 unsigned StepDenominator; 1891 int64_t Addend; 1892 }; 1893 1894 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1895 // to the (non-zero) step S and start value X. This can be then lowered as the 1896 // RVV sequence (VID * S) + X, for example. 1897 // The step S is represented as an integer numerator divided by a positive 1898 // denominator. Note that the implementation currently only identifies 1899 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1900 // cannot detect 2/3, for example. 1901 // Note that this method will also match potentially unappealing index 1902 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1903 // determine whether this is worth generating code for. 1904 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1905 unsigned NumElts = Op.getNumOperands(); 1906 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1907 if (!Op.getValueType().isInteger()) 1908 return None; 1909 1910 Optional<unsigned> SeqStepDenom; 1911 Optional<int64_t> SeqStepNum, SeqAddend; 1912 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1913 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1914 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1915 // Assume undef elements match the sequence; we just have to be careful 1916 // when interpolating across them. 1917 if (Op.getOperand(Idx).isUndef()) 1918 continue; 1919 // The BUILD_VECTOR must be all constants. 1920 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1921 return None; 1922 1923 uint64_t Val = Op.getConstantOperandVal(Idx) & 1924 maskTrailingOnes<uint64_t>(EltSizeInBits); 1925 1926 if (PrevElt) { 1927 // Calculate the step since the last non-undef element, and ensure 1928 // it's consistent across the entire sequence. 1929 unsigned IdxDiff = Idx - PrevElt->second; 1930 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1931 1932 // A zero-value value difference means that we're somewhere in the middle 1933 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1934 // step change before evaluating the sequence. 1935 if (ValDiff == 0) 1936 continue; 1937 1938 int64_t Remainder = ValDiff % IdxDiff; 1939 // Normalize the step if it's greater than 1. 1940 if (Remainder != ValDiff) { 1941 // The difference must cleanly divide the element span. 1942 if (Remainder != 0) 1943 return None; 1944 ValDiff /= IdxDiff; 1945 IdxDiff = 1; 1946 } 1947 1948 if (!SeqStepNum) 1949 SeqStepNum = ValDiff; 1950 else if (ValDiff != SeqStepNum) 1951 return None; 1952 1953 if (!SeqStepDenom) 1954 SeqStepDenom = IdxDiff; 1955 else if (IdxDiff != *SeqStepDenom) 1956 return None; 1957 } 1958 1959 // Record this non-undef element for later. 1960 if (!PrevElt || PrevElt->first != Val) 1961 PrevElt = std::make_pair(Val, Idx); 1962 } 1963 1964 // We need to have logged a step for this to count as a legal index sequence. 1965 if (!SeqStepNum || !SeqStepDenom) 1966 return None; 1967 1968 // Loop back through the sequence and validate elements we might have skipped 1969 // while waiting for a valid step. While doing this, log any sequence addend. 1970 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1971 if (Op.getOperand(Idx).isUndef()) 1972 continue; 1973 uint64_t Val = Op.getConstantOperandVal(Idx) & 1974 maskTrailingOnes<uint64_t>(EltSizeInBits); 1975 uint64_t ExpectedVal = 1976 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1977 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1978 if (!SeqAddend) 1979 SeqAddend = Addend; 1980 else if (Addend != SeqAddend) 1981 return None; 1982 } 1983 1984 assert(SeqAddend && "Must have an addend if we have a step"); 1985 1986 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1987 } 1988 1989 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1990 // and lower it as a VRGATHER_VX_VL from the source vector. 1991 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1992 SelectionDAG &DAG, 1993 const RISCVSubtarget &Subtarget) { 1994 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1995 return SDValue(); 1996 SDValue Vec = SplatVal.getOperand(0); 1997 // Only perform this optimization on vectors of the same size for simplicity. 1998 // Don't perform this optimization for i1 vectors. 1999 // FIXME: Support i1 vectors, maybe by promoting to i8? 2000 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 2001 return SDValue(); 2002 SDValue Idx = SplatVal.getOperand(1); 2003 // The index must be a legal type. 2004 if (Idx.getValueType() != Subtarget.getXLenVT()) 2005 return SDValue(); 2006 2007 MVT ContainerVT = VT; 2008 if (VT.isFixedLengthVector()) { 2009 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2010 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2011 } 2012 2013 SDValue Mask, VL; 2014 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2015 2016 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2017 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 2018 2019 if (!VT.isFixedLengthVector()) 2020 return Gather; 2021 2022 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2023 } 2024 2025 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2026 const RISCVSubtarget &Subtarget) { 2027 MVT VT = Op.getSimpleValueType(); 2028 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2029 2030 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2031 2032 SDLoc DL(Op); 2033 SDValue Mask, VL; 2034 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2035 2036 MVT XLenVT = Subtarget.getXLenVT(); 2037 unsigned NumElts = Op.getNumOperands(); 2038 2039 if (VT.getVectorElementType() == MVT::i1) { 2040 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2041 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2042 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2043 } 2044 2045 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2046 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2047 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2048 } 2049 2050 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2051 // scalar integer chunks whose bit-width depends on the number of mask 2052 // bits and XLEN. 2053 // First, determine the most appropriate scalar integer type to use. This 2054 // is at most XLenVT, but may be shrunk to a smaller vector element type 2055 // according to the size of the final vector - use i8 chunks rather than 2056 // XLenVT if we're producing a v8i1. This results in more consistent 2057 // codegen across RV32 and RV64. 2058 unsigned NumViaIntegerBits = 2059 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2060 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2061 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2062 // If we have to use more than one INSERT_VECTOR_ELT then this 2063 // optimization is likely to increase code size; avoid peforming it in 2064 // such a case. We can use a load from a constant pool in this case. 2065 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2066 return SDValue(); 2067 // Now we can create our integer vector type. Note that it may be larger 2068 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2069 MVT IntegerViaVecVT = 2070 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2071 divideCeil(NumElts, NumViaIntegerBits)); 2072 2073 uint64_t Bits = 0; 2074 unsigned BitPos = 0, IntegerEltIdx = 0; 2075 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2076 2077 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2078 // Once we accumulate enough bits to fill our scalar type, insert into 2079 // our vector and clear our accumulated data. 2080 if (I != 0 && I % NumViaIntegerBits == 0) { 2081 if (NumViaIntegerBits <= 32) 2082 Bits = SignExtend64<32>(Bits); 2083 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2084 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2085 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2086 Bits = 0; 2087 BitPos = 0; 2088 IntegerEltIdx++; 2089 } 2090 SDValue V = Op.getOperand(I); 2091 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2092 Bits |= ((uint64_t)BitValue << BitPos); 2093 } 2094 2095 // Insert the (remaining) scalar value into position in our integer 2096 // vector type. 2097 if (NumViaIntegerBits <= 32) 2098 Bits = SignExtend64<32>(Bits); 2099 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2100 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2101 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2102 2103 if (NumElts < NumViaIntegerBits) { 2104 // If we're producing a smaller vector than our minimum legal integer 2105 // type, bitcast to the equivalent (known-legal) mask type, and extract 2106 // our final mask. 2107 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2108 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2109 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2110 DAG.getConstant(0, DL, XLenVT)); 2111 } else { 2112 // Else we must have produced an integer type with the same size as the 2113 // mask type; bitcast for the final result. 2114 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2115 Vec = DAG.getBitcast(VT, Vec); 2116 } 2117 2118 return Vec; 2119 } 2120 2121 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2122 // vector type, we have a legal equivalently-sized i8 type, so we can use 2123 // that. 2124 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2125 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2126 2127 SDValue WideVec; 2128 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2129 // For a splat, perform a scalar truncate before creating the wider 2130 // vector. 2131 assert(Splat.getValueType() == XLenVT && 2132 "Unexpected type for i1 splat value"); 2133 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2134 DAG.getConstant(1, DL, XLenVT)); 2135 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2136 } else { 2137 SmallVector<SDValue, 8> Ops(Op->op_values()); 2138 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2139 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2140 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2141 } 2142 2143 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2144 } 2145 2146 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2147 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2148 return Gather; 2149 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2150 : RISCVISD::VMV_V_X_VL; 2151 Splat = 2152 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2153 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2154 } 2155 2156 // Try and match index sequences, which we can lower to the vid instruction 2157 // with optional modifications. An all-undef vector is matched by 2158 // getSplatValue, above. 2159 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2160 int64_t StepNumerator = SimpleVID->StepNumerator; 2161 unsigned StepDenominator = SimpleVID->StepDenominator; 2162 int64_t Addend = SimpleVID->Addend; 2163 2164 assert(StepNumerator != 0 && "Invalid step"); 2165 bool Negate = false; 2166 int64_t SplatStepVal = StepNumerator; 2167 unsigned StepOpcode = ISD::MUL; 2168 if (StepNumerator != 1) { 2169 if (isPowerOf2_64(std::abs(StepNumerator))) { 2170 Negate = StepNumerator < 0; 2171 StepOpcode = ISD::SHL; 2172 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2173 } 2174 } 2175 2176 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2177 // threshold since it's the immediate value many RVV instructions accept. 2178 // There is no vmul.vi instruction so ensure multiply constant can fit in 2179 // a single addi instruction. 2180 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2181 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2182 isPowerOf2_32(StepDenominator) && 2183 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2184 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2185 // Convert right out of the scalable type so we can use standard ISD 2186 // nodes for the rest of the computation. If we used scalable types with 2187 // these, we'd lose the fixed-length vector info and generate worse 2188 // vsetvli code. 2189 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2190 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2191 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2192 SDValue SplatStep = DAG.getSplatBuildVector( 2193 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2194 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2195 } 2196 if (StepDenominator != 1) { 2197 SDValue SplatStep = DAG.getSplatBuildVector( 2198 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2199 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2200 } 2201 if (Addend != 0 || Negate) { 2202 SDValue SplatAddend = DAG.getSplatBuildVector( 2203 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2204 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2205 } 2206 return VID; 2207 } 2208 } 2209 2210 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2211 // when re-interpreted as a vector with a larger element type. For example, 2212 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2213 // could be instead splat as 2214 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2215 // TODO: This optimization could also work on non-constant splats, but it 2216 // would require bit-manipulation instructions to construct the splat value. 2217 SmallVector<SDValue> Sequence; 2218 unsigned EltBitSize = VT.getScalarSizeInBits(); 2219 const auto *BV = cast<BuildVectorSDNode>(Op); 2220 if (VT.isInteger() && EltBitSize < 64 && 2221 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2222 BV->getRepeatedSequence(Sequence) && 2223 (Sequence.size() * EltBitSize) <= 64) { 2224 unsigned SeqLen = Sequence.size(); 2225 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2226 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2227 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2228 ViaIntVT == MVT::i64) && 2229 "Unexpected sequence type"); 2230 2231 unsigned EltIdx = 0; 2232 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2233 uint64_t SplatValue = 0; 2234 // Construct the amalgamated value which can be splatted as this larger 2235 // vector type. 2236 for (const auto &SeqV : Sequence) { 2237 if (!SeqV.isUndef()) 2238 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2239 << (EltIdx * EltBitSize)); 2240 EltIdx++; 2241 } 2242 2243 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2244 // achieve better constant materializion. 2245 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2246 SplatValue = SignExtend64<32>(SplatValue); 2247 2248 // Since we can't introduce illegal i64 types at this stage, we can only 2249 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2250 // way we can use RVV instructions to splat. 2251 assert((ViaIntVT.bitsLE(XLenVT) || 2252 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2253 "Unexpected bitcast sequence"); 2254 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2255 SDValue ViaVL = 2256 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2257 MVT ViaContainerVT = 2258 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2259 SDValue Splat = 2260 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2261 DAG.getUNDEF(ViaContainerVT), 2262 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2263 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2264 return DAG.getBitcast(VT, Splat); 2265 } 2266 } 2267 2268 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2269 // which constitute a large proportion of the elements. In such cases we can 2270 // splat a vector with the dominant element and make up the shortfall with 2271 // INSERT_VECTOR_ELTs. 2272 // Note that this includes vectors of 2 elements by association. The 2273 // upper-most element is the "dominant" one, allowing us to use a splat to 2274 // "insert" the upper element, and an insert of the lower element at position 2275 // 0, which improves codegen. 2276 SDValue DominantValue; 2277 unsigned MostCommonCount = 0; 2278 DenseMap<SDValue, unsigned> ValueCounts; 2279 unsigned NumUndefElts = 2280 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2281 2282 // Track the number of scalar loads we know we'd be inserting, estimated as 2283 // any non-zero floating-point constant. Other kinds of element are either 2284 // already in registers or are materialized on demand. The threshold at which 2285 // a vector load is more desirable than several scalar materializion and 2286 // vector-insertion instructions is not known. 2287 unsigned NumScalarLoads = 0; 2288 2289 for (SDValue V : Op->op_values()) { 2290 if (V.isUndef()) 2291 continue; 2292 2293 ValueCounts.insert(std::make_pair(V, 0)); 2294 unsigned &Count = ValueCounts[V]; 2295 2296 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2297 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2298 2299 // Is this value dominant? In case of a tie, prefer the highest element as 2300 // it's cheaper to insert near the beginning of a vector than it is at the 2301 // end. 2302 if (++Count >= MostCommonCount) { 2303 DominantValue = V; 2304 MostCommonCount = Count; 2305 } 2306 } 2307 2308 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2309 unsigned NumDefElts = NumElts - NumUndefElts; 2310 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2311 2312 // Don't perform this optimization when optimizing for size, since 2313 // materializing elements and inserting them tends to cause code bloat. 2314 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2315 ((MostCommonCount > DominantValueCountThreshold) || 2316 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2317 // Start by splatting the most common element. 2318 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2319 2320 DenseSet<SDValue> Processed{DominantValue}; 2321 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2322 for (const auto &OpIdx : enumerate(Op->ops())) { 2323 const SDValue &V = OpIdx.value(); 2324 if (V.isUndef() || !Processed.insert(V).second) 2325 continue; 2326 if (ValueCounts[V] == 1) { 2327 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2328 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2329 } else { 2330 // Blend in all instances of this value using a VSELECT, using a 2331 // mask where each bit signals whether that element is the one 2332 // we're after. 2333 SmallVector<SDValue> Ops; 2334 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2335 return DAG.getConstant(V == V1, DL, XLenVT); 2336 }); 2337 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2338 DAG.getBuildVector(SelMaskTy, DL, Ops), 2339 DAG.getSplatBuildVector(VT, DL, V), Vec); 2340 } 2341 } 2342 2343 return Vec; 2344 } 2345 2346 return SDValue(); 2347 } 2348 2349 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2350 SDValue Lo, SDValue Hi, SDValue VL, 2351 SelectionDAG &DAG) { 2352 if (!Passthru) 2353 Passthru = DAG.getUNDEF(VT); 2354 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2355 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2356 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2357 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2358 // node in order to try and match RVV vector/scalar instructions. 2359 if ((LoC >> 31) == HiC) 2360 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2361 2362 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2363 // vmv.v.x whose EEW = 32 to lower it. 2364 auto *Const = dyn_cast<ConstantSDNode>(VL); 2365 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2366 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2367 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2368 // access the subtarget here now. 2369 auto InterVec = DAG.getNode( 2370 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2371 DAG.getRegister(RISCV::X0, MVT::i32)); 2372 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2373 } 2374 } 2375 2376 // Fall back to a stack store and stride x0 vector load. 2377 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2378 Hi, VL); 2379 } 2380 2381 // Called by type legalization to handle splat of i64 on RV32. 2382 // FIXME: We can optimize this when the type has sign or zero bits in one 2383 // of the halves. 2384 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2385 SDValue Scalar, SDValue VL, 2386 SelectionDAG &DAG) { 2387 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2388 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2389 DAG.getConstant(0, DL, MVT::i32)); 2390 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2391 DAG.getConstant(1, DL, MVT::i32)); 2392 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2393 } 2394 2395 // This function lowers a splat of a scalar operand Splat with the vector 2396 // length VL. It ensures the final sequence is type legal, which is useful when 2397 // lowering a splat after type legalization. 2398 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2399 MVT VT, SDLoc DL, SelectionDAG &DAG, 2400 const RISCVSubtarget &Subtarget) { 2401 bool HasPassthru = Passthru && !Passthru.isUndef(); 2402 if (!HasPassthru && !Passthru) 2403 Passthru = DAG.getUNDEF(VT); 2404 if (VT.isFloatingPoint()) { 2405 // If VL is 1, we could use vfmv.s.f. 2406 if (isOneConstant(VL)) 2407 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2408 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2409 } 2410 2411 MVT XLenVT = Subtarget.getXLenVT(); 2412 2413 // Simplest case is that the operand needs to be promoted to XLenVT. 2414 if (Scalar.getValueType().bitsLE(XLenVT)) { 2415 // If the operand is a constant, sign extend to increase our chances 2416 // of being able to use a .vi instruction. ANY_EXTEND would become a 2417 // a zero extend and the simm5 check in isel would fail. 2418 // FIXME: Should we ignore the upper bits in isel instead? 2419 unsigned ExtOpc = 2420 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2421 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2422 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2423 // If VL is 1 and the scalar value won't benefit from immediate, we could 2424 // use vmv.s.x. 2425 if (isOneConstant(VL) && 2426 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2427 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2428 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2429 } 2430 2431 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2432 "Unexpected scalar for splat lowering!"); 2433 2434 if (isOneConstant(VL) && isNullConstant(Scalar)) 2435 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2436 DAG.getConstant(0, DL, XLenVT), VL); 2437 2438 // Otherwise use the more complicated splatting algorithm. 2439 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2440 } 2441 2442 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2443 const RISCVSubtarget &Subtarget) { 2444 // We need to be able to widen elements to the next larger integer type. 2445 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2446 return false; 2447 2448 int Size = Mask.size(); 2449 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2450 2451 int Srcs[] = {-1, -1}; 2452 for (int i = 0; i != Size; ++i) { 2453 // Ignore undef elements. 2454 if (Mask[i] < 0) 2455 continue; 2456 2457 // Is this an even or odd element. 2458 int Pol = i % 2; 2459 2460 // Ensure we consistently use the same source for this element polarity. 2461 int Src = Mask[i] / Size; 2462 if (Srcs[Pol] < 0) 2463 Srcs[Pol] = Src; 2464 if (Srcs[Pol] != Src) 2465 return false; 2466 2467 // Make sure the element within the source is appropriate for this element 2468 // in the destination. 2469 int Elt = Mask[i] % Size; 2470 if (Elt != i / 2) 2471 return false; 2472 } 2473 2474 // We need to find a source for each polarity and they can't be the same. 2475 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2476 return false; 2477 2478 // Swap the sources if the second source was in the even polarity. 2479 SwapSources = Srcs[0] > Srcs[1]; 2480 2481 return true; 2482 } 2483 2484 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2485 /// and then extract the original number of elements from the rotated result. 2486 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2487 /// returned rotation amount is for a rotate right, where elements move from 2488 /// higher elements to lower elements. \p LoSrc indicates the first source 2489 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2490 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2491 /// 0 or 1 if a rotation is found. 2492 /// 2493 /// NOTE: We talk about rotate to the right which matches how bit shift and 2494 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2495 /// and the table below write vectors with the lowest elements on the left. 2496 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2497 int Size = Mask.size(); 2498 2499 // We need to detect various ways of spelling a rotation: 2500 // [11, 12, 13, 14, 15, 0, 1, 2] 2501 // [-1, 12, 13, 14, -1, -1, 1, -1] 2502 // [-1, -1, -1, -1, -1, -1, 1, 2] 2503 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2504 // [-1, 4, 5, 6, -1, -1, 9, -1] 2505 // [-1, 4, 5, 6, -1, -1, -1, -1] 2506 int Rotation = 0; 2507 LoSrc = -1; 2508 HiSrc = -1; 2509 for (int i = 0; i != Size; ++i) { 2510 int M = Mask[i]; 2511 if (M < 0) 2512 continue; 2513 2514 // Determine where a rotate vector would have started. 2515 int StartIdx = i - (M % Size); 2516 // The identity rotation isn't interesting, stop. 2517 if (StartIdx == 0) 2518 return -1; 2519 2520 // If we found the tail of a vector the rotation must be the missing 2521 // front. If we found the head of a vector, it must be how much of the 2522 // head. 2523 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2524 2525 if (Rotation == 0) 2526 Rotation = CandidateRotation; 2527 else if (Rotation != CandidateRotation) 2528 // The rotations don't match, so we can't match this mask. 2529 return -1; 2530 2531 // Compute which value this mask is pointing at. 2532 int MaskSrc = M < Size ? 0 : 1; 2533 2534 // Compute which of the two target values this index should be assigned to. 2535 // This reflects whether the high elements are remaining or the low elemnts 2536 // are remaining. 2537 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2538 2539 // Either set up this value if we've not encountered it before, or check 2540 // that it remains consistent. 2541 if (TargetSrc < 0) 2542 TargetSrc = MaskSrc; 2543 else if (TargetSrc != MaskSrc) 2544 // This may be a rotation, but it pulls from the inputs in some 2545 // unsupported interleaving. 2546 return -1; 2547 } 2548 2549 // Check that we successfully analyzed the mask, and normalize the results. 2550 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2551 assert((LoSrc >= 0 || HiSrc >= 0) && 2552 "Failed to find a rotated input vector!"); 2553 2554 return Rotation; 2555 } 2556 2557 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2558 const RISCVSubtarget &Subtarget) { 2559 SDValue V1 = Op.getOperand(0); 2560 SDValue V2 = Op.getOperand(1); 2561 SDLoc DL(Op); 2562 MVT XLenVT = Subtarget.getXLenVT(); 2563 MVT VT = Op.getSimpleValueType(); 2564 unsigned NumElts = VT.getVectorNumElements(); 2565 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2566 2567 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2568 2569 SDValue TrueMask, VL; 2570 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2571 2572 if (SVN->isSplat()) { 2573 const int Lane = SVN->getSplatIndex(); 2574 if (Lane >= 0) { 2575 MVT SVT = VT.getVectorElementType(); 2576 2577 // Turn splatted vector load into a strided load with an X0 stride. 2578 SDValue V = V1; 2579 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2580 // with undef. 2581 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2582 int Offset = Lane; 2583 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2584 int OpElements = 2585 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2586 V = V.getOperand(Offset / OpElements); 2587 Offset %= OpElements; 2588 } 2589 2590 // We need to ensure the load isn't atomic or volatile. 2591 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2592 auto *Ld = cast<LoadSDNode>(V); 2593 Offset *= SVT.getStoreSize(); 2594 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2595 TypeSize::Fixed(Offset), DL); 2596 2597 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2598 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2599 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2600 SDValue IntID = 2601 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2602 SDValue Ops[] = {Ld->getChain(), 2603 IntID, 2604 DAG.getUNDEF(ContainerVT), 2605 NewAddr, 2606 DAG.getRegister(RISCV::X0, XLenVT), 2607 VL}; 2608 SDValue NewLoad = DAG.getMemIntrinsicNode( 2609 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2610 DAG.getMachineFunction().getMachineMemOperand( 2611 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2612 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2613 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2614 } 2615 2616 // Otherwise use a scalar load and splat. This will give the best 2617 // opportunity to fold a splat into the operation. ISel can turn it into 2618 // the x0 strided load if we aren't able to fold away the select. 2619 if (SVT.isFloatingPoint()) 2620 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2621 Ld->getPointerInfo().getWithOffset(Offset), 2622 Ld->getOriginalAlign(), 2623 Ld->getMemOperand()->getFlags()); 2624 else 2625 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2626 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2627 Ld->getOriginalAlign(), 2628 Ld->getMemOperand()->getFlags()); 2629 DAG.makeEquivalentMemoryOrdering(Ld, V); 2630 2631 unsigned Opc = 2632 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2633 SDValue Splat = 2634 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2635 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2636 } 2637 2638 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2639 assert(Lane < (int)NumElts && "Unexpected lane!"); 2640 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2641 V1, DAG.getConstant(Lane, DL, XLenVT), 2642 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2643 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2644 } 2645 } 2646 2647 ArrayRef<int> Mask = SVN->getMask(); 2648 2649 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2650 // be undef which can be handled with a single SLIDEDOWN/UP. 2651 int LoSrc, HiSrc; 2652 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2653 if (Rotation > 0) { 2654 SDValue LoV, HiV; 2655 if (LoSrc >= 0) { 2656 LoV = LoSrc == 0 ? V1 : V2; 2657 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2658 } 2659 if (HiSrc >= 0) { 2660 HiV = HiSrc == 0 ? V1 : V2; 2661 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2662 } 2663 2664 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2665 // to slide LoV up by (NumElts - Rotation). 2666 unsigned InvRotate = NumElts - Rotation; 2667 2668 SDValue Res = DAG.getUNDEF(ContainerVT); 2669 if (HiV) { 2670 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2671 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2672 // causes multiple vsetvlis in some test cases such as lowering 2673 // reduce.mul 2674 SDValue DownVL = VL; 2675 if (LoV) 2676 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2677 Res = 2678 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2679 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2680 } 2681 if (LoV) 2682 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2683 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2684 2685 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2686 } 2687 2688 // Detect an interleave shuffle and lower to 2689 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2690 bool SwapSources; 2691 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2692 // Swap sources if needed. 2693 if (SwapSources) 2694 std::swap(V1, V2); 2695 2696 // Extract the lower half of the vectors. 2697 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2698 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2699 DAG.getConstant(0, DL, XLenVT)); 2700 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2701 DAG.getConstant(0, DL, XLenVT)); 2702 2703 // Double the element width and halve the number of elements in an int type. 2704 unsigned EltBits = VT.getScalarSizeInBits(); 2705 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2706 MVT WideIntVT = 2707 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2708 // Convert this to a scalable vector. We need to base this on the 2709 // destination size to ensure there's always a type with a smaller LMUL. 2710 MVT WideIntContainerVT = 2711 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2712 2713 // Convert sources to scalable vectors with the same element count as the 2714 // larger type. 2715 MVT HalfContainerVT = MVT::getVectorVT( 2716 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2717 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2718 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2719 2720 // Cast sources to integer. 2721 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2722 MVT IntHalfVT = 2723 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2724 V1 = DAG.getBitcast(IntHalfVT, V1); 2725 V2 = DAG.getBitcast(IntHalfVT, V2); 2726 2727 // Freeze V2 since we use it twice and we need to be sure that the add and 2728 // multiply see the same value. 2729 V2 = DAG.getFreeze(V2); 2730 2731 // Recreate TrueMask using the widened type's element count. 2732 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2733 2734 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2735 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2736 V2, TrueMask, VL); 2737 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2738 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2739 DAG.getUNDEF(IntHalfVT), 2740 DAG.getAllOnesConstant(DL, XLenVT)); 2741 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2742 V2, Multiplier, TrueMask, VL); 2743 // Add the new copies to our previous addition giving us 2^eltbits copies of 2744 // V2. This is equivalent to shifting V2 left by eltbits. This should 2745 // combine with the vwmulu.vv above to form vwmaccu.vv. 2746 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2747 TrueMask, VL); 2748 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2749 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2750 // vector VT. 2751 ContainerVT = 2752 MVT::getVectorVT(VT.getVectorElementType(), 2753 WideIntContainerVT.getVectorElementCount() * 2); 2754 Add = DAG.getBitcast(ContainerVT, Add); 2755 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2756 } 2757 2758 // Detect shuffles which can be re-expressed as vector selects; these are 2759 // shuffles in which each element in the destination is taken from an element 2760 // at the corresponding index in either source vectors. 2761 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2762 int MaskIndex = MaskIdx.value(); 2763 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2764 }); 2765 2766 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2767 2768 SmallVector<SDValue> MaskVals; 2769 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2770 // merged with a second vrgather. 2771 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2772 2773 // By default we preserve the original operand order, and use a mask to 2774 // select LHS as true and RHS as false. However, since RVV vector selects may 2775 // feature splats but only on the LHS, we may choose to invert our mask and 2776 // instead select between RHS and LHS. 2777 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2778 bool InvertMask = IsSelect == SwapOps; 2779 2780 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2781 // half. 2782 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2783 2784 // Now construct the mask that will be used by the vselect or blended 2785 // vrgather operation. For vrgathers, construct the appropriate indices into 2786 // each vector. 2787 for (int MaskIndex : Mask) { 2788 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2789 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2790 if (!IsSelect) { 2791 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2792 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2793 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2794 : DAG.getUNDEF(XLenVT)); 2795 GatherIndicesRHS.push_back( 2796 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2797 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2798 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2799 ++LHSIndexCounts[MaskIndex]; 2800 if (!IsLHSOrUndefIndex) 2801 ++RHSIndexCounts[MaskIndex - NumElts]; 2802 } 2803 } 2804 2805 if (SwapOps) { 2806 std::swap(V1, V2); 2807 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2808 } 2809 2810 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2811 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2812 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2813 2814 if (IsSelect) 2815 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2816 2817 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2818 // On such a large vector we're unable to use i8 as the index type. 2819 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2820 // may involve vector splitting if we're already at LMUL=8, or our 2821 // user-supplied maximum fixed-length LMUL. 2822 return SDValue(); 2823 } 2824 2825 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2826 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2827 MVT IndexVT = VT.changeTypeToInteger(); 2828 // Since we can't introduce illegal index types at this stage, use i16 and 2829 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2830 // than XLenVT. 2831 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2832 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2833 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2834 } 2835 2836 MVT IndexContainerVT = 2837 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2838 2839 SDValue Gather; 2840 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2841 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2842 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2843 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2844 Subtarget); 2845 } else { 2846 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2847 // If only one index is used, we can use a "splat" vrgather. 2848 // TODO: We can splat the most-common index and fix-up any stragglers, if 2849 // that's beneficial. 2850 if (LHSIndexCounts.size() == 1) { 2851 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2852 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2853 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2854 DAG.getUNDEF(ContainerVT), VL); 2855 } else { 2856 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2857 LHSIndices = 2858 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2859 2860 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2861 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2862 } 2863 } 2864 2865 // If a second vector operand is used by this shuffle, blend it in with an 2866 // additional vrgather. 2867 if (!V2.isUndef()) { 2868 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2869 2870 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2871 SelectMask = 2872 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2873 2874 // If only one index is used, we can use a "splat" vrgather. 2875 // TODO: We can splat the most-common index and fix-up any stragglers, if 2876 // that's beneficial. 2877 if (RHSIndexCounts.size() == 1) { 2878 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2879 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2880 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2881 Gather, VL); 2882 } else { 2883 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2884 RHSIndices = 2885 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2886 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2887 SelectMask, Gather, VL); 2888 } 2889 } 2890 2891 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2892 } 2893 2894 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2895 // Support splats for any type. These should type legalize well. 2896 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2897 return true; 2898 2899 // Only support legal VTs for other shuffles for now. 2900 if (!isTypeLegal(VT)) 2901 return false; 2902 2903 MVT SVT = VT.getSimpleVT(); 2904 2905 bool SwapSources; 2906 int LoSrc, HiSrc; 2907 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2908 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2909 } 2910 2911 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2912 // the exponent. 2913 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2914 MVT VT = Op.getSimpleValueType(); 2915 unsigned EltSize = VT.getScalarSizeInBits(); 2916 SDValue Src = Op.getOperand(0); 2917 SDLoc DL(Op); 2918 2919 // We need a FP type that can represent the value. 2920 // TODO: Use f16 for i8 when possible? 2921 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2922 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2923 2924 // Legal types should have been checked in the RISCVTargetLowering 2925 // constructor. 2926 // TODO: Splitting may make sense in some cases. 2927 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2928 "Expected legal float type!"); 2929 2930 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2931 // The trailing zero count is equal to log2 of this single bit value. 2932 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2933 SDValue Neg = 2934 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2935 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2936 } 2937 2938 // We have a legal FP type, convert to it. 2939 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2940 // Bitcast to integer and shift the exponent to the LSB. 2941 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2942 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2943 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2944 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2945 DAG.getConstant(ShiftAmt, DL, IntVT)); 2946 // Truncate back to original type to allow vnsrl. 2947 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2948 // The exponent contains log2 of the value in biased form. 2949 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2950 2951 // For trailing zeros, we just need to subtract the bias. 2952 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2953 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2954 DAG.getConstant(ExponentBias, DL, VT)); 2955 2956 // For leading zeros, we need to remove the bias and convert from log2 to 2957 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2958 unsigned Adjust = ExponentBias + (EltSize - 1); 2959 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2960 } 2961 2962 // While RVV has alignment restrictions, we should always be able to load as a 2963 // legal equivalently-sized byte-typed vector instead. This method is 2964 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2965 // the load is already correctly-aligned, it returns SDValue(). 2966 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2967 SelectionDAG &DAG) const { 2968 auto *Load = cast<LoadSDNode>(Op); 2969 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2970 2971 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2972 Load->getMemoryVT(), 2973 *Load->getMemOperand())) 2974 return SDValue(); 2975 2976 SDLoc DL(Op); 2977 MVT VT = Op.getSimpleValueType(); 2978 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2979 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2980 "Unexpected unaligned RVV load type"); 2981 MVT NewVT = 2982 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2983 assert(NewVT.isValid() && 2984 "Expecting equally-sized RVV vector types to be legal"); 2985 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2986 Load->getPointerInfo(), Load->getOriginalAlign(), 2987 Load->getMemOperand()->getFlags()); 2988 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2989 } 2990 2991 // While RVV has alignment restrictions, we should always be able to store as a 2992 // legal equivalently-sized byte-typed vector instead. This method is 2993 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2994 // returns SDValue() if the store is already correctly aligned. 2995 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2996 SelectionDAG &DAG) const { 2997 auto *Store = cast<StoreSDNode>(Op); 2998 assert(Store && Store->getValue().getValueType().isVector() && 2999 "Expected vector store"); 3000 3001 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3002 Store->getMemoryVT(), 3003 *Store->getMemOperand())) 3004 return SDValue(); 3005 3006 SDLoc DL(Op); 3007 SDValue StoredVal = Store->getValue(); 3008 MVT VT = StoredVal.getSimpleValueType(); 3009 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3010 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3011 "Unexpected unaligned RVV store type"); 3012 MVT NewVT = 3013 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3014 assert(NewVT.isValid() && 3015 "Expecting equally-sized RVV vector types to be legal"); 3016 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3017 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3018 Store->getPointerInfo(), Store->getOriginalAlign(), 3019 Store->getMemOperand()->getFlags()); 3020 } 3021 3022 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 3023 const RISCVSubtarget &Subtarget) { 3024 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 3025 3026 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 3027 3028 // All simm32 constants should be handled by isel. 3029 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 3030 // this check redundant, but small immediates are common so this check 3031 // should have better compile time. 3032 if (isInt<32>(Imm)) 3033 return Op; 3034 3035 // We only need to cost the immediate, if constant pool lowering is enabled. 3036 if (!Subtarget.useConstantPoolForLargeInts()) 3037 return Op; 3038 3039 RISCVMatInt::InstSeq Seq = 3040 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3041 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3042 return Op; 3043 3044 // Expand to a constant pool using the default expansion code. 3045 return SDValue(); 3046 } 3047 3048 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3049 SelectionDAG &DAG) const { 3050 switch (Op.getOpcode()) { 3051 default: 3052 report_fatal_error("unimplemented operand"); 3053 case ISD::GlobalAddress: 3054 return lowerGlobalAddress(Op, DAG); 3055 case ISD::BlockAddress: 3056 return lowerBlockAddress(Op, DAG); 3057 case ISD::ConstantPool: 3058 return lowerConstantPool(Op, DAG); 3059 case ISD::JumpTable: 3060 return lowerJumpTable(Op, DAG); 3061 case ISD::GlobalTLSAddress: 3062 return lowerGlobalTLSAddress(Op, DAG); 3063 case ISD::Constant: 3064 return lowerConstant(Op, DAG, Subtarget); 3065 case ISD::SELECT: 3066 return lowerSELECT(Op, DAG); 3067 case ISD::BRCOND: 3068 return lowerBRCOND(Op, DAG); 3069 case ISD::VASTART: 3070 return lowerVASTART(Op, DAG); 3071 case ISD::FRAMEADDR: 3072 return lowerFRAMEADDR(Op, DAG); 3073 case ISD::RETURNADDR: 3074 return lowerRETURNADDR(Op, DAG); 3075 case ISD::SHL_PARTS: 3076 return lowerShiftLeftParts(Op, DAG); 3077 case ISD::SRA_PARTS: 3078 return lowerShiftRightParts(Op, DAG, true); 3079 case ISD::SRL_PARTS: 3080 return lowerShiftRightParts(Op, DAG, false); 3081 case ISD::BITCAST: { 3082 SDLoc DL(Op); 3083 EVT VT = Op.getValueType(); 3084 SDValue Op0 = Op.getOperand(0); 3085 EVT Op0VT = Op0.getValueType(); 3086 MVT XLenVT = Subtarget.getXLenVT(); 3087 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3088 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3089 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3090 return FPConv; 3091 } 3092 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3093 Subtarget.hasStdExtF()) { 3094 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3095 SDValue FPConv = 3096 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3097 return FPConv; 3098 } 3099 3100 // Consider other scalar<->scalar casts as legal if the types are legal. 3101 // Otherwise expand them. 3102 if (!VT.isVector() && !Op0VT.isVector()) { 3103 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3104 return Op; 3105 return SDValue(); 3106 } 3107 3108 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3109 "Unexpected types"); 3110 3111 if (VT.isFixedLengthVector()) { 3112 // We can handle fixed length vector bitcasts with a simple replacement 3113 // in isel. 3114 if (Op0VT.isFixedLengthVector()) 3115 return Op; 3116 // When bitcasting from scalar to fixed-length vector, insert the scalar 3117 // into a one-element vector of the result type, and perform a vector 3118 // bitcast. 3119 if (!Op0VT.isVector()) { 3120 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3121 if (!isTypeLegal(BVT)) 3122 return SDValue(); 3123 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3124 DAG.getUNDEF(BVT), Op0, 3125 DAG.getConstant(0, DL, XLenVT))); 3126 } 3127 return SDValue(); 3128 } 3129 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3130 // thus: bitcast the vector to a one-element vector type whose element type 3131 // is the same as the result type, and extract the first element. 3132 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3133 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3134 if (!isTypeLegal(BVT)) 3135 return SDValue(); 3136 SDValue BVec = DAG.getBitcast(BVT, Op0); 3137 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3138 DAG.getConstant(0, DL, XLenVT)); 3139 } 3140 return SDValue(); 3141 } 3142 case ISD::INTRINSIC_WO_CHAIN: 3143 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3144 case ISD::INTRINSIC_W_CHAIN: 3145 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3146 case ISD::INTRINSIC_VOID: 3147 return LowerINTRINSIC_VOID(Op, DAG); 3148 case ISD::BSWAP: 3149 case ISD::BITREVERSE: { 3150 MVT VT = Op.getSimpleValueType(); 3151 SDLoc DL(Op); 3152 if (Subtarget.hasStdExtZbp()) { 3153 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3154 // Start with the maximum immediate value which is the bitwidth - 1. 3155 unsigned Imm = VT.getSizeInBits() - 1; 3156 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3157 if (Op.getOpcode() == ISD::BSWAP) 3158 Imm &= ~0x7U; 3159 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3160 DAG.getConstant(Imm, DL, VT)); 3161 } 3162 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3163 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3164 // Expand bitreverse to a bswap(rev8) followed by brev8. 3165 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3166 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3167 // as brev8 by an isel pattern. 3168 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3169 DAG.getConstant(7, DL, VT)); 3170 } 3171 case ISD::FSHL: 3172 case ISD::FSHR: { 3173 MVT VT = Op.getSimpleValueType(); 3174 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3175 SDLoc DL(Op); 3176 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3177 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3178 // accidentally setting the extra bit. 3179 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3180 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3181 DAG.getConstant(ShAmtWidth, DL, VT)); 3182 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3183 // instruction use different orders. fshl will return its first operand for 3184 // shift of zero, fshr will return its second operand. fsl and fsr both 3185 // return rs1 so the ISD nodes need to have different operand orders. 3186 // Shift amount is in rs2. 3187 SDValue Op0 = Op.getOperand(0); 3188 SDValue Op1 = Op.getOperand(1); 3189 unsigned Opc = RISCVISD::FSL; 3190 if (Op.getOpcode() == ISD::FSHR) { 3191 std::swap(Op0, Op1); 3192 Opc = RISCVISD::FSR; 3193 } 3194 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3195 } 3196 case ISD::TRUNCATE: 3197 // Only custom-lower vector truncates 3198 if (!Op.getSimpleValueType().isVector()) 3199 return Op; 3200 return lowerVectorTruncLike(Op, DAG); 3201 case ISD::ANY_EXTEND: 3202 case ISD::ZERO_EXTEND: 3203 if (Op.getOperand(0).getValueType().isVector() && 3204 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3205 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3206 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3207 case ISD::SIGN_EXTEND: 3208 if (Op.getOperand(0).getValueType().isVector() && 3209 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3210 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3211 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3212 case ISD::SPLAT_VECTOR_PARTS: 3213 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3214 case ISD::INSERT_VECTOR_ELT: 3215 return lowerINSERT_VECTOR_ELT(Op, DAG); 3216 case ISD::EXTRACT_VECTOR_ELT: 3217 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3218 case ISD::VSCALE: { 3219 MVT VT = Op.getSimpleValueType(); 3220 SDLoc DL(Op); 3221 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3222 // We define our scalable vector types for lmul=1 to use a 64 bit known 3223 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3224 // vscale as VLENB / 8. 3225 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3226 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3227 report_fatal_error("Support for VLEN==32 is incomplete."); 3228 // We assume VLENB is a multiple of 8. We manually choose the best shift 3229 // here because SimplifyDemandedBits isn't always able to simplify it. 3230 uint64_t Val = Op.getConstantOperandVal(0); 3231 if (isPowerOf2_64(Val)) { 3232 uint64_t Log2 = Log2_64(Val); 3233 if (Log2 < 3) 3234 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3235 DAG.getConstant(3 - Log2, DL, VT)); 3236 if (Log2 > 3) 3237 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3238 DAG.getConstant(Log2 - 3, DL, VT)); 3239 return VLENB; 3240 } 3241 // If the multiplier is a multiple of 8, scale it down to avoid needing 3242 // to shift the VLENB value. 3243 if ((Val % 8) == 0) 3244 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3245 DAG.getConstant(Val / 8, DL, VT)); 3246 3247 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3248 DAG.getConstant(3, DL, VT)); 3249 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3250 } 3251 case ISD::FPOWI: { 3252 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3253 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3254 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3255 Op.getOperand(1).getValueType() == MVT::i32) { 3256 SDLoc DL(Op); 3257 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3258 SDValue Powi = 3259 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3260 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3261 DAG.getIntPtrConstant(0, DL)); 3262 } 3263 return SDValue(); 3264 } 3265 case ISD::FP_EXTEND: 3266 case ISD::FP_ROUND: 3267 if (!Op.getValueType().isVector()) 3268 return Op; 3269 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3270 case ISD::FP_TO_SINT: 3271 case ISD::FP_TO_UINT: 3272 case ISD::SINT_TO_FP: 3273 case ISD::UINT_TO_FP: { 3274 // RVV can only do fp<->int conversions to types half/double the size as 3275 // the source. We custom-lower any conversions that do two hops into 3276 // sequences. 3277 MVT VT = Op.getSimpleValueType(); 3278 if (!VT.isVector()) 3279 return Op; 3280 SDLoc DL(Op); 3281 SDValue Src = Op.getOperand(0); 3282 MVT EltVT = VT.getVectorElementType(); 3283 MVT SrcVT = Src.getSimpleValueType(); 3284 MVT SrcEltVT = SrcVT.getVectorElementType(); 3285 unsigned EltSize = EltVT.getSizeInBits(); 3286 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3287 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3288 "Unexpected vector element types"); 3289 3290 bool IsInt2FP = SrcEltVT.isInteger(); 3291 // Widening conversions 3292 if (EltSize > (2 * SrcEltSize)) { 3293 if (IsInt2FP) { 3294 // Do a regular integer sign/zero extension then convert to float. 3295 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3296 VT.getVectorElementCount()); 3297 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3298 ? ISD::ZERO_EXTEND 3299 : ISD::SIGN_EXTEND; 3300 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3301 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3302 } 3303 // FP2Int 3304 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3305 // Do one doubling fp_extend then complete the operation by converting 3306 // to int. 3307 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3308 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3309 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3310 } 3311 3312 // Narrowing conversions 3313 if (SrcEltSize > (2 * EltSize)) { 3314 if (IsInt2FP) { 3315 // One narrowing int_to_fp, then an fp_round. 3316 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3317 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3318 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3319 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3320 } 3321 // FP2Int 3322 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3323 // representable by the integer, the result is poison. 3324 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3325 VT.getVectorElementCount()); 3326 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3327 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3328 } 3329 3330 // Scalable vectors can exit here. Patterns will handle equally-sized 3331 // conversions halving/doubling ones. 3332 if (!VT.isFixedLengthVector()) 3333 return Op; 3334 3335 // For fixed-length vectors we lower to a custom "VL" node. 3336 unsigned RVVOpc = 0; 3337 switch (Op.getOpcode()) { 3338 default: 3339 llvm_unreachable("Impossible opcode"); 3340 case ISD::FP_TO_SINT: 3341 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3342 break; 3343 case ISD::FP_TO_UINT: 3344 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3345 break; 3346 case ISD::SINT_TO_FP: 3347 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3348 break; 3349 case ISD::UINT_TO_FP: 3350 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3351 break; 3352 } 3353 3354 MVT ContainerVT, SrcContainerVT; 3355 // Derive the reference container type from the larger vector type. 3356 if (SrcEltSize > EltSize) { 3357 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3358 ContainerVT = 3359 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3360 } else { 3361 ContainerVT = getContainerForFixedLengthVector(VT); 3362 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3363 } 3364 3365 SDValue Mask, VL; 3366 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3367 3368 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3369 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3370 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3371 } 3372 case ISD::FP_TO_SINT_SAT: 3373 case ISD::FP_TO_UINT_SAT: 3374 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3375 case ISD::FTRUNC: 3376 case ISD::FCEIL: 3377 case ISD::FFLOOR: 3378 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3379 case ISD::FROUND: 3380 return lowerFROUND(Op, DAG); 3381 case ISD::VECREDUCE_ADD: 3382 case ISD::VECREDUCE_UMAX: 3383 case ISD::VECREDUCE_SMAX: 3384 case ISD::VECREDUCE_UMIN: 3385 case ISD::VECREDUCE_SMIN: 3386 return lowerVECREDUCE(Op, DAG); 3387 case ISD::VECREDUCE_AND: 3388 case ISD::VECREDUCE_OR: 3389 case ISD::VECREDUCE_XOR: 3390 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3391 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3392 return lowerVECREDUCE(Op, DAG); 3393 case ISD::VECREDUCE_FADD: 3394 case ISD::VECREDUCE_SEQ_FADD: 3395 case ISD::VECREDUCE_FMIN: 3396 case ISD::VECREDUCE_FMAX: 3397 return lowerFPVECREDUCE(Op, DAG); 3398 case ISD::VP_REDUCE_ADD: 3399 case ISD::VP_REDUCE_UMAX: 3400 case ISD::VP_REDUCE_SMAX: 3401 case ISD::VP_REDUCE_UMIN: 3402 case ISD::VP_REDUCE_SMIN: 3403 case ISD::VP_REDUCE_FADD: 3404 case ISD::VP_REDUCE_SEQ_FADD: 3405 case ISD::VP_REDUCE_FMIN: 3406 case ISD::VP_REDUCE_FMAX: 3407 return lowerVPREDUCE(Op, DAG); 3408 case ISD::VP_REDUCE_AND: 3409 case ISD::VP_REDUCE_OR: 3410 case ISD::VP_REDUCE_XOR: 3411 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3412 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3413 return lowerVPREDUCE(Op, DAG); 3414 case ISD::INSERT_SUBVECTOR: 3415 return lowerINSERT_SUBVECTOR(Op, DAG); 3416 case ISD::EXTRACT_SUBVECTOR: 3417 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3418 case ISD::STEP_VECTOR: 3419 return lowerSTEP_VECTOR(Op, DAG); 3420 case ISD::VECTOR_REVERSE: 3421 return lowerVECTOR_REVERSE(Op, DAG); 3422 case ISD::VECTOR_SPLICE: 3423 return lowerVECTOR_SPLICE(Op, DAG); 3424 case ISD::BUILD_VECTOR: 3425 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3426 case ISD::SPLAT_VECTOR: 3427 if (Op.getValueType().getVectorElementType() == MVT::i1) 3428 return lowerVectorMaskSplat(Op, DAG); 3429 return SDValue(); 3430 case ISD::VECTOR_SHUFFLE: 3431 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3432 case ISD::CONCAT_VECTORS: { 3433 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3434 // better than going through the stack, as the default expansion does. 3435 SDLoc DL(Op); 3436 MVT VT = Op.getSimpleValueType(); 3437 unsigned NumOpElts = 3438 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3439 SDValue Vec = DAG.getUNDEF(VT); 3440 for (const auto &OpIdx : enumerate(Op->ops())) { 3441 SDValue SubVec = OpIdx.value(); 3442 // Don't insert undef subvectors. 3443 if (SubVec.isUndef()) 3444 continue; 3445 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3446 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3447 } 3448 return Vec; 3449 } 3450 case ISD::LOAD: 3451 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3452 return V; 3453 if (Op.getValueType().isFixedLengthVector()) 3454 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3455 return Op; 3456 case ISD::STORE: 3457 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3458 return V; 3459 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3460 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3461 return Op; 3462 case ISD::MLOAD: 3463 case ISD::VP_LOAD: 3464 return lowerMaskedLoad(Op, DAG); 3465 case ISD::MSTORE: 3466 case ISD::VP_STORE: 3467 return lowerMaskedStore(Op, DAG); 3468 case ISD::SETCC: 3469 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3470 case ISD::ADD: 3471 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3472 case ISD::SUB: 3473 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3474 case ISD::MUL: 3475 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3476 case ISD::MULHS: 3477 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3478 case ISD::MULHU: 3479 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3480 case ISD::AND: 3481 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3482 RISCVISD::AND_VL); 3483 case ISD::OR: 3484 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3485 RISCVISD::OR_VL); 3486 case ISD::XOR: 3487 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3488 RISCVISD::XOR_VL); 3489 case ISD::SDIV: 3490 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3491 case ISD::SREM: 3492 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3493 case ISD::UDIV: 3494 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3495 case ISD::UREM: 3496 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3497 case ISD::SHL: 3498 case ISD::SRA: 3499 case ISD::SRL: 3500 if (Op.getSimpleValueType().isFixedLengthVector()) 3501 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3502 // This can be called for an i32 shift amount that needs to be promoted. 3503 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3504 "Unexpected custom legalisation"); 3505 return SDValue(); 3506 case ISD::SADDSAT: 3507 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3508 case ISD::UADDSAT: 3509 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3510 case ISD::SSUBSAT: 3511 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3512 case ISD::USUBSAT: 3513 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3514 case ISD::FADD: 3515 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3516 case ISD::FSUB: 3517 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3518 case ISD::FMUL: 3519 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3520 case ISD::FDIV: 3521 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3522 case ISD::FNEG: 3523 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3524 case ISD::FABS: 3525 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3526 case ISD::FSQRT: 3527 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3528 case ISD::FMA: 3529 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3530 case ISD::SMIN: 3531 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3532 case ISD::SMAX: 3533 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3534 case ISD::UMIN: 3535 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3536 case ISD::UMAX: 3537 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3538 case ISD::FMINNUM: 3539 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3540 case ISD::FMAXNUM: 3541 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3542 case ISD::ABS: 3543 return lowerABS(Op, DAG); 3544 case ISD::CTLZ_ZERO_UNDEF: 3545 case ISD::CTTZ_ZERO_UNDEF: 3546 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3547 case ISD::VSELECT: 3548 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3549 case ISD::FCOPYSIGN: 3550 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3551 case ISD::MGATHER: 3552 case ISD::VP_GATHER: 3553 return lowerMaskedGather(Op, DAG); 3554 case ISD::MSCATTER: 3555 case ISD::VP_SCATTER: 3556 return lowerMaskedScatter(Op, DAG); 3557 case ISD::FLT_ROUNDS_: 3558 return lowerGET_ROUNDING(Op, DAG); 3559 case ISD::SET_ROUNDING: 3560 return lowerSET_ROUNDING(Op, DAG); 3561 case ISD::EH_DWARF_CFA: 3562 return lowerEH_DWARF_CFA(Op, DAG); 3563 case ISD::VP_SELECT: 3564 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3565 case ISD::VP_MERGE: 3566 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3567 case ISD::VP_ADD: 3568 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3569 case ISD::VP_SUB: 3570 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3571 case ISD::VP_MUL: 3572 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3573 case ISD::VP_SDIV: 3574 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3575 case ISD::VP_UDIV: 3576 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3577 case ISD::VP_SREM: 3578 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3579 case ISD::VP_UREM: 3580 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3581 case ISD::VP_AND: 3582 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3583 case ISD::VP_OR: 3584 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3585 case ISD::VP_XOR: 3586 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3587 case ISD::VP_ASHR: 3588 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3589 case ISD::VP_LSHR: 3590 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3591 case ISD::VP_SHL: 3592 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3593 case ISD::VP_FADD: 3594 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3595 case ISD::VP_FSUB: 3596 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3597 case ISD::VP_FMUL: 3598 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3599 case ISD::VP_FDIV: 3600 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3601 case ISD::VP_FNEG: 3602 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3603 case ISD::VP_FMA: 3604 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3605 case ISD::VP_SIGN_EXTEND: 3606 case ISD::VP_ZERO_EXTEND: 3607 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3608 return lowerVPExtMaskOp(Op, DAG); 3609 return lowerVPOp(Op, DAG, 3610 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3611 ? RISCVISD::VSEXT_VL 3612 : RISCVISD::VZEXT_VL); 3613 case ISD::VP_TRUNCATE: 3614 return lowerVectorTruncLike(Op, DAG); 3615 case ISD::VP_FP_EXTEND: 3616 case ISD::VP_FP_ROUND: 3617 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3618 case ISD::VP_FPTOSI: 3619 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3620 case ISD::VP_FPTOUI: 3621 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3622 case ISD::VP_SITOFP: 3623 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3624 case ISD::VP_UITOFP: 3625 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3626 case ISD::VP_SETCC: 3627 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3628 return lowerVPSetCCMaskOp(Op, DAG); 3629 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3630 } 3631 } 3632 3633 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3634 SelectionDAG &DAG, unsigned Flags) { 3635 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3636 } 3637 3638 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3639 SelectionDAG &DAG, unsigned Flags) { 3640 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3641 Flags); 3642 } 3643 3644 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3645 SelectionDAG &DAG, unsigned Flags) { 3646 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3647 N->getOffset(), Flags); 3648 } 3649 3650 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3651 SelectionDAG &DAG, unsigned Flags) { 3652 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3653 } 3654 3655 template <class NodeTy> 3656 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3657 bool IsLocal) const { 3658 SDLoc DL(N); 3659 EVT Ty = getPointerTy(DAG.getDataLayout()); 3660 3661 if (isPositionIndependent()) { 3662 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3663 if (IsLocal) 3664 // Use PC-relative addressing to access the symbol. This generates the 3665 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3666 // %pcrel_lo(auipc)). 3667 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3668 3669 // Use PC-relative addressing to access the GOT for this symbol, then load 3670 // the address from the GOT. This generates the pattern (PseudoLA sym), 3671 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3672 MachineFunction &MF = DAG.getMachineFunction(); 3673 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3674 MachinePointerInfo::getGOT(MF), 3675 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3676 MachineMemOperand::MOInvariant, 3677 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3678 SDValue Load = 3679 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3680 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3681 return Load; 3682 } 3683 3684 switch (getTargetMachine().getCodeModel()) { 3685 default: 3686 report_fatal_error("Unsupported code model for lowering"); 3687 case CodeModel::Small: { 3688 // Generate a sequence for accessing addresses within the first 2 GiB of 3689 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3690 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3691 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3692 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3693 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3694 } 3695 case CodeModel::Medium: { 3696 // Generate a sequence for accessing addresses within any 2GiB range within 3697 // the address space. This generates the pattern (PseudoLLA sym), which 3698 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3699 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3700 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3701 } 3702 } 3703 } 3704 3705 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3706 SelectionDAG &DAG) const { 3707 SDLoc DL(Op); 3708 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3709 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3710 return getAddr(N, DAG, N->getGlobal()->isDSOLocal()); 3711 } 3712 3713 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3714 SelectionDAG &DAG) const { 3715 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3716 3717 return getAddr(N, DAG); 3718 } 3719 3720 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3721 SelectionDAG &DAG) const { 3722 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3723 3724 return getAddr(N, DAG); 3725 } 3726 3727 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3728 SelectionDAG &DAG) const { 3729 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3730 3731 return getAddr(N, DAG); 3732 } 3733 3734 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3735 SelectionDAG &DAG, 3736 bool UseGOT) const { 3737 SDLoc DL(N); 3738 EVT Ty = getPointerTy(DAG.getDataLayout()); 3739 const GlobalValue *GV = N->getGlobal(); 3740 MVT XLenVT = Subtarget.getXLenVT(); 3741 3742 if (UseGOT) { 3743 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3744 // load the address from the GOT and add the thread pointer. This generates 3745 // the pattern (PseudoLA_TLS_IE sym), which expands to 3746 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3747 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3748 MachineFunction &MF = DAG.getMachineFunction(); 3749 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3750 MachinePointerInfo::getGOT(MF), 3751 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3752 MachineMemOperand::MOInvariant, 3753 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3754 SDValue Load = DAG.getMemIntrinsicNode( 3755 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3756 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3757 3758 // Add the thread pointer. 3759 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3760 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3761 } 3762 3763 // Generate a sequence for accessing the address relative to the thread 3764 // pointer, with the appropriate adjustment for the thread pointer offset. 3765 // This generates the pattern 3766 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3767 SDValue AddrHi = 3768 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3769 SDValue AddrAdd = 3770 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3771 SDValue AddrLo = 3772 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3773 3774 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3775 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3776 SDValue MNAdd = 3777 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3778 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3779 } 3780 3781 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3782 SelectionDAG &DAG) const { 3783 SDLoc DL(N); 3784 EVT Ty = getPointerTy(DAG.getDataLayout()); 3785 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3786 const GlobalValue *GV = N->getGlobal(); 3787 3788 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3789 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3790 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3791 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3792 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3793 3794 // Prepare argument list to generate call. 3795 ArgListTy Args; 3796 ArgListEntry Entry; 3797 Entry.Node = Load; 3798 Entry.Ty = CallTy; 3799 Args.push_back(Entry); 3800 3801 // Setup call to __tls_get_addr. 3802 TargetLowering::CallLoweringInfo CLI(DAG); 3803 CLI.setDebugLoc(DL) 3804 .setChain(DAG.getEntryNode()) 3805 .setLibCallee(CallingConv::C, CallTy, 3806 DAG.getExternalSymbol("__tls_get_addr", Ty), 3807 std::move(Args)); 3808 3809 return LowerCallTo(CLI).first; 3810 } 3811 3812 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3813 SelectionDAG &DAG) const { 3814 SDLoc DL(Op); 3815 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3816 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3817 3818 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3819 3820 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3821 CallingConv::GHC) 3822 report_fatal_error("In GHC calling convention TLS is not supported"); 3823 3824 SDValue Addr; 3825 switch (Model) { 3826 case TLSModel::LocalExec: 3827 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3828 break; 3829 case TLSModel::InitialExec: 3830 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3831 break; 3832 case TLSModel::LocalDynamic: 3833 case TLSModel::GeneralDynamic: 3834 Addr = getDynamicTLSAddr(N, DAG); 3835 break; 3836 } 3837 3838 return Addr; 3839 } 3840 3841 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3842 SDValue CondV = Op.getOperand(0); 3843 SDValue TrueV = Op.getOperand(1); 3844 SDValue FalseV = Op.getOperand(2); 3845 SDLoc DL(Op); 3846 MVT VT = Op.getSimpleValueType(); 3847 MVT XLenVT = Subtarget.getXLenVT(); 3848 3849 // Lower vector SELECTs to VSELECTs by splatting the condition. 3850 if (VT.isVector()) { 3851 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3852 SDValue CondSplat = VT.isScalableVector() 3853 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3854 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3855 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3856 } 3857 3858 // If the result type is XLenVT and CondV is the output of a SETCC node 3859 // which also operated on XLenVT inputs, then merge the SETCC node into the 3860 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3861 // compare+branch instructions. i.e.: 3862 // (select (setcc lhs, rhs, cc), truev, falsev) 3863 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3864 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3865 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3866 SDValue LHS = CondV.getOperand(0); 3867 SDValue RHS = CondV.getOperand(1); 3868 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3869 ISD::CondCode CCVal = CC->get(); 3870 3871 // Special case for a select of 2 constants that have a diffence of 1. 3872 // Normally this is done by DAGCombine, but if the select is introduced by 3873 // type legalization or op legalization, we miss it. Restricting to SETLT 3874 // case for now because that is what signed saturating add/sub need. 3875 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3876 // but we would probably want to swap the true/false values if the condition 3877 // is SETGE/SETLE to avoid an XORI. 3878 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3879 CCVal == ISD::SETLT) { 3880 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3881 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3882 if (TrueVal - 1 == FalseVal) 3883 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3884 if (TrueVal + 1 == FalseVal) 3885 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3886 } 3887 3888 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3889 3890 SDValue TargetCC = DAG.getCondCode(CCVal); 3891 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3892 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3893 } 3894 3895 // Otherwise: 3896 // (select condv, truev, falsev) 3897 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3898 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3899 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3900 3901 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3902 3903 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3904 } 3905 3906 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3907 SDValue CondV = Op.getOperand(1); 3908 SDLoc DL(Op); 3909 MVT XLenVT = Subtarget.getXLenVT(); 3910 3911 if (CondV.getOpcode() == ISD::SETCC && 3912 CondV.getOperand(0).getValueType() == XLenVT) { 3913 SDValue LHS = CondV.getOperand(0); 3914 SDValue RHS = CondV.getOperand(1); 3915 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3916 3917 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3918 3919 SDValue TargetCC = DAG.getCondCode(CCVal); 3920 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3921 LHS, RHS, TargetCC, Op.getOperand(2)); 3922 } 3923 3924 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3925 CondV, DAG.getConstant(0, DL, XLenVT), 3926 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3927 } 3928 3929 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3930 MachineFunction &MF = DAG.getMachineFunction(); 3931 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3932 3933 SDLoc DL(Op); 3934 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3935 getPointerTy(MF.getDataLayout())); 3936 3937 // vastart just stores the address of the VarArgsFrameIndex slot into the 3938 // memory location argument. 3939 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3940 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3941 MachinePointerInfo(SV)); 3942 } 3943 3944 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3945 SelectionDAG &DAG) const { 3946 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3947 MachineFunction &MF = DAG.getMachineFunction(); 3948 MachineFrameInfo &MFI = MF.getFrameInfo(); 3949 MFI.setFrameAddressIsTaken(true); 3950 Register FrameReg = RI.getFrameRegister(MF); 3951 int XLenInBytes = Subtarget.getXLen() / 8; 3952 3953 EVT VT = Op.getValueType(); 3954 SDLoc DL(Op); 3955 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3956 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3957 while (Depth--) { 3958 int Offset = -(XLenInBytes * 2); 3959 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3960 DAG.getIntPtrConstant(Offset, DL)); 3961 FrameAddr = 3962 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3963 } 3964 return FrameAddr; 3965 } 3966 3967 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3968 SelectionDAG &DAG) const { 3969 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3970 MachineFunction &MF = DAG.getMachineFunction(); 3971 MachineFrameInfo &MFI = MF.getFrameInfo(); 3972 MFI.setReturnAddressIsTaken(true); 3973 MVT XLenVT = Subtarget.getXLenVT(); 3974 int XLenInBytes = Subtarget.getXLen() / 8; 3975 3976 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3977 return SDValue(); 3978 3979 EVT VT = Op.getValueType(); 3980 SDLoc DL(Op); 3981 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3982 if (Depth) { 3983 int Off = -XLenInBytes; 3984 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3985 SDValue Offset = DAG.getConstant(Off, DL, VT); 3986 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3987 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3988 MachinePointerInfo()); 3989 } 3990 3991 // Return the value of the return address register, marking it an implicit 3992 // live-in. 3993 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3994 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3995 } 3996 3997 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3998 SelectionDAG &DAG) const { 3999 SDLoc DL(Op); 4000 SDValue Lo = Op.getOperand(0); 4001 SDValue Hi = Op.getOperand(1); 4002 SDValue Shamt = Op.getOperand(2); 4003 EVT VT = Lo.getValueType(); 4004 4005 // if Shamt-XLEN < 0: // Shamt < XLEN 4006 // Lo = Lo << Shamt 4007 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4008 // else: 4009 // Lo = 0 4010 // Hi = Lo << (Shamt-XLEN) 4011 4012 SDValue Zero = DAG.getConstant(0, DL, VT); 4013 SDValue One = DAG.getConstant(1, DL, VT); 4014 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4015 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4016 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4017 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4018 4019 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4020 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4021 SDValue ShiftRightLo = 4022 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4023 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4024 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4025 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4026 4027 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4028 4029 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4030 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4031 4032 SDValue Parts[2] = {Lo, Hi}; 4033 return DAG.getMergeValues(Parts, DL); 4034 } 4035 4036 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4037 bool IsSRA) const { 4038 SDLoc DL(Op); 4039 SDValue Lo = Op.getOperand(0); 4040 SDValue Hi = Op.getOperand(1); 4041 SDValue Shamt = Op.getOperand(2); 4042 EVT VT = Lo.getValueType(); 4043 4044 // SRA expansion: 4045 // if Shamt-XLEN < 0: // Shamt < XLEN 4046 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4047 // Hi = Hi >>s Shamt 4048 // else: 4049 // Lo = Hi >>s (Shamt-XLEN); 4050 // Hi = Hi >>s (XLEN-1) 4051 // 4052 // SRL expansion: 4053 // if Shamt-XLEN < 0: // Shamt < XLEN 4054 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4055 // Hi = Hi >>u Shamt 4056 // else: 4057 // Lo = Hi >>u (Shamt-XLEN); 4058 // Hi = 0; 4059 4060 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4061 4062 SDValue Zero = DAG.getConstant(0, DL, VT); 4063 SDValue One = DAG.getConstant(1, DL, VT); 4064 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4065 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4066 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4067 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4068 4069 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4070 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4071 SDValue ShiftLeftHi = 4072 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4073 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4074 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4075 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4076 SDValue HiFalse = 4077 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4078 4079 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4080 4081 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4082 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4083 4084 SDValue Parts[2] = {Lo, Hi}; 4085 return DAG.getMergeValues(Parts, DL); 4086 } 4087 4088 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4089 // legal equivalently-sized i8 type, so we can use that as a go-between. 4090 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4091 SelectionDAG &DAG) const { 4092 SDLoc DL(Op); 4093 MVT VT = Op.getSimpleValueType(); 4094 SDValue SplatVal = Op.getOperand(0); 4095 // All-zeros or all-ones splats are handled specially. 4096 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4097 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4098 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4099 } 4100 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4101 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4102 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4103 } 4104 MVT XLenVT = Subtarget.getXLenVT(); 4105 assert(SplatVal.getValueType() == XLenVT && 4106 "Unexpected type for i1 splat value"); 4107 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4108 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4109 DAG.getConstant(1, DL, XLenVT)); 4110 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4111 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4112 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4113 } 4114 4115 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4116 // illegal (currently only vXi64 RV32). 4117 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4118 // them to VMV_V_X_VL. 4119 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4120 SelectionDAG &DAG) const { 4121 SDLoc DL(Op); 4122 MVT VecVT = Op.getSimpleValueType(); 4123 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4124 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4125 4126 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4127 SDValue Lo = Op.getOperand(0); 4128 SDValue Hi = Op.getOperand(1); 4129 4130 if (VecVT.isFixedLengthVector()) { 4131 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4132 SDLoc DL(Op); 4133 SDValue Mask, VL; 4134 std::tie(Mask, VL) = 4135 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4136 4137 SDValue Res = 4138 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4139 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4140 } 4141 4142 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4143 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4144 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4145 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4146 // node in order to try and match RVV vector/scalar instructions. 4147 if ((LoC >> 31) == HiC) 4148 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4149 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4150 } 4151 4152 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4153 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4154 isa<ConstantSDNode>(Hi.getOperand(1)) && 4155 Hi.getConstantOperandVal(1) == 31) 4156 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4157 DAG.getRegister(RISCV::X0, MVT::i32)); 4158 4159 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4160 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4161 DAG.getUNDEF(VecVT), Lo, Hi, 4162 DAG.getRegister(RISCV::X0, MVT::i32)); 4163 } 4164 4165 // Custom-lower extensions from mask vectors by using a vselect either with 1 4166 // for zero/any-extension or -1 for sign-extension: 4167 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4168 // Note that any-extension is lowered identically to zero-extension. 4169 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4170 int64_t ExtTrueVal) const { 4171 SDLoc DL(Op); 4172 MVT VecVT = Op.getSimpleValueType(); 4173 SDValue Src = Op.getOperand(0); 4174 // Only custom-lower extensions from mask types 4175 assert(Src.getValueType().isVector() && 4176 Src.getValueType().getVectorElementType() == MVT::i1); 4177 4178 if (VecVT.isScalableVector()) { 4179 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4180 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4181 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4182 } 4183 4184 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4185 MVT I1ContainerVT = 4186 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4187 4188 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4189 4190 SDValue Mask, VL; 4191 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4192 4193 MVT XLenVT = Subtarget.getXLenVT(); 4194 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4195 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4196 4197 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4198 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4199 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4200 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4201 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4202 SplatTrueVal, SplatZero, VL); 4203 4204 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4205 } 4206 4207 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4208 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4209 MVT ExtVT = Op.getSimpleValueType(); 4210 // Only custom-lower extensions from fixed-length vector types. 4211 if (!ExtVT.isFixedLengthVector()) 4212 return Op; 4213 MVT VT = Op.getOperand(0).getSimpleValueType(); 4214 // Grab the canonical container type for the extended type. Infer the smaller 4215 // type from that to ensure the same number of vector elements, as we know 4216 // the LMUL will be sufficient to hold the smaller type. 4217 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4218 // Get the extended container type manually to ensure the same number of 4219 // vector elements between source and dest. 4220 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4221 ContainerExtVT.getVectorElementCount()); 4222 4223 SDValue Op1 = 4224 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4225 4226 SDLoc DL(Op); 4227 SDValue Mask, VL; 4228 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4229 4230 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4231 4232 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4233 } 4234 4235 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4236 // setcc operation: 4237 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4238 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4239 SelectionDAG &DAG) const { 4240 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4241 SDLoc DL(Op); 4242 EVT MaskVT = Op.getValueType(); 4243 // Only expect to custom-lower truncations to mask types 4244 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4245 "Unexpected type for vector mask lowering"); 4246 SDValue Src = Op.getOperand(0); 4247 MVT VecVT = Src.getSimpleValueType(); 4248 SDValue Mask, VL; 4249 if (IsVPTrunc) { 4250 Mask = Op.getOperand(1); 4251 VL = Op.getOperand(2); 4252 } 4253 // If this is a fixed vector, we need to convert it to a scalable vector. 4254 MVT ContainerVT = VecVT; 4255 4256 if (VecVT.isFixedLengthVector()) { 4257 ContainerVT = getContainerForFixedLengthVector(VecVT); 4258 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4259 if (IsVPTrunc) { 4260 MVT MaskContainerVT = 4261 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4262 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4263 } 4264 } 4265 4266 if (!IsVPTrunc) { 4267 std::tie(Mask, VL) = 4268 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4269 } 4270 4271 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4272 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4273 4274 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4275 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4276 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4277 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4278 4279 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4280 SDValue Trunc = 4281 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4282 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4283 DAG.getCondCode(ISD::SETNE), Mask, VL); 4284 if (MaskVT.isFixedLengthVector()) 4285 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4286 return Trunc; 4287 } 4288 4289 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4290 SelectionDAG &DAG) const { 4291 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4292 SDLoc DL(Op); 4293 4294 MVT VT = Op.getSimpleValueType(); 4295 // Only custom-lower vector truncates 4296 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4297 4298 // Truncates to mask types are handled differently 4299 if (VT.getVectorElementType() == MVT::i1) 4300 return lowerVectorMaskTruncLike(Op, DAG); 4301 4302 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4303 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4304 // truncate by one power of two at a time. 4305 MVT DstEltVT = VT.getVectorElementType(); 4306 4307 SDValue Src = Op.getOperand(0); 4308 MVT SrcVT = Src.getSimpleValueType(); 4309 MVT SrcEltVT = SrcVT.getVectorElementType(); 4310 4311 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4312 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4313 "Unexpected vector truncate lowering"); 4314 4315 MVT ContainerVT = SrcVT; 4316 SDValue Mask, VL; 4317 if (IsVPTrunc) { 4318 Mask = Op.getOperand(1); 4319 VL = Op.getOperand(2); 4320 } 4321 if (SrcVT.isFixedLengthVector()) { 4322 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4323 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4324 if (IsVPTrunc) { 4325 MVT MaskVT = getMaskTypeFor(ContainerVT); 4326 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4327 } 4328 } 4329 4330 SDValue Result = Src; 4331 if (!IsVPTrunc) { 4332 std::tie(Mask, VL) = 4333 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4334 } 4335 4336 LLVMContext &Context = *DAG.getContext(); 4337 const ElementCount Count = ContainerVT.getVectorElementCount(); 4338 do { 4339 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4340 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4341 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4342 Mask, VL); 4343 } while (SrcEltVT != DstEltVT); 4344 4345 if (SrcVT.isFixedLengthVector()) 4346 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4347 4348 return Result; 4349 } 4350 4351 SDValue 4352 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4353 SelectionDAG &DAG) const { 4354 bool IsVP = 4355 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4356 bool IsExtend = 4357 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4358 // RVV can only do truncate fp to types half the size as the source. We 4359 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4360 // conversion instruction. 4361 SDLoc DL(Op); 4362 MVT VT = Op.getSimpleValueType(); 4363 4364 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4365 4366 SDValue Src = Op.getOperand(0); 4367 MVT SrcVT = Src.getSimpleValueType(); 4368 4369 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4370 SrcVT.getVectorElementType() != MVT::f16); 4371 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4372 SrcVT.getVectorElementType() != MVT::f64); 4373 4374 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4375 4376 // Prepare any fixed-length vector operands. 4377 MVT ContainerVT = VT; 4378 SDValue Mask, VL; 4379 if (IsVP) { 4380 Mask = Op.getOperand(1); 4381 VL = Op.getOperand(2); 4382 } 4383 if (VT.isFixedLengthVector()) { 4384 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4385 ContainerVT = 4386 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4387 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4388 if (IsVP) { 4389 MVT MaskVT = getMaskTypeFor(ContainerVT); 4390 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4391 } 4392 } 4393 4394 if (!IsVP) 4395 std::tie(Mask, VL) = 4396 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4397 4398 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4399 4400 if (IsDirectConv) { 4401 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4402 if (VT.isFixedLengthVector()) 4403 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4404 return Src; 4405 } 4406 4407 unsigned InterConvOpc = 4408 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4409 4410 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4411 SDValue IntermediateConv = 4412 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4413 SDValue Result = 4414 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4415 if (VT.isFixedLengthVector()) 4416 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4417 return Result; 4418 } 4419 4420 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4421 // first position of a vector, and that vector is slid up to the insert index. 4422 // By limiting the active vector length to index+1 and merging with the 4423 // original vector (with an undisturbed tail policy for elements >= VL), we 4424 // achieve the desired result of leaving all elements untouched except the one 4425 // at VL-1, which is replaced with the desired value. 4426 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4427 SelectionDAG &DAG) const { 4428 SDLoc DL(Op); 4429 MVT VecVT = Op.getSimpleValueType(); 4430 SDValue Vec = Op.getOperand(0); 4431 SDValue Val = Op.getOperand(1); 4432 SDValue Idx = Op.getOperand(2); 4433 4434 if (VecVT.getVectorElementType() == MVT::i1) { 4435 // FIXME: For now we just promote to an i8 vector and insert into that, 4436 // but this is probably not optimal. 4437 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4438 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4439 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4440 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4441 } 4442 4443 MVT ContainerVT = VecVT; 4444 // If the operand is a fixed-length vector, convert to a scalable one. 4445 if (VecVT.isFixedLengthVector()) { 4446 ContainerVT = getContainerForFixedLengthVector(VecVT); 4447 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4448 } 4449 4450 MVT XLenVT = Subtarget.getXLenVT(); 4451 4452 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4453 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4454 // Even i64-element vectors on RV32 can be lowered without scalar 4455 // legalization if the most-significant 32 bits of the value are not affected 4456 // by the sign-extension of the lower 32 bits. 4457 // TODO: We could also catch sign extensions of a 32-bit value. 4458 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4459 const auto *CVal = cast<ConstantSDNode>(Val); 4460 if (isInt<32>(CVal->getSExtValue())) { 4461 IsLegalInsert = true; 4462 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4463 } 4464 } 4465 4466 SDValue Mask, VL; 4467 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4468 4469 SDValue ValInVec; 4470 4471 if (IsLegalInsert) { 4472 unsigned Opc = 4473 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4474 if (isNullConstant(Idx)) { 4475 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4476 if (!VecVT.isFixedLengthVector()) 4477 return Vec; 4478 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4479 } 4480 ValInVec = 4481 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4482 } else { 4483 // On RV32, i64-element vectors must be specially handled to place the 4484 // value at element 0, by using two vslide1up instructions in sequence on 4485 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4486 // this. 4487 SDValue One = DAG.getConstant(1, DL, XLenVT); 4488 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4489 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4490 MVT I32ContainerVT = 4491 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4492 SDValue I32Mask = 4493 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4494 // Limit the active VL to two. 4495 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4496 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4497 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4498 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4499 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4500 // First slide in the hi value, then the lo in underneath it. 4501 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4502 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4503 I32Mask, InsertI64VL); 4504 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4505 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4506 I32Mask, InsertI64VL); 4507 // Bitcast back to the right container type. 4508 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4509 } 4510 4511 // Now that the value is in a vector, slide it into position. 4512 SDValue InsertVL = 4513 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4514 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4515 ValInVec, Idx, Mask, InsertVL); 4516 if (!VecVT.isFixedLengthVector()) 4517 return Slideup; 4518 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4519 } 4520 4521 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4522 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4523 // types this is done using VMV_X_S to allow us to glean information about the 4524 // sign bits of the result. 4525 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4526 SelectionDAG &DAG) const { 4527 SDLoc DL(Op); 4528 SDValue Idx = Op.getOperand(1); 4529 SDValue Vec = Op.getOperand(0); 4530 EVT EltVT = Op.getValueType(); 4531 MVT VecVT = Vec.getSimpleValueType(); 4532 MVT XLenVT = Subtarget.getXLenVT(); 4533 4534 if (VecVT.getVectorElementType() == MVT::i1) { 4535 if (VecVT.isFixedLengthVector()) { 4536 unsigned NumElts = VecVT.getVectorNumElements(); 4537 if (NumElts >= 8) { 4538 MVT WideEltVT; 4539 unsigned WidenVecLen; 4540 SDValue ExtractElementIdx; 4541 SDValue ExtractBitIdx; 4542 unsigned MaxEEW = Subtarget.getELEN(); 4543 MVT LargestEltVT = MVT::getIntegerVT( 4544 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4545 if (NumElts <= LargestEltVT.getSizeInBits()) { 4546 assert(isPowerOf2_32(NumElts) && 4547 "the number of elements should be power of 2"); 4548 WideEltVT = MVT::getIntegerVT(NumElts); 4549 WidenVecLen = 1; 4550 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4551 ExtractBitIdx = Idx; 4552 } else { 4553 WideEltVT = LargestEltVT; 4554 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4555 // extract element index = index / element width 4556 ExtractElementIdx = DAG.getNode( 4557 ISD::SRL, DL, XLenVT, Idx, 4558 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4559 // mask bit index = index % element width 4560 ExtractBitIdx = DAG.getNode( 4561 ISD::AND, DL, XLenVT, Idx, 4562 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4563 } 4564 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4565 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4566 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4567 Vec, ExtractElementIdx); 4568 // Extract the bit from GPR. 4569 SDValue ShiftRight = 4570 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4571 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4572 DAG.getConstant(1, DL, XLenVT)); 4573 } 4574 } 4575 // Otherwise, promote to an i8 vector and extract from that. 4576 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4577 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4578 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4579 } 4580 4581 // If this is a fixed vector, we need to convert it to a scalable vector. 4582 MVT ContainerVT = VecVT; 4583 if (VecVT.isFixedLengthVector()) { 4584 ContainerVT = getContainerForFixedLengthVector(VecVT); 4585 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4586 } 4587 4588 // If the index is 0, the vector is already in the right position. 4589 if (!isNullConstant(Idx)) { 4590 // Use a VL of 1 to avoid processing more elements than we need. 4591 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4592 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4593 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4594 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4595 } 4596 4597 if (!EltVT.isInteger()) { 4598 // Floating-point extracts are handled in TableGen. 4599 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4600 DAG.getConstant(0, DL, XLenVT)); 4601 } 4602 4603 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4604 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4605 } 4606 4607 // Some RVV intrinsics may claim that they want an integer operand to be 4608 // promoted or expanded. 4609 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4610 const RISCVSubtarget &Subtarget) { 4611 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4612 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4613 "Unexpected opcode"); 4614 4615 if (!Subtarget.hasVInstructions()) 4616 return SDValue(); 4617 4618 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4619 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4620 SDLoc DL(Op); 4621 4622 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4623 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4624 if (!II || !II->hasScalarOperand()) 4625 return SDValue(); 4626 4627 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4628 assert(SplatOp < Op.getNumOperands()); 4629 4630 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4631 SDValue &ScalarOp = Operands[SplatOp]; 4632 MVT OpVT = ScalarOp.getSimpleValueType(); 4633 MVT XLenVT = Subtarget.getXLenVT(); 4634 4635 // If this isn't a scalar, or its type is XLenVT we're done. 4636 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4637 return SDValue(); 4638 4639 // Simplest case is that the operand needs to be promoted to XLenVT. 4640 if (OpVT.bitsLT(XLenVT)) { 4641 // If the operand is a constant, sign extend to increase our chances 4642 // of being able to use a .vi instruction. ANY_EXTEND would become a 4643 // a zero extend and the simm5 check in isel would fail. 4644 // FIXME: Should we ignore the upper bits in isel instead? 4645 unsigned ExtOpc = 4646 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4647 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4648 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4649 } 4650 4651 // Use the previous operand to get the vXi64 VT. The result might be a mask 4652 // VT for compares. Using the previous operand assumes that the previous 4653 // operand will never have a smaller element size than a scalar operand and 4654 // that a widening operation never uses SEW=64. 4655 // NOTE: If this fails the below assert, we can probably just find the 4656 // element count from any operand or result and use it to construct the VT. 4657 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4658 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4659 4660 // The more complex case is when the scalar is larger than XLenVT. 4661 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4662 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4663 4664 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4665 // instruction to sign-extend since SEW>XLEN. 4666 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4667 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4668 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4669 } 4670 4671 switch (IntNo) { 4672 case Intrinsic::riscv_vslide1up: 4673 case Intrinsic::riscv_vslide1down: 4674 case Intrinsic::riscv_vslide1up_mask: 4675 case Intrinsic::riscv_vslide1down_mask: { 4676 // We need to special case these when the scalar is larger than XLen. 4677 unsigned NumOps = Op.getNumOperands(); 4678 bool IsMasked = NumOps == 7; 4679 4680 // Convert the vector source to the equivalent nxvXi32 vector. 4681 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4682 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4683 4684 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4685 DAG.getConstant(0, DL, XLenVT)); 4686 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4687 DAG.getConstant(1, DL, XLenVT)); 4688 4689 // Double the VL since we halved SEW. 4690 SDValue AVL = getVLOperand(Op); 4691 SDValue I32VL; 4692 4693 // Optimize for constant AVL 4694 if (isa<ConstantSDNode>(AVL)) { 4695 unsigned EltSize = VT.getScalarSizeInBits(); 4696 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4697 4698 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4699 unsigned MaxVLMAX = 4700 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4701 4702 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4703 unsigned MinVLMAX = 4704 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4705 4706 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4707 if (AVLInt <= MinVLMAX) { 4708 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4709 } else if (AVLInt >= 2 * MaxVLMAX) { 4710 // Just set vl to VLMAX in this situation 4711 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4712 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4713 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4714 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4715 SDValue SETVLMAX = DAG.getTargetConstant( 4716 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4717 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4718 LMUL); 4719 } else { 4720 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4721 // is related to the hardware implementation. 4722 // So let the following code handle 4723 } 4724 } 4725 if (!I32VL) { 4726 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4727 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4728 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4729 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4730 SDValue SETVL = 4731 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4732 // Using vsetvli instruction to get actually used length which related to 4733 // the hardware implementation 4734 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4735 SEW, LMUL); 4736 I32VL = 4737 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4738 } 4739 4740 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4741 4742 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4743 // instructions. 4744 SDValue Passthru; 4745 if (IsMasked) 4746 Passthru = DAG.getUNDEF(I32VT); 4747 else 4748 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4749 4750 if (IntNo == Intrinsic::riscv_vslide1up || 4751 IntNo == Intrinsic::riscv_vslide1up_mask) { 4752 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4753 ScalarHi, I32Mask, I32VL); 4754 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4755 ScalarLo, I32Mask, I32VL); 4756 } else { 4757 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4758 ScalarLo, I32Mask, I32VL); 4759 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4760 ScalarHi, I32Mask, I32VL); 4761 } 4762 4763 // Convert back to nxvXi64. 4764 Vec = DAG.getBitcast(VT, Vec); 4765 4766 if (!IsMasked) 4767 return Vec; 4768 // Apply mask after the operation. 4769 SDValue Mask = Operands[NumOps - 3]; 4770 SDValue MaskedOff = Operands[1]; 4771 // Assume Policy operand is the last operand. 4772 uint64_t Policy = 4773 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4774 // We don't need to select maskedoff if it's undef. 4775 if (MaskedOff.isUndef()) 4776 return Vec; 4777 // TAMU 4778 if (Policy == RISCVII::TAIL_AGNOSTIC) 4779 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4780 AVL); 4781 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4782 // It's fine because vmerge does not care mask policy. 4783 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4784 AVL); 4785 } 4786 } 4787 4788 // We need to convert the scalar to a splat vector. 4789 SDValue VL = getVLOperand(Op); 4790 assert(VL.getValueType() == XLenVT); 4791 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4792 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4793 } 4794 4795 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4796 SelectionDAG &DAG) const { 4797 unsigned IntNo = Op.getConstantOperandVal(0); 4798 SDLoc DL(Op); 4799 MVT XLenVT = Subtarget.getXLenVT(); 4800 4801 switch (IntNo) { 4802 default: 4803 break; // Don't custom lower most intrinsics. 4804 case Intrinsic::thread_pointer: { 4805 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4806 return DAG.getRegister(RISCV::X4, PtrVT); 4807 } 4808 case Intrinsic::riscv_orc_b: 4809 case Intrinsic::riscv_brev8: { 4810 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4811 unsigned Opc = 4812 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4813 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4814 DAG.getConstant(7, DL, XLenVT)); 4815 } 4816 case Intrinsic::riscv_grev: 4817 case Intrinsic::riscv_gorc: { 4818 unsigned Opc = 4819 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4820 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4821 } 4822 case Intrinsic::riscv_zip: 4823 case Intrinsic::riscv_unzip: { 4824 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4825 // For i32 the immediate is 15. For i64 the immediate is 31. 4826 unsigned Opc = 4827 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4828 unsigned BitWidth = Op.getValueSizeInBits(); 4829 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4830 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4831 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4832 } 4833 case Intrinsic::riscv_shfl: 4834 case Intrinsic::riscv_unshfl: { 4835 unsigned Opc = 4836 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4837 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4838 } 4839 case Intrinsic::riscv_bcompress: 4840 case Intrinsic::riscv_bdecompress: { 4841 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4842 : RISCVISD::BDECOMPRESS; 4843 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4844 } 4845 case Intrinsic::riscv_bfp: 4846 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4847 Op.getOperand(2)); 4848 case Intrinsic::riscv_fsl: 4849 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4850 Op.getOperand(2), Op.getOperand(3)); 4851 case Intrinsic::riscv_fsr: 4852 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4853 Op.getOperand(2), Op.getOperand(3)); 4854 case Intrinsic::riscv_vmv_x_s: 4855 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4856 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4857 Op.getOperand(1)); 4858 case Intrinsic::riscv_vmv_v_x: 4859 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4860 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4861 Subtarget); 4862 case Intrinsic::riscv_vfmv_v_f: 4863 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4864 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4865 case Intrinsic::riscv_vmv_s_x: { 4866 SDValue Scalar = Op.getOperand(2); 4867 4868 if (Scalar.getValueType().bitsLE(XLenVT)) { 4869 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4870 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4871 Op.getOperand(1), Scalar, Op.getOperand(3)); 4872 } 4873 4874 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4875 4876 // This is an i64 value that lives in two scalar registers. We have to 4877 // insert this in a convoluted way. First we build vXi64 splat containing 4878 // the two values that we assemble using some bit math. Next we'll use 4879 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4880 // to merge element 0 from our splat into the source vector. 4881 // FIXME: This is probably not the best way to do this, but it is 4882 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4883 // point. 4884 // sw lo, (a0) 4885 // sw hi, 4(a0) 4886 // vlse vX, (a0) 4887 // 4888 // vid.v vVid 4889 // vmseq.vx mMask, vVid, 0 4890 // vmerge.vvm vDest, vSrc, vVal, mMask 4891 MVT VT = Op.getSimpleValueType(); 4892 SDValue Vec = Op.getOperand(1); 4893 SDValue VL = getVLOperand(Op); 4894 4895 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4896 if (Op.getOperand(1).isUndef()) 4897 return SplattedVal; 4898 SDValue SplattedIdx = 4899 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4900 DAG.getConstant(0, DL, MVT::i32), VL); 4901 4902 MVT MaskVT = getMaskTypeFor(VT); 4903 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4904 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4905 SDValue SelectCond = 4906 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4907 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4908 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4909 Vec, VL); 4910 } 4911 } 4912 4913 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4914 } 4915 4916 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4917 SelectionDAG &DAG) const { 4918 unsigned IntNo = Op.getConstantOperandVal(1); 4919 switch (IntNo) { 4920 default: 4921 break; 4922 case Intrinsic::riscv_masked_strided_load: { 4923 SDLoc DL(Op); 4924 MVT XLenVT = Subtarget.getXLenVT(); 4925 4926 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4927 // the selection of the masked intrinsics doesn't do this for us. 4928 SDValue Mask = Op.getOperand(5); 4929 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4930 4931 MVT VT = Op->getSimpleValueType(0); 4932 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4933 4934 SDValue PassThru = Op.getOperand(2); 4935 if (!IsUnmasked) { 4936 MVT MaskVT = getMaskTypeFor(ContainerVT); 4937 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4938 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4939 } 4940 4941 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4942 4943 SDValue IntID = DAG.getTargetConstant( 4944 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4945 XLenVT); 4946 4947 auto *Load = cast<MemIntrinsicSDNode>(Op); 4948 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4949 if (IsUnmasked) 4950 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4951 else 4952 Ops.push_back(PassThru); 4953 Ops.push_back(Op.getOperand(3)); // Ptr 4954 Ops.push_back(Op.getOperand(4)); // Stride 4955 if (!IsUnmasked) 4956 Ops.push_back(Mask); 4957 Ops.push_back(VL); 4958 if (!IsUnmasked) { 4959 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4960 Ops.push_back(Policy); 4961 } 4962 4963 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4964 SDValue Result = 4965 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4966 Load->getMemoryVT(), Load->getMemOperand()); 4967 SDValue Chain = Result.getValue(1); 4968 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4969 return DAG.getMergeValues({Result, Chain}, DL); 4970 } 4971 case Intrinsic::riscv_seg2_load: 4972 case Intrinsic::riscv_seg3_load: 4973 case Intrinsic::riscv_seg4_load: 4974 case Intrinsic::riscv_seg5_load: 4975 case Intrinsic::riscv_seg6_load: 4976 case Intrinsic::riscv_seg7_load: 4977 case Intrinsic::riscv_seg8_load: { 4978 SDLoc DL(Op); 4979 static const Intrinsic::ID VlsegInts[7] = { 4980 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4981 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4982 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4983 Intrinsic::riscv_vlseg8}; 4984 unsigned NF = Op->getNumValues() - 1; 4985 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4986 MVT XLenVT = Subtarget.getXLenVT(); 4987 MVT VT = Op->getSimpleValueType(0); 4988 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4989 4990 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4991 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4992 auto *Load = cast<MemIntrinsicSDNode>(Op); 4993 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4994 ContainerVTs.push_back(MVT::Other); 4995 SDVTList VTs = DAG.getVTList(ContainerVTs); 4996 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4997 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4998 Ops.push_back(Op.getOperand(2)); 4999 Ops.push_back(VL); 5000 SDValue Result = 5001 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5002 Load->getMemoryVT(), Load->getMemOperand()); 5003 SmallVector<SDValue, 9> Results; 5004 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5005 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5006 DAG, Subtarget)); 5007 Results.push_back(Result.getValue(NF)); 5008 return DAG.getMergeValues(Results, DL); 5009 } 5010 } 5011 5012 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5013 } 5014 5015 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5016 SelectionDAG &DAG) const { 5017 unsigned IntNo = Op.getConstantOperandVal(1); 5018 switch (IntNo) { 5019 default: 5020 break; 5021 case Intrinsic::riscv_masked_strided_store: { 5022 SDLoc DL(Op); 5023 MVT XLenVT = Subtarget.getXLenVT(); 5024 5025 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5026 // the selection of the masked intrinsics doesn't do this for us. 5027 SDValue Mask = Op.getOperand(5); 5028 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5029 5030 SDValue Val = Op.getOperand(2); 5031 MVT VT = Val.getSimpleValueType(); 5032 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5033 5034 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5035 if (!IsUnmasked) { 5036 MVT MaskVT = getMaskTypeFor(ContainerVT); 5037 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5038 } 5039 5040 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5041 5042 SDValue IntID = DAG.getTargetConstant( 5043 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5044 XLenVT); 5045 5046 auto *Store = cast<MemIntrinsicSDNode>(Op); 5047 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5048 Ops.push_back(Val); 5049 Ops.push_back(Op.getOperand(3)); // Ptr 5050 Ops.push_back(Op.getOperand(4)); // Stride 5051 if (!IsUnmasked) 5052 Ops.push_back(Mask); 5053 Ops.push_back(VL); 5054 5055 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5056 Ops, Store->getMemoryVT(), 5057 Store->getMemOperand()); 5058 } 5059 } 5060 5061 return SDValue(); 5062 } 5063 5064 static MVT getLMUL1VT(MVT VT) { 5065 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5066 "Unexpected vector MVT"); 5067 return MVT::getScalableVectorVT( 5068 VT.getVectorElementType(), 5069 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5070 } 5071 5072 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5073 switch (ISDOpcode) { 5074 default: 5075 llvm_unreachable("Unhandled reduction"); 5076 case ISD::VECREDUCE_ADD: 5077 return RISCVISD::VECREDUCE_ADD_VL; 5078 case ISD::VECREDUCE_UMAX: 5079 return RISCVISD::VECREDUCE_UMAX_VL; 5080 case ISD::VECREDUCE_SMAX: 5081 return RISCVISD::VECREDUCE_SMAX_VL; 5082 case ISD::VECREDUCE_UMIN: 5083 return RISCVISD::VECREDUCE_UMIN_VL; 5084 case ISD::VECREDUCE_SMIN: 5085 return RISCVISD::VECREDUCE_SMIN_VL; 5086 case ISD::VECREDUCE_AND: 5087 return RISCVISD::VECREDUCE_AND_VL; 5088 case ISD::VECREDUCE_OR: 5089 return RISCVISD::VECREDUCE_OR_VL; 5090 case ISD::VECREDUCE_XOR: 5091 return RISCVISD::VECREDUCE_XOR_VL; 5092 } 5093 } 5094 5095 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5096 SelectionDAG &DAG, 5097 bool IsVP) const { 5098 SDLoc DL(Op); 5099 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5100 MVT VecVT = Vec.getSimpleValueType(); 5101 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5102 Op.getOpcode() == ISD::VECREDUCE_OR || 5103 Op.getOpcode() == ISD::VECREDUCE_XOR || 5104 Op.getOpcode() == ISD::VP_REDUCE_AND || 5105 Op.getOpcode() == ISD::VP_REDUCE_OR || 5106 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5107 "Unexpected reduction lowering"); 5108 5109 MVT XLenVT = Subtarget.getXLenVT(); 5110 assert(Op.getValueType() == XLenVT && 5111 "Expected reduction output to be legalized to XLenVT"); 5112 5113 MVT ContainerVT = VecVT; 5114 if (VecVT.isFixedLengthVector()) { 5115 ContainerVT = getContainerForFixedLengthVector(VecVT); 5116 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5117 } 5118 5119 SDValue Mask, VL; 5120 if (IsVP) { 5121 Mask = Op.getOperand(2); 5122 VL = Op.getOperand(3); 5123 } else { 5124 std::tie(Mask, VL) = 5125 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5126 } 5127 5128 unsigned BaseOpc; 5129 ISD::CondCode CC; 5130 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5131 5132 switch (Op.getOpcode()) { 5133 default: 5134 llvm_unreachable("Unhandled reduction"); 5135 case ISD::VECREDUCE_AND: 5136 case ISD::VP_REDUCE_AND: { 5137 // vcpop ~x == 0 5138 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5139 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5140 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5141 CC = ISD::SETEQ; 5142 BaseOpc = ISD::AND; 5143 break; 5144 } 5145 case ISD::VECREDUCE_OR: 5146 case ISD::VP_REDUCE_OR: 5147 // vcpop x != 0 5148 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5149 CC = ISD::SETNE; 5150 BaseOpc = ISD::OR; 5151 break; 5152 case ISD::VECREDUCE_XOR: 5153 case ISD::VP_REDUCE_XOR: { 5154 // ((vcpop x) & 1) != 0 5155 SDValue One = DAG.getConstant(1, DL, XLenVT); 5156 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5157 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5158 CC = ISD::SETNE; 5159 BaseOpc = ISD::XOR; 5160 break; 5161 } 5162 } 5163 5164 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5165 5166 if (!IsVP) 5167 return SetCC; 5168 5169 // Now include the start value in the operation. 5170 // Note that we must return the start value when no elements are operated 5171 // upon. The vcpop instructions we've emitted in each case above will return 5172 // 0 for an inactive vector, and so we've already received the neutral value: 5173 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5174 // can simply include the start value. 5175 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5176 } 5177 5178 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5179 SelectionDAG &DAG) const { 5180 SDLoc DL(Op); 5181 SDValue Vec = Op.getOperand(0); 5182 EVT VecEVT = Vec.getValueType(); 5183 5184 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5185 5186 // Due to ordering in legalize types we may have a vector type that needs to 5187 // be split. Do that manually so we can get down to a legal type. 5188 while (getTypeAction(*DAG.getContext(), VecEVT) == 5189 TargetLowering::TypeSplitVector) { 5190 SDValue Lo, Hi; 5191 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5192 VecEVT = Lo.getValueType(); 5193 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5194 } 5195 5196 // TODO: The type may need to be widened rather than split. Or widened before 5197 // it can be split. 5198 if (!isTypeLegal(VecEVT)) 5199 return SDValue(); 5200 5201 MVT VecVT = VecEVT.getSimpleVT(); 5202 MVT VecEltVT = VecVT.getVectorElementType(); 5203 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5204 5205 MVT ContainerVT = VecVT; 5206 if (VecVT.isFixedLengthVector()) { 5207 ContainerVT = getContainerForFixedLengthVector(VecVT); 5208 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5209 } 5210 5211 MVT M1VT = getLMUL1VT(ContainerVT); 5212 MVT XLenVT = Subtarget.getXLenVT(); 5213 5214 SDValue Mask, VL; 5215 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5216 5217 SDValue NeutralElem = 5218 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5219 SDValue IdentitySplat = 5220 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5221 M1VT, DL, DAG, Subtarget); 5222 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5223 IdentitySplat, Mask, VL); 5224 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5225 DAG.getConstant(0, DL, XLenVT)); 5226 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5227 } 5228 5229 // Given a reduction op, this function returns the matching reduction opcode, 5230 // the vector SDValue and the scalar SDValue required to lower this to a 5231 // RISCVISD node. 5232 static std::tuple<unsigned, SDValue, SDValue> 5233 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5234 SDLoc DL(Op); 5235 auto Flags = Op->getFlags(); 5236 unsigned Opcode = Op.getOpcode(); 5237 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5238 switch (Opcode) { 5239 default: 5240 llvm_unreachable("Unhandled reduction"); 5241 case ISD::VECREDUCE_FADD: { 5242 // Use positive zero if we can. It is cheaper to materialize. 5243 SDValue Zero = 5244 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5245 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5246 } 5247 case ISD::VECREDUCE_SEQ_FADD: 5248 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5249 Op.getOperand(0)); 5250 case ISD::VECREDUCE_FMIN: 5251 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5252 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5253 case ISD::VECREDUCE_FMAX: 5254 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5255 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5256 } 5257 } 5258 5259 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5260 SelectionDAG &DAG) const { 5261 SDLoc DL(Op); 5262 MVT VecEltVT = Op.getSimpleValueType(); 5263 5264 unsigned RVVOpcode; 5265 SDValue VectorVal, ScalarVal; 5266 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5267 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5268 MVT VecVT = VectorVal.getSimpleValueType(); 5269 5270 MVT ContainerVT = VecVT; 5271 if (VecVT.isFixedLengthVector()) { 5272 ContainerVT = getContainerForFixedLengthVector(VecVT); 5273 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5274 } 5275 5276 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5277 MVT XLenVT = Subtarget.getXLenVT(); 5278 5279 SDValue Mask, VL; 5280 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5281 5282 SDValue ScalarSplat = 5283 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5284 M1VT, DL, DAG, Subtarget); 5285 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5286 VectorVal, ScalarSplat, Mask, VL); 5287 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5288 DAG.getConstant(0, DL, XLenVT)); 5289 } 5290 5291 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5292 switch (ISDOpcode) { 5293 default: 5294 llvm_unreachable("Unhandled reduction"); 5295 case ISD::VP_REDUCE_ADD: 5296 return RISCVISD::VECREDUCE_ADD_VL; 5297 case ISD::VP_REDUCE_UMAX: 5298 return RISCVISD::VECREDUCE_UMAX_VL; 5299 case ISD::VP_REDUCE_SMAX: 5300 return RISCVISD::VECREDUCE_SMAX_VL; 5301 case ISD::VP_REDUCE_UMIN: 5302 return RISCVISD::VECREDUCE_UMIN_VL; 5303 case ISD::VP_REDUCE_SMIN: 5304 return RISCVISD::VECREDUCE_SMIN_VL; 5305 case ISD::VP_REDUCE_AND: 5306 return RISCVISD::VECREDUCE_AND_VL; 5307 case ISD::VP_REDUCE_OR: 5308 return RISCVISD::VECREDUCE_OR_VL; 5309 case ISD::VP_REDUCE_XOR: 5310 return RISCVISD::VECREDUCE_XOR_VL; 5311 case ISD::VP_REDUCE_FADD: 5312 return RISCVISD::VECREDUCE_FADD_VL; 5313 case ISD::VP_REDUCE_SEQ_FADD: 5314 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5315 case ISD::VP_REDUCE_FMAX: 5316 return RISCVISD::VECREDUCE_FMAX_VL; 5317 case ISD::VP_REDUCE_FMIN: 5318 return RISCVISD::VECREDUCE_FMIN_VL; 5319 } 5320 } 5321 5322 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5323 SelectionDAG &DAG) const { 5324 SDLoc DL(Op); 5325 SDValue Vec = Op.getOperand(1); 5326 EVT VecEVT = Vec.getValueType(); 5327 5328 // TODO: The type may need to be widened rather than split. Or widened before 5329 // it can be split. 5330 if (!isTypeLegal(VecEVT)) 5331 return SDValue(); 5332 5333 MVT VecVT = VecEVT.getSimpleVT(); 5334 MVT VecEltVT = VecVT.getVectorElementType(); 5335 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5336 5337 MVT ContainerVT = VecVT; 5338 if (VecVT.isFixedLengthVector()) { 5339 ContainerVT = getContainerForFixedLengthVector(VecVT); 5340 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5341 } 5342 5343 SDValue VL = Op.getOperand(3); 5344 SDValue Mask = Op.getOperand(2); 5345 5346 MVT M1VT = getLMUL1VT(ContainerVT); 5347 MVT XLenVT = Subtarget.getXLenVT(); 5348 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5349 5350 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5351 DAG.getConstant(1, DL, XLenVT), M1VT, 5352 DL, DAG, Subtarget); 5353 SDValue Reduction = 5354 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5355 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5356 DAG.getConstant(0, DL, XLenVT)); 5357 if (!VecVT.isInteger()) 5358 return Elt0; 5359 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5360 } 5361 5362 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5363 SelectionDAG &DAG) const { 5364 SDValue Vec = Op.getOperand(0); 5365 SDValue SubVec = Op.getOperand(1); 5366 MVT VecVT = Vec.getSimpleValueType(); 5367 MVT SubVecVT = SubVec.getSimpleValueType(); 5368 5369 SDLoc DL(Op); 5370 MVT XLenVT = Subtarget.getXLenVT(); 5371 unsigned OrigIdx = Op.getConstantOperandVal(2); 5372 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5373 5374 // We don't have the ability to slide mask vectors up indexed by their i1 5375 // elements; the smallest we can do is i8. Often we are able to bitcast to 5376 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5377 // into a scalable one, we might not necessarily have enough scalable 5378 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5379 if (SubVecVT.getVectorElementType() == MVT::i1 && 5380 (OrigIdx != 0 || !Vec.isUndef())) { 5381 if (VecVT.getVectorMinNumElements() >= 8 && 5382 SubVecVT.getVectorMinNumElements() >= 8) { 5383 assert(OrigIdx % 8 == 0 && "Invalid index"); 5384 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5385 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5386 "Unexpected mask vector lowering"); 5387 OrigIdx /= 8; 5388 SubVecVT = 5389 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5390 SubVecVT.isScalableVector()); 5391 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5392 VecVT.isScalableVector()); 5393 Vec = DAG.getBitcast(VecVT, Vec); 5394 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5395 } else { 5396 // We can't slide this mask vector up indexed by its i1 elements. 5397 // This poses a problem when we wish to insert a scalable vector which 5398 // can't be re-expressed as a larger type. Just choose the slow path and 5399 // extend to a larger type, then truncate back down. 5400 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5401 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5402 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5403 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5404 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5405 Op.getOperand(2)); 5406 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5407 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5408 } 5409 } 5410 5411 // If the subvector vector is a fixed-length type, we cannot use subregister 5412 // manipulation to simplify the codegen; we don't know which register of a 5413 // LMUL group contains the specific subvector as we only know the minimum 5414 // register size. Therefore we must slide the vector group up the full 5415 // amount. 5416 if (SubVecVT.isFixedLengthVector()) { 5417 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5418 return Op; 5419 MVT ContainerVT = VecVT; 5420 if (VecVT.isFixedLengthVector()) { 5421 ContainerVT = getContainerForFixedLengthVector(VecVT); 5422 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5423 } 5424 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5425 DAG.getUNDEF(ContainerVT), SubVec, 5426 DAG.getConstant(0, DL, XLenVT)); 5427 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5428 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5429 return DAG.getBitcast(Op.getValueType(), SubVec); 5430 } 5431 SDValue Mask = 5432 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5433 // Set the vector length to only the number of elements we care about. Note 5434 // that for slideup this includes the offset. 5435 SDValue VL = 5436 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5437 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5438 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5439 SubVec, SlideupAmt, Mask, VL); 5440 if (VecVT.isFixedLengthVector()) 5441 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5442 return DAG.getBitcast(Op.getValueType(), Slideup); 5443 } 5444 5445 unsigned SubRegIdx, RemIdx; 5446 std::tie(SubRegIdx, RemIdx) = 5447 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5448 VecVT, SubVecVT, OrigIdx, TRI); 5449 5450 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5451 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5452 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5453 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5454 5455 // 1. If the Idx has been completely eliminated and this subvector's size is 5456 // a vector register or a multiple thereof, or the surrounding elements are 5457 // undef, then this is a subvector insert which naturally aligns to a vector 5458 // register. These can easily be handled using subregister manipulation. 5459 // 2. If the subvector is smaller than a vector register, then the insertion 5460 // must preserve the undisturbed elements of the register. We do this by 5461 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5462 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5463 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5464 // LMUL=1 type back into the larger vector (resolving to another subregister 5465 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5466 // to avoid allocating a large register group to hold our subvector. 5467 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5468 return Op; 5469 5470 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5471 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5472 // (in our case undisturbed). This means we can set up a subvector insertion 5473 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5474 // size of the subvector. 5475 MVT InterSubVT = VecVT; 5476 SDValue AlignedExtract = Vec; 5477 unsigned AlignedIdx = OrigIdx - RemIdx; 5478 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5479 InterSubVT = getLMUL1VT(VecVT); 5480 // Extract a subvector equal to the nearest full vector register type. This 5481 // should resolve to a EXTRACT_SUBREG instruction. 5482 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5483 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5484 } 5485 5486 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5487 // For scalable vectors this must be further multiplied by vscale. 5488 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5489 5490 SDValue Mask, VL; 5491 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5492 5493 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5494 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5495 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5496 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5497 5498 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5499 DAG.getUNDEF(InterSubVT), SubVec, 5500 DAG.getConstant(0, DL, XLenVT)); 5501 5502 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5503 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5504 5505 // If required, insert this subvector back into the correct vector register. 5506 // This should resolve to an INSERT_SUBREG instruction. 5507 if (VecVT.bitsGT(InterSubVT)) 5508 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5509 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5510 5511 // We might have bitcast from a mask type: cast back to the original type if 5512 // required. 5513 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5514 } 5515 5516 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5517 SelectionDAG &DAG) const { 5518 SDValue Vec = Op.getOperand(0); 5519 MVT SubVecVT = Op.getSimpleValueType(); 5520 MVT VecVT = Vec.getSimpleValueType(); 5521 5522 SDLoc DL(Op); 5523 MVT XLenVT = Subtarget.getXLenVT(); 5524 unsigned OrigIdx = Op.getConstantOperandVal(1); 5525 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5526 5527 // We don't have the ability to slide mask vectors down indexed by their i1 5528 // elements; the smallest we can do is i8. Often we are able to bitcast to 5529 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5530 // from a scalable one, we might not necessarily have enough scalable 5531 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5532 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5533 if (VecVT.getVectorMinNumElements() >= 8 && 5534 SubVecVT.getVectorMinNumElements() >= 8) { 5535 assert(OrigIdx % 8 == 0 && "Invalid index"); 5536 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5537 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5538 "Unexpected mask vector lowering"); 5539 OrigIdx /= 8; 5540 SubVecVT = 5541 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5542 SubVecVT.isScalableVector()); 5543 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5544 VecVT.isScalableVector()); 5545 Vec = DAG.getBitcast(VecVT, Vec); 5546 } else { 5547 // We can't slide this mask vector down, indexed by its i1 elements. 5548 // This poses a problem when we wish to extract a scalable vector which 5549 // can't be re-expressed as a larger type. Just choose the slow path and 5550 // extend to a larger type, then truncate back down. 5551 // TODO: We could probably improve this when extracting certain fixed 5552 // from fixed, where we can extract as i8 and shift the correct element 5553 // right to reach the desired subvector? 5554 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5555 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5556 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5557 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5558 Op.getOperand(1)); 5559 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5560 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5561 } 5562 } 5563 5564 // If the subvector vector is a fixed-length type, we cannot use subregister 5565 // manipulation to simplify the codegen; we don't know which register of a 5566 // LMUL group contains the specific subvector as we only know the minimum 5567 // register size. Therefore we must slide the vector group down the full 5568 // amount. 5569 if (SubVecVT.isFixedLengthVector()) { 5570 // With an index of 0 this is a cast-like subvector, which can be performed 5571 // with subregister operations. 5572 if (OrigIdx == 0) 5573 return Op; 5574 MVT ContainerVT = VecVT; 5575 if (VecVT.isFixedLengthVector()) { 5576 ContainerVT = getContainerForFixedLengthVector(VecVT); 5577 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5578 } 5579 SDValue Mask = 5580 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5581 // Set the vector length to only the number of elements we care about. This 5582 // avoids sliding down elements we're going to discard straight away. 5583 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5584 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5585 SDValue Slidedown = 5586 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5587 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5588 // Now we can use a cast-like subvector extract to get the result. 5589 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5590 DAG.getConstant(0, DL, XLenVT)); 5591 return DAG.getBitcast(Op.getValueType(), Slidedown); 5592 } 5593 5594 unsigned SubRegIdx, RemIdx; 5595 std::tie(SubRegIdx, RemIdx) = 5596 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5597 VecVT, SubVecVT, OrigIdx, TRI); 5598 5599 // If the Idx has been completely eliminated then this is a subvector extract 5600 // which naturally aligns to a vector register. These can easily be handled 5601 // using subregister manipulation. 5602 if (RemIdx == 0) 5603 return Op; 5604 5605 // Else we must shift our vector register directly to extract the subvector. 5606 // Do this using VSLIDEDOWN. 5607 5608 // If the vector type is an LMUL-group type, extract a subvector equal to the 5609 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5610 // instruction. 5611 MVT InterSubVT = VecVT; 5612 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5613 InterSubVT = getLMUL1VT(VecVT); 5614 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5615 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5616 } 5617 5618 // Slide this vector register down by the desired number of elements in order 5619 // to place the desired subvector starting at element 0. 5620 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5621 // For scalable vectors this must be further multiplied by vscale. 5622 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5623 5624 SDValue Mask, VL; 5625 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5626 SDValue Slidedown = 5627 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5628 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5629 5630 // Now the vector is in the right position, extract our final subvector. This 5631 // should resolve to a COPY. 5632 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5633 DAG.getConstant(0, DL, XLenVT)); 5634 5635 // We might have bitcast from a mask type: cast back to the original type if 5636 // required. 5637 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5638 } 5639 5640 // Lower step_vector to the vid instruction. Any non-identity step value must 5641 // be accounted for my manual expansion. 5642 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5643 SelectionDAG &DAG) const { 5644 SDLoc DL(Op); 5645 MVT VT = Op.getSimpleValueType(); 5646 MVT XLenVT = Subtarget.getXLenVT(); 5647 SDValue Mask, VL; 5648 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5649 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5650 uint64_t StepValImm = Op.getConstantOperandVal(0); 5651 if (StepValImm != 1) { 5652 if (isPowerOf2_64(StepValImm)) { 5653 SDValue StepVal = 5654 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5655 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5656 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5657 } else { 5658 SDValue StepVal = lowerScalarSplat( 5659 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5660 VL, VT, DL, DAG, Subtarget); 5661 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5662 } 5663 } 5664 return StepVec; 5665 } 5666 5667 // Implement vector_reverse using vrgather.vv with indices determined by 5668 // subtracting the id of each element from (VLMAX-1). This will convert 5669 // the indices like so: 5670 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5671 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5672 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5673 SelectionDAG &DAG) const { 5674 SDLoc DL(Op); 5675 MVT VecVT = Op.getSimpleValueType(); 5676 if (VecVT.getVectorElementType() == MVT::i1) { 5677 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5678 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5679 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5680 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5681 } 5682 unsigned EltSize = VecVT.getScalarSizeInBits(); 5683 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5684 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5685 unsigned MaxVLMAX = 5686 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5687 5688 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5689 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5690 5691 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5692 // to use vrgatherei16.vv. 5693 // TODO: It's also possible to use vrgatherei16.vv for other types to 5694 // decrease register width for the index calculation. 5695 if (MaxVLMAX > 256 && EltSize == 8) { 5696 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5697 // Reverse each half, then reassemble them in reverse order. 5698 // NOTE: It's also possible that after splitting that VLMAX no longer 5699 // requires vrgatherei16.vv. 5700 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5701 SDValue Lo, Hi; 5702 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5703 EVT LoVT, HiVT; 5704 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5705 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5706 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5707 // Reassemble the low and high pieces reversed. 5708 // FIXME: This is a CONCAT_VECTORS. 5709 SDValue Res = 5710 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5711 DAG.getIntPtrConstant(0, DL)); 5712 return DAG.getNode( 5713 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5714 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5715 } 5716 5717 // Just promote the int type to i16 which will double the LMUL. 5718 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5719 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5720 } 5721 5722 MVT XLenVT = Subtarget.getXLenVT(); 5723 SDValue Mask, VL; 5724 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5725 5726 // Calculate VLMAX-1 for the desired SEW. 5727 unsigned MinElts = VecVT.getVectorMinNumElements(); 5728 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5729 DAG.getConstant(MinElts, DL, XLenVT)); 5730 SDValue VLMinus1 = 5731 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5732 5733 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5734 bool IsRV32E64 = 5735 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5736 SDValue SplatVL; 5737 if (!IsRV32E64) 5738 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5739 else 5740 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5741 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5742 5743 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5744 SDValue Indices = 5745 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5746 5747 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5748 DAG.getUNDEF(VecVT), VL); 5749 } 5750 5751 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5752 SelectionDAG &DAG) const { 5753 SDLoc DL(Op); 5754 SDValue V1 = Op.getOperand(0); 5755 SDValue V2 = Op.getOperand(1); 5756 MVT XLenVT = Subtarget.getXLenVT(); 5757 MVT VecVT = Op.getSimpleValueType(); 5758 5759 unsigned MinElts = VecVT.getVectorMinNumElements(); 5760 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5761 DAG.getConstant(MinElts, DL, XLenVT)); 5762 5763 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5764 SDValue DownOffset, UpOffset; 5765 if (ImmValue >= 0) { 5766 // The operand is a TargetConstant, we need to rebuild it as a regular 5767 // constant. 5768 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5769 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5770 } else { 5771 // The operand is a TargetConstant, we need to rebuild it as a regular 5772 // constant rather than negating the original operand. 5773 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5774 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5775 } 5776 5777 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5778 5779 SDValue SlideDown = 5780 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5781 DownOffset, TrueMask, UpOffset); 5782 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5783 TrueMask, DAG.getRegister(RISCV::X0, XLenVT)); 5784 } 5785 5786 SDValue 5787 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5788 SelectionDAG &DAG) const { 5789 SDLoc DL(Op); 5790 auto *Load = cast<LoadSDNode>(Op); 5791 5792 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5793 Load->getMemoryVT(), 5794 *Load->getMemOperand()) && 5795 "Expecting a correctly-aligned load"); 5796 5797 MVT VT = Op.getSimpleValueType(); 5798 MVT XLenVT = Subtarget.getXLenVT(); 5799 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5800 5801 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5802 5803 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5804 SDValue IntID = DAG.getTargetConstant( 5805 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5806 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5807 if (!IsMaskOp) 5808 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5809 Ops.push_back(Load->getBasePtr()); 5810 Ops.push_back(VL); 5811 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5812 SDValue NewLoad = 5813 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5814 Load->getMemoryVT(), Load->getMemOperand()); 5815 5816 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5817 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5818 } 5819 5820 SDValue 5821 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5822 SelectionDAG &DAG) const { 5823 SDLoc DL(Op); 5824 auto *Store = cast<StoreSDNode>(Op); 5825 5826 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5827 Store->getMemoryVT(), 5828 *Store->getMemOperand()) && 5829 "Expecting a correctly-aligned store"); 5830 5831 SDValue StoreVal = Store->getValue(); 5832 MVT VT = StoreVal.getSimpleValueType(); 5833 MVT XLenVT = Subtarget.getXLenVT(); 5834 5835 // If the size less than a byte, we need to pad with zeros to make a byte. 5836 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5837 VT = MVT::v8i1; 5838 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5839 DAG.getConstant(0, DL, VT), StoreVal, 5840 DAG.getIntPtrConstant(0, DL)); 5841 } 5842 5843 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5844 5845 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5846 5847 SDValue NewValue = 5848 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5849 5850 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5851 SDValue IntID = DAG.getTargetConstant( 5852 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5853 return DAG.getMemIntrinsicNode( 5854 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5855 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5856 Store->getMemoryVT(), Store->getMemOperand()); 5857 } 5858 5859 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5860 SelectionDAG &DAG) const { 5861 SDLoc DL(Op); 5862 MVT VT = Op.getSimpleValueType(); 5863 5864 const auto *MemSD = cast<MemSDNode>(Op); 5865 EVT MemVT = MemSD->getMemoryVT(); 5866 MachineMemOperand *MMO = MemSD->getMemOperand(); 5867 SDValue Chain = MemSD->getChain(); 5868 SDValue BasePtr = MemSD->getBasePtr(); 5869 5870 SDValue Mask, PassThru, VL; 5871 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5872 Mask = VPLoad->getMask(); 5873 PassThru = DAG.getUNDEF(VT); 5874 VL = VPLoad->getVectorLength(); 5875 } else { 5876 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5877 Mask = MLoad->getMask(); 5878 PassThru = MLoad->getPassThru(); 5879 } 5880 5881 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5882 5883 MVT XLenVT = Subtarget.getXLenVT(); 5884 5885 MVT ContainerVT = VT; 5886 if (VT.isFixedLengthVector()) { 5887 ContainerVT = getContainerForFixedLengthVector(VT); 5888 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5889 if (!IsUnmasked) { 5890 MVT MaskVT = getMaskTypeFor(ContainerVT); 5891 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5892 } 5893 } 5894 5895 if (!VL) 5896 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5897 5898 unsigned IntID = 5899 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5900 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5901 if (IsUnmasked) 5902 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5903 else 5904 Ops.push_back(PassThru); 5905 Ops.push_back(BasePtr); 5906 if (!IsUnmasked) 5907 Ops.push_back(Mask); 5908 Ops.push_back(VL); 5909 if (!IsUnmasked) 5910 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5911 5912 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5913 5914 SDValue Result = 5915 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5916 Chain = Result.getValue(1); 5917 5918 if (VT.isFixedLengthVector()) 5919 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5920 5921 return DAG.getMergeValues({Result, Chain}, DL); 5922 } 5923 5924 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5925 SelectionDAG &DAG) const { 5926 SDLoc DL(Op); 5927 5928 const auto *MemSD = cast<MemSDNode>(Op); 5929 EVT MemVT = MemSD->getMemoryVT(); 5930 MachineMemOperand *MMO = MemSD->getMemOperand(); 5931 SDValue Chain = MemSD->getChain(); 5932 SDValue BasePtr = MemSD->getBasePtr(); 5933 SDValue Val, Mask, VL; 5934 5935 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5936 Val = VPStore->getValue(); 5937 Mask = VPStore->getMask(); 5938 VL = VPStore->getVectorLength(); 5939 } else { 5940 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5941 Val = MStore->getValue(); 5942 Mask = MStore->getMask(); 5943 } 5944 5945 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5946 5947 MVT VT = Val.getSimpleValueType(); 5948 MVT XLenVT = Subtarget.getXLenVT(); 5949 5950 MVT ContainerVT = VT; 5951 if (VT.isFixedLengthVector()) { 5952 ContainerVT = getContainerForFixedLengthVector(VT); 5953 5954 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5955 if (!IsUnmasked) { 5956 MVT MaskVT = getMaskTypeFor(ContainerVT); 5957 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5958 } 5959 } 5960 5961 if (!VL) 5962 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5963 5964 unsigned IntID = 5965 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5966 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5967 Ops.push_back(Val); 5968 Ops.push_back(BasePtr); 5969 if (!IsUnmasked) 5970 Ops.push_back(Mask); 5971 Ops.push_back(VL); 5972 5973 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5974 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5975 } 5976 5977 SDValue 5978 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5979 SelectionDAG &DAG) const { 5980 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5981 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5982 5983 MVT VT = Op.getSimpleValueType(); 5984 5985 SDValue Op1 = 5986 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5987 SDValue Op2 = 5988 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5989 5990 SDLoc DL(Op); 5991 SDValue VL = 5992 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5993 5994 MVT MaskVT = getMaskTypeFor(ContainerVT); 5995 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5996 5997 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5998 Op.getOperand(2), Mask, VL); 5999 6000 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 6001 } 6002 6003 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6004 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6005 MVT VT = Op.getSimpleValueType(); 6006 6007 if (VT.getVectorElementType() == MVT::i1) 6008 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 6009 6010 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 6011 } 6012 6013 SDValue 6014 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6015 SelectionDAG &DAG) const { 6016 unsigned Opc; 6017 switch (Op.getOpcode()) { 6018 default: llvm_unreachable("Unexpected opcode!"); 6019 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6020 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6021 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6022 } 6023 6024 return lowerToScalableOp(Op, DAG, Opc); 6025 } 6026 6027 // Lower vector ABS to smax(X, sub(0, X)). 6028 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6029 SDLoc DL(Op); 6030 MVT VT = Op.getSimpleValueType(); 6031 SDValue X = Op.getOperand(0); 6032 6033 assert(VT.isFixedLengthVector() && "Unexpected type"); 6034 6035 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6036 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6037 6038 SDValue Mask, VL; 6039 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6040 6041 SDValue SplatZero = DAG.getNode( 6042 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6043 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6044 SDValue NegX = 6045 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6046 SDValue Max = 6047 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6048 6049 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6050 } 6051 6052 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6053 SDValue Op, SelectionDAG &DAG) const { 6054 SDLoc DL(Op); 6055 MVT VT = Op.getSimpleValueType(); 6056 SDValue Mag = Op.getOperand(0); 6057 SDValue Sign = Op.getOperand(1); 6058 assert(Mag.getValueType() == Sign.getValueType() && 6059 "Can only handle COPYSIGN with matching types."); 6060 6061 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6062 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6063 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6064 6065 SDValue Mask, VL; 6066 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6067 6068 SDValue CopySign = 6069 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6070 6071 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6072 } 6073 6074 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6075 SDValue Op, SelectionDAG &DAG) const { 6076 MVT VT = Op.getSimpleValueType(); 6077 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6078 6079 MVT I1ContainerVT = 6080 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6081 6082 SDValue CC = 6083 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6084 SDValue Op1 = 6085 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6086 SDValue Op2 = 6087 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6088 6089 SDLoc DL(Op); 6090 SDValue Mask, VL; 6091 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6092 6093 SDValue Select = 6094 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6095 6096 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6097 } 6098 6099 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6100 unsigned NewOpc, 6101 bool HasMask) const { 6102 MVT VT = Op.getSimpleValueType(); 6103 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6104 6105 // Create list of operands by converting existing ones to scalable types. 6106 SmallVector<SDValue, 6> Ops; 6107 for (const SDValue &V : Op->op_values()) { 6108 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6109 6110 // Pass through non-vector operands. 6111 if (!V.getValueType().isVector()) { 6112 Ops.push_back(V); 6113 continue; 6114 } 6115 6116 // "cast" fixed length vector to a scalable vector. 6117 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6118 "Only fixed length vectors are supported!"); 6119 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6120 } 6121 6122 SDLoc DL(Op); 6123 SDValue Mask, VL; 6124 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6125 if (HasMask) 6126 Ops.push_back(Mask); 6127 Ops.push_back(VL); 6128 6129 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6130 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6131 } 6132 6133 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6134 // * Operands of each node are assumed to be in the same order. 6135 // * The EVL operand is promoted from i32 to i64 on RV64. 6136 // * Fixed-length vectors are converted to their scalable-vector container 6137 // types. 6138 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6139 unsigned RISCVISDOpc) const { 6140 SDLoc DL(Op); 6141 MVT VT = Op.getSimpleValueType(); 6142 SmallVector<SDValue, 4> Ops; 6143 6144 for (const auto &OpIdx : enumerate(Op->ops())) { 6145 SDValue V = OpIdx.value(); 6146 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6147 // Pass through operands which aren't fixed-length vectors. 6148 if (!V.getValueType().isFixedLengthVector()) { 6149 Ops.push_back(V); 6150 continue; 6151 } 6152 // "cast" fixed length vector to a scalable vector. 6153 MVT OpVT = V.getSimpleValueType(); 6154 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6155 assert(useRVVForFixedLengthVectorVT(OpVT) && 6156 "Only fixed length vectors are supported!"); 6157 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6158 } 6159 6160 if (!VT.isFixedLengthVector()) 6161 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6162 6163 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6164 6165 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6166 6167 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6168 } 6169 6170 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6171 SelectionDAG &DAG) const { 6172 SDLoc DL(Op); 6173 MVT VT = Op.getSimpleValueType(); 6174 6175 SDValue Src = Op.getOperand(0); 6176 // NOTE: Mask is dropped. 6177 SDValue VL = Op.getOperand(2); 6178 6179 MVT ContainerVT = VT; 6180 if (VT.isFixedLengthVector()) { 6181 ContainerVT = getContainerForFixedLengthVector(VT); 6182 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6183 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6184 } 6185 6186 MVT XLenVT = Subtarget.getXLenVT(); 6187 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6188 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6189 DAG.getUNDEF(ContainerVT), Zero, VL); 6190 6191 SDValue SplatValue = DAG.getConstant( 6192 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6193 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6194 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6195 6196 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6197 Splat, ZeroSplat, VL); 6198 if (!VT.isFixedLengthVector()) 6199 return Result; 6200 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6201 } 6202 6203 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6204 SelectionDAG &DAG) const { 6205 SDLoc DL(Op); 6206 MVT VT = Op.getSimpleValueType(); 6207 6208 SDValue Op1 = Op.getOperand(0); 6209 SDValue Op2 = Op.getOperand(1); 6210 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6211 // NOTE: Mask is dropped. 6212 SDValue VL = Op.getOperand(4); 6213 6214 MVT ContainerVT = VT; 6215 if (VT.isFixedLengthVector()) { 6216 ContainerVT = getContainerForFixedLengthVector(VT); 6217 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6218 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6219 } 6220 6221 SDValue Result; 6222 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6223 6224 switch (Condition) { 6225 default: 6226 break; 6227 // X != Y --> (X^Y) 6228 case ISD::SETNE: 6229 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6230 break; 6231 // X == Y --> ~(X^Y) 6232 case ISD::SETEQ: { 6233 SDValue Temp = 6234 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6235 Result = 6236 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6237 break; 6238 } 6239 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6240 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6241 case ISD::SETGT: 6242 case ISD::SETULT: { 6243 SDValue Temp = 6244 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6245 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6246 break; 6247 } 6248 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6249 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6250 case ISD::SETLT: 6251 case ISD::SETUGT: { 6252 SDValue Temp = 6253 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6254 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6255 break; 6256 } 6257 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6258 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6259 case ISD::SETGE: 6260 case ISD::SETULE: { 6261 SDValue Temp = 6262 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6263 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6264 break; 6265 } 6266 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6267 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6268 case ISD::SETLE: 6269 case ISD::SETUGE: { 6270 SDValue Temp = 6271 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6272 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6273 break; 6274 } 6275 } 6276 6277 if (!VT.isFixedLengthVector()) 6278 return Result; 6279 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6280 } 6281 6282 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6283 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6284 unsigned RISCVISDOpc) const { 6285 SDLoc DL(Op); 6286 6287 SDValue Src = Op.getOperand(0); 6288 SDValue Mask = Op.getOperand(1); 6289 SDValue VL = Op.getOperand(2); 6290 6291 MVT DstVT = Op.getSimpleValueType(); 6292 MVT SrcVT = Src.getSimpleValueType(); 6293 if (DstVT.isFixedLengthVector()) { 6294 DstVT = getContainerForFixedLengthVector(DstVT); 6295 SrcVT = getContainerForFixedLengthVector(SrcVT); 6296 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6297 MVT MaskVT = getMaskTypeFor(DstVT); 6298 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6299 } 6300 6301 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6302 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6303 ? RISCVISD::VSEXT_VL 6304 : RISCVISD::VZEXT_VL; 6305 6306 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6307 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6308 6309 SDValue Result; 6310 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6311 if (SrcVT.isInteger()) { 6312 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6313 6314 // Do we need to do any pre-widening before converting? 6315 if (SrcEltSize == 1) { 6316 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6317 MVT XLenVT = Subtarget.getXLenVT(); 6318 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6319 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6320 DAG.getUNDEF(IntVT), Zero, VL); 6321 SDValue One = DAG.getConstant( 6322 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6323 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6324 DAG.getUNDEF(IntVT), One, VL); 6325 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6326 ZeroSplat, VL); 6327 } else if (DstEltSize > (2 * SrcEltSize)) { 6328 // Widen before converting. 6329 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6330 DstVT.getVectorElementCount()); 6331 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6332 } 6333 6334 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6335 } else { 6336 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6337 "Wrong input/output vector types"); 6338 6339 // Convert f16 to f32 then convert f32 to i64. 6340 if (DstEltSize > (2 * SrcEltSize)) { 6341 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6342 MVT InterimFVT = 6343 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6344 Src = 6345 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6346 } 6347 6348 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6349 } 6350 } else { // Narrowing + Conversion 6351 if (SrcVT.isInteger()) { 6352 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6353 // First do a narrowing convert to an FP type half the size, then round 6354 // the FP type to a small FP type if needed. 6355 6356 MVT InterimFVT = DstVT; 6357 if (SrcEltSize > (2 * DstEltSize)) { 6358 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6359 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6360 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6361 } 6362 6363 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6364 6365 if (InterimFVT != DstVT) { 6366 Src = Result; 6367 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6368 } 6369 } else { 6370 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6371 "Wrong input/output vector types"); 6372 // First do a narrowing conversion to an integer half the size, then 6373 // truncate if needed. 6374 6375 if (DstEltSize == 1) { 6376 // First convert to the same size integer, then convert to mask using 6377 // setcc. 6378 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6379 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6380 DstVT.getVectorElementCount()); 6381 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6382 6383 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6384 // otherwise the conversion was undefined. 6385 MVT XLenVT = Subtarget.getXLenVT(); 6386 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6387 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6388 DAG.getUNDEF(InterimIVT), SplatZero); 6389 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6390 DAG.getCondCode(ISD::SETNE), Mask, VL); 6391 } else { 6392 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6393 DstVT.getVectorElementCount()); 6394 6395 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6396 6397 while (InterimIVT != DstVT) { 6398 SrcEltSize /= 2; 6399 Src = Result; 6400 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6401 DstVT.getVectorElementCount()); 6402 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6403 Src, Mask, VL); 6404 } 6405 } 6406 } 6407 } 6408 6409 MVT VT = Op.getSimpleValueType(); 6410 if (!VT.isFixedLengthVector()) 6411 return Result; 6412 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6413 } 6414 6415 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6416 unsigned MaskOpc, 6417 unsigned VecOpc) const { 6418 MVT VT = Op.getSimpleValueType(); 6419 if (VT.getVectorElementType() != MVT::i1) 6420 return lowerVPOp(Op, DAG, VecOpc); 6421 6422 // It is safe to drop mask parameter as masked-off elements are undef. 6423 SDValue Op1 = Op->getOperand(0); 6424 SDValue Op2 = Op->getOperand(1); 6425 SDValue VL = Op->getOperand(3); 6426 6427 MVT ContainerVT = VT; 6428 const bool IsFixed = VT.isFixedLengthVector(); 6429 if (IsFixed) { 6430 ContainerVT = getContainerForFixedLengthVector(VT); 6431 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6432 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6433 } 6434 6435 SDLoc DL(Op); 6436 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6437 if (!IsFixed) 6438 return Val; 6439 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6440 } 6441 6442 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6443 // matched to a RVV indexed load. The RVV indexed load instructions only 6444 // support the "unsigned unscaled" addressing mode; indices are implicitly 6445 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6446 // signed or scaled indexing is extended to the XLEN value type and scaled 6447 // accordingly. 6448 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6449 SelectionDAG &DAG) const { 6450 SDLoc DL(Op); 6451 MVT VT = Op.getSimpleValueType(); 6452 6453 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6454 EVT MemVT = MemSD->getMemoryVT(); 6455 MachineMemOperand *MMO = MemSD->getMemOperand(); 6456 SDValue Chain = MemSD->getChain(); 6457 SDValue BasePtr = MemSD->getBasePtr(); 6458 6459 ISD::LoadExtType LoadExtType; 6460 SDValue Index, Mask, PassThru, VL; 6461 6462 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6463 Index = VPGN->getIndex(); 6464 Mask = VPGN->getMask(); 6465 PassThru = DAG.getUNDEF(VT); 6466 VL = VPGN->getVectorLength(); 6467 // VP doesn't support extending loads. 6468 LoadExtType = ISD::NON_EXTLOAD; 6469 } else { 6470 // Else it must be a MGATHER. 6471 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6472 Index = MGN->getIndex(); 6473 Mask = MGN->getMask(); 6474 PassThru = MGN->getPassThru(); 6475 LoadExtType = MGN->getExtensionType(); 6476 } 6477 6478 MVT IndexVT = Index.getSimpleValueType(); 6479 MVT XLenVT = Subtarget.getXLenVT(); 6480 6481 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6482 "Unexpected VTs!"); 6483 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6484 // Targets have to explicitly opt-in for extending vector loads. 6485 assert(LoadExtType == ISD::NON_EXTLOAD && 6486 "Unexpected extending MGATHER/VP_GATHER"); 6487 (void)LoadExtType; 6488 6489 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6490 // the selection of the masked intrinsics doesn't do this for us. 6491 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6492 6493 MVT ContainerVT = VT; 6494 if (VT.isFixedLengthVector()) { 6495 ContainerVT = getContainerForFixedLengthVector(VT); 6496 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6497 ContainerVT.getVectorElementCount()); 6498 6499 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6500 6501 if (!IsUnmasked) { 6502 MVT MaskVT = getMaskTypeFor(ContainerVT); 6503 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6504 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6505 } 6506 } 6507 6508 if (!VL) 6509 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6510 6511 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6512 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6513 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6514 VL); 6515 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6516 TrueMask, VL); 6517 } 6518 6519 unsigned IntID = 6520 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6521 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6522 if (IsUnmasked) 6523 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6524 else 6525 Ops.push_back(PassThru); 6526 Ops.push_back(BasePtr); 6527 Ops.push_back(Index); 6528 if (!IsUnmasked) 6529 Ops.push_back(Mask); 6530 Ops.push_back(VL); 6531 if (!IsUnmasked) 6532 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6533 6534 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6535 SDValue Result = 6536 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6537 Chain = Result.getValue(1); 6538 6539 if (VT.isFixedLengthVector()) 6540 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6541 6542 return DAG.getMergeValues({Result, Chain}, DL); 6543 } 6544 6545 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6546 // matched to a RVV indexed store. The RVV indexed store instructions only 6547 // support the "unsigned unscaled" addressing mode; indices are implicitly 6548 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6549 // signed or scaled indexing is extended to the XLEN value type and scaled 6550 // accordingly. 6551 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6552 SelectionDAG &DAG) const { 6553 SDLoc DL(Op); 6554 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6555 EVT MemVT = MemSD->getMemoryVT(); 6556 MachineMemOperand *MMO = MemSD->getMemOperand(); 6557 SDValue Chain = MemSD->getChain(); 6558 SDValue BasePtr = MemSD->getBasePtr(); 6559 6560 bool IsTruncatingStore = false; 6561 SDValue Index, Mask, Val, VL; 6562 6563 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6564 Index = VPSN->getIndex(); 6565 Mask = VPSN->getMask(); 6566 Val = VPSN->getValue(); 6567 VL = VPSN->getVectorLength(); 6568 // VP doesn't support truncating stores. 6569 IsTruncatingStore = false; 6570 } else { 6571 // Else it must be a MSCATTER. 6572 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6573 Index = MSN->getIndex(); 6574 Mask = MSN->getMask(); 6575 Val = MSN->getValue(); 6576 IsTruncatingStore = MSN->isTruncatingStore(); 6577 } 6578 6579 MVT VT = Val.getSimpleValueType(); 6580 MVT IndexVT = Index.getSimpleValueType(); 6581 MVT XLenVT = Subtarget.getXLenVT(); 6582 6583 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6584 "Unexpected VTs!"); 6585 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6586 // Targets have to explicitly opt-in for extending vector loads and 6587 // truncating vector stores. 6588 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6589 (void)IsTruncatingStore; 6590 6591 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6592 // the selection of the masked intrinsics doesn't do this for us. 6593 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6594 6595 MVT ContainerVT = VT; 6596 if (VT.isFixedLengthVector()) { 6597 ContainerVT = getContainerForFixedLengthVector(VT); 6598 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6599 ContainerVT.getVectorElementCount()); 6600 6601 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6602 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6603 6604 if (!IsUnmasked) { 6605 MVT MaskVT = getMaskTypeFor(ContainerVT); 6606 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6607 } 6608 } 6609 6610 if (!VL) 6611 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6612 6613 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6614 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6615 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6616 VL); 6617 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6618 TrueMask, VL); 6619 } 6620 6621 unsigned IntID = 6622 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6623 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6624 Ops.push_back(Val); 6625 Ops.push_back(BasePtr); 6626 Ops.push_back(Index); 6627 if (!IsUnmasked) 6628 Ops.push_back(Mask); 6629 Ops.push_back(VL); 6630 6631 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6632 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6633 } 6634 6635 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6636 SelectionDAG &DAG) const { 6637 const MVT XLenVT = Subtarget.getXLenVT(); 6638 SDLoc DL(Op); 6639 SDValue Chain = Op->getOperand(0); 6640 SDValue SysRegNo = DAG.getTargetConstant( 6641 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6642 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6643 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6644 6645 // Encoding used for rounding mode in RISCV differs from that used in 6646 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6647 // table, which consists of a sequence of 4-bit fields, each representing 6648 // corresponding FLT_ROUNDS mode. 6649 static const int Table = 6650 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6651 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6652 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6653 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6654 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6655 6656 SDValue Shift = 6657 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6658 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6659 DAG.getConstant(Table, DL, XLenVT), Shift); 6660 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6661 DAG.getConstant(7, DL, XLenVT)); 6662 6663 return DAG.getMergeValues({Masked, Chain}, DL); 6664 } 6665 6666 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6667 SelectionDAG &DAG) const { 6668 const MVT XLenVT = Subtarget.getXLenVT(); 6669 SDLoc DL(Op); 6670 SDValue Chain = Op->getOperand(0); 6671 SDValue RMValue = Op->getOperand(1); 6672 SDValue SysRegNo = DAG.getTargetConstant( 6673 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6674 6675 // Encoding used for rounding mode in RISCV differs from that used in 6676 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6677 // a table, which consists of a sequence of 4-bit fields, each representing 6678 // corresponding RISCV mode. 6679 static const unsigned Table = 6680 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6681 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6682 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6683 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6684 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6685 6686 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6687 DAG.getConstant(2, DL, XLenVT)); 6688 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6689 DAG.getConstant(Table, DL, XLenVT), Shift); 6690 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6691 DAG.getConstant(0x7, DL, XLenVT)); 6692 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6693 RMValue); 6694 } 6695 6696 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6697 SelectionDAG &DAG) const { 6698 MachineFunction &MF = DAG.getMachineFunction(); 6699 6700 bool isRISCV64 = Subtarget.is64Bit(); 6701 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6702 6703 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6704 return DAG.getFrameIndex(FI, PtrVT); 6705 } 6706 6707 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6708 switch (IntNo) { 6709 default: 6710 llvm_unreachable("Unexpected Intrinsic"); 6711 case Intrinsic::riscv_bcompress: 6712 return RISCVISD::BCOMPRESSW; 6713 case Intrinsic::riscv_bdecompress: 6714 return RISCVISD::BDECOMPRESSW; 6715 case Intrinsic::riscv_bfp: 6716 return RISCVISD::BFPW; 6717 case Intrinsic::riscv_fsl: 6718 return RISCVISD::FSLW; 6719 case Intrinsic::riscv_fsr: 6720 return RISCVISD::FSRW; 6721 } 6722 } 6723 6724 // Converts the given intrinsic to a i64 operation with any extension. 6725 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6726 unsigned IntNo) { 6727 SDLoc DL(N); 6728 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6729 // Deal with the Instruction Operands 6730 SmallVector<SDValue, 3> NewOps; 6731 for (SDValue Op : drop_begin(N->ops())) 6732 // Promote the operand to i64 type 6733 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6734 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6735 // ReplaceNodeResults requires we maintain the same type for the return value. 6736 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6737 } 6738 6739 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6740 // form of the given Opcode. 6741 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6742 switch (Opcode) { 6743 default: 6744 llvm_unreachable("Unexpected opcode"); 6745 case ISD::SHL: 6746 return RISCVISD::SLLW; 6747 case ISD::SRA: 6748 return RISCVISD::SRAW; 6749 case ISD::SRL: 6750 return RISCVISD::SRLW; 6751 case ISD::SDIV: 6752 return RISCVISD::DIVW; 6753 case ISD::UDIV: 6754 return RISCVISD::DIVUW; 6755 case ISD::UREM: 6756 return RISCVISD::REMUW; 6757 case ISD::ROTL: 6758 return RISCVISD::ROLW; 6759 case ISD::ROTR: 6760 return RISCVISD::RORW; 6761 } 6762 } 6763 6764 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6765 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6766 // otherwise be promoted to i64, making it difficult to select the 6767 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6768 // type i8/i16/i32 is lost. 6769 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6770 unsigned ExtOpc = ISD::ANY_EXTEND) { 6771 SDLoc DL(N); 6772 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6773 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6774 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6775 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6776 // ReplaceNodeResults requires we maintain the same type for the return value. 6777 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6778 } 6779 6780 // Converts the given 32-bit operation to a i64 operation with signed extension 6781 // semantic to reduce the signed extension instructions. 6782 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6783 SDLoc DL(N); 6784 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6785 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6786 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6787 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6788 DAG.getValueType(MVT::i32)); 6789 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6790 } 6791 6792 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6793 SmallVectorImpl<SDValue> &Results, 6794 SelectionDAG &DAG) const { 6795 SDLoc DL(N); 6796 switch (N->getOpcode()) { 6797 default: 6798 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6799 case ISD::STRICT_FP_TO_SINT: 6800 case ISD::STRICT_FP_TO_UINT: 6801 case ISD::FP_TO_SINT: 6802 case ISD::FP_TO_UINT: { 6803 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6804 "Unexpected custom legalisation"); 6805 bool IsStrict = N->isStrictFPOpcode(); 6806 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6807 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6808 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6809 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6810 TargetLowering::TypeSoftenFloat) { 6811 if (!isTypeLegal(Op0.getValueType())) 6812 return; 6813 if (IsStrict) { 6814 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6815 : RISCVISD::STRICT_FCVT_WU_RV64; 6816 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6817 SDValue Res = DAG.getNode( 6818 Opc, DL, VTs, N->getOperand(0), Op0, 6819 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6820 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6821 Results.push_back(Res.getValue(1)); 6822 return; 6823 } 6824 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6825 SDValue Res = 6826 DAG.getNode(Opc, DL, MVT::i64, Op0, 6827 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6828 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6829 return; 6830 } 6831 // If the FP type needs to be softened, emit a library call using the 'si' 6832 // version. If we left it to default legalization we'd end up with 'di'. If 6833 // the FP type doesn't need to be softened just let generic type 6834 // legalization promote the result type. 6835 RTLIB::Libcall LC; 6836 if (IsSigned) 6837 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6838 else 6839 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6840 MakeLibCallOptions CallOptions; 6841 EVT OpVT = Op0.getValueType(); 6842 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6843 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6844 SDValue Result; 6845 std::tie(Result, Chain) = 6846 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6847 Results.push_back(Result); 6848 if (IsStrict) 6849 Results.push_back(Chain); 6850 break; 6851 } 6852 case ISD::READCYCLECOUNTER: { 6853 assert(!Subtarget.is64Bit() && 6854 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6855 6856 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6857 SDValue RCW = 6858 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6859 6860 Results.push_back( 6861 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6862 Results.push_back(RCW.getValue(2)); 6863 break; 6864 } 6865 case ISD::MUL: { 6866 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6867 unsigned XLen = Subtarget.getXLen(); 6868 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6869 if (Size > XLen) { 6870 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6871 SDValue LHS = N->getOperand(0); 6872 SDValue RHS = N->getOperand(1); 6873 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6874 6875 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6876 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6877 // We need exactly one side to be unsigned. 6878 if (LHSIsU == RHSIsU) 6879 return; 6880 6881 auto MakeMULPair = [&](SDValue S, SDValue U) { 6882 MVT XLenVT = Subtarget.getXLenVT(); 6883 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6884 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6885 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6886 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6887 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6888 }; 6889 6890 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6891 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6892 6893 // The other operand should be signed, but still prefer MULH when 6894 // possible. 6895 if (RHSIsU && LHSIsS && !RHSIsS) 6896 Results.push_back(MakeMULPair(LHS, RHS)); 6897 else if (LHSIsU && RHSIsS && !LHSIsS) 6898 Results.push_back(MakeMULPair(RHS, LHS)); 6899 6900 return; 6901 } 6902 LLVM_FALLTHROUGH; 6903 } 6904 case ISD::ADD: 6905 case ISD::SUB: 6906 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6907 "Unexpected custom legalisation"); 6908 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6909 break; 6910 case ISD::SHL: 6911 case ISD::SRA: 6912 case ISD::SRL: 6913 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6914 "Unexpected custom legalisation"); 6915 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6916 // If we can use a BSET instruction, allow default promotion to apply. 6917 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6918 isOneConstant(N->getOperand(0))) 6919 break; 6920 Results.push_back(customLegalizeToWOp(N, DAG)); 6921 break; 6922 } 6923 6924 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6925 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6926 // shift amount. 6927 if (N->getOpcode() == ISD::SHL) { 6928 SDLoc DL(N); 6929 SDValue NewOp0 = 6930 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6931 SDValue NewOp1 = 6932 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6933 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6934 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6935 DAG.getValueType(MVT::i32)); 6936 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6937 } 6938 6939 break; 6940 case ISD::ROTL: 6941 case ISD::ROTR: 6942 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6943 "Unexpected custom legalisation"); 6944 Results.push_back(customLegalizeToWOp(N, DAG)); 6945 break; 6946 case ISD::CTTZ: 6947 case ISD::CTTZ_ZERO_UNDEF: 6948 case ISD::CTLZ: 6949 case ISD::CTLZ_ZERO_UNDEF: { 6950 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6951 "Unexpected custom legalisation"); 6952 6953 SDValue NewOp0 = 6954 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6955 bool IsCTZ = 6956 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6957 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6958 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6959 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6960 return; 6961 } 6962 case ISD::SDIV: 6963 case ISD::UDIV: 6964 case ISD::UREM: { 6965 MVT VT = N->getSimpleValueType(0); 6966 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6967 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6968 "Unexpected custom legalisation"); 6969 // Don't promote division/remainder by constant since we should expand those 6970 // to multiply by magic constant. 6971 // FIXME: What if the expansion is disabled for minsize. 6972 if (N->getOperand(1).getOpcode() == ISD::Constant) 6973 return; 6974 6975 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6976 // the upper 32 bits. For other types we need to sign or zero extend 6977 // based on the opcode. 6978 unsigned ExtOpc = ISD::ANY_EXTEND; 6979 if (VT != MVT::i32) 6980 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6981 : ISD::ZERO_EXTEND; 6982 6983 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6984 break; 6985 } 6986 case ISD::UADDO: 6987 case ISD::USUBO: { 6988 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6989 "Unexpected custom legalisation"); 6990 bool IsAdd = N->getOpcode() == ISD::UADDO; 6991 // Create an ADDW or SUBW. 6992 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6993 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6994 SDValue Res = 6995 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6996 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6997 DAG.getValueType(MVT::i32)); 6998 6999 SDValue Overflow; 7000 if (IsAdd && isOneConstant(RHS)) { 7001 // Special case uaddo X, 1 overflowed if the addition result is 0. 7002 // The general case (X + C) < C is not necessarily beneficial. Although we 7003 // reduce the live range of X, we may introduce the materialization of 7004 // constant C, especially when the setcc result is used by branch. We have 7005 // no compare with constant and branch instructions. 7006 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 7007 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 7008 } else { 7009 // Sign extend the LHS and perform an unsigned compare with the ADDW 7010 // result. Since the inputs are sign extended from i32, this is equivalent 7011 // to comparing the lower 32 bits. 7012 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7013 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 7014 IsAdd ? ISD::SETULT : ISD::SETUGT); 7015 } 7016 7017 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7018 Results.push_back(Overflow); 7019 return; 7020 } 7021 case ISD::UADDSAT: 7022 case ISD::USUBSAT: { 7023 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7024 "Unexpected custom legalisation"); 7025 if (Subtarget.hasStdExtZbb()) { 7026 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7027 // sign extend allows overflow of the lower 32 bits to be detected on 7028 // the promoted size. 7029 SDValue LHS = 7030 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7031 SDValue RHS = 7032 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7033 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7034 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7035 return; 7036 } 7037 7038 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7039 // promotion for UADDO/USUBO. 7040 Results.push_back(expandAddSubSat(N, DAG)); 7041 return; 7042 } 7043 case ISD::ABS: { 7044 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7045 "Unexpected custom legalisation"); 7046 7047 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7048 7049 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7050 7051 // Freeze the source so we can increase it's use count. 7052 Src = DAG.getFreeze(Src); 7053 7054 // Copy sign bit to all bits using the sraiw pattern. 7055 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7056 DAG.getValueType(MVT::i32)); 7057 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7058 DAG.getConstant(31, DL, MVT::i64)); 7059 7060 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7061 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7062 7063 // NOTE: The result is only required to be anyextended, but sext is 7064 // consistent with type legalization of sub. 7065 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7066 DAG.getValueType(MVT::i32)); 7067 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7068 return; 7069 } 7070 case ISD::BITCAST: { 7071 EVT VT = N->getValueType(0); 7072 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7073 SDValue Op0 = N->getOperand(0); 7074 EVT Op0VT = Op0.getValueType(); 7075 MVT XLenVT = Subtarget.getXLenVT(); 7076 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7077 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7078 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7079 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7080 Subtarget.hasStdExtF()) { 7081 SDValue FPConv = 7082 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7083 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7084 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7085 isTypeLegal(Op0VT)) { 7086 // Custom-legalize bitcasts from fixed-length vector types to illegal 7087 // scalar types in order to improve codegen. Bitcast the vector to a 7088 // one-element vector type whose element type is the same as the result 7089 // type, and extract the first element. 7090 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7091 if (isTypeLegal(BVT)) { 7092 SDValue BVec = DAG.getBitcast(BVT, Op0); 7093 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7094 DAG.getConstant(0, DL, XLenVT))); 7095 } 7096 } 7097 break; 7098 } 7099 case RISCVISD::GREV: 7100 case RISCVISD::GORC: 7101 case RISCVISD::SHFL: { 7102 MVT VT = N->getSimpleValueType(0); 7103 MVT XLenVT = Subtarget.getXLenVT(); 7104 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7105 "Unexpected custom legalisation"); 7106 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7107 assert((Subtarget.hasStdExtZbp() || 7108 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7109 N->getConstantOperandVal(1) == 7)) && 7110 "Unexpected extension"); 7111 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7112 SDValue NewOp1 = 7113 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7114 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7115 // ReplaceNodeResults requires we maintain the same type for the return 7116 // value. 7117 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7118 break; 7119 } 7120 case ISD::BSWAP: 7121 case ISD::BITREVERSE: { 7122 MVT VT = N->getSimpleValueType(0); 7123 MVT XLenVT = Subtarget.getXLenVT(); 7124 assert((VT == MVT::i8 || VT == MVT::i16 || 7125 (VT == MVT::i32 && Subtarget.is64Bit())) && 7126 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7127 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7128 unsigned Imm = VT.getSizeInBits() - 1; 7129 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7130 if (N->getOpcode() == ISD::BSWAP) 7131 Imm &= ~0x7U; 7132 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7133 DAG.getConstant(Imm, DL, XLenVT)); 7134 // ReplaceNodeResults requires we maintain the same type for the return 7135 // value. 7136 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7137 break; 7138 } 7139 case ISD::FSHL: 7140 case ISD::FSHR: { 7141 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7142 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7143 SDValue NewOp0 = 7144 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7145 SDValue NewOp1 = 7146 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7147 SDValue NewShAmt = 7148 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7149 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7150 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7151 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7152 DAG.getConstant(0x1f, DL, MVT::i64)); 7153 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7154 // instruction use different orders. fshl will return its first operand for 7155 // shift of zero, fshr will return its second operand. fsl and fsr both 7156 // return rs1 so the ISD nodes need to have different operand orders. 7157 // Shift amount is in rs2. 7158 unsigned Opc = RISCVISD::FSLW; 7159 if (N->getOpcode() == ISD::FSHR) { 7160 std::swap(NewOp0, NewOp1); 7161 Opc = RISCVISD::FSRW; 7162 } 7163 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7164 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7165 break; 7166 } 7167 case ISD::EXTRACT_VECTOR_ELT: { 7168 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7169 // type is illegal (currently only vXi64 RV32). 7170 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7171 // transferred to the destination register. We issue two of these from the 7172 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7173 // first element. 7174 SDValue Vec = N->getOperand(0); 7175 SDValue Idx = N->getOperand(1); 7176 7177 // The vector type hasn't been legalized yet so we can't issue target 7178 // specific nodes if it needs legalization. 7179 // FIXME: We would manually legalize if it's important. 7180 if (!isTypeLegal(Vec.getValueType())) 7181 return; 7182 7183 MVT VecVT = Vec.getSimpleValueType(); 7184 7185 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7186 VecVT.getVectorElementType() == MVT::i64 && 7187 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7188 7189 // If this is a fixed vector, we need to convert it to a scalable vector. 7190 MVT ContainerVT = VecVT; 7191 if (VecVT.isFixedLengthVector()) { 7192 ContainerVT = getContainerForFixedLengthVector(VecVT); 7193 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7194 } 7195 7196 MVT XLenVT = Subtarget.getXLenVT(); 7197 7198 // Use a VL of 1 to avoid processing more elements than we need. 7199 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7200 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7201 7202 // Unless the index is known to be 0, we must slide the vector down to get 7203 // the desired element into index 0. 7204 if (!isNullConstant(Idx)) { 7205 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7206 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7207 } 7208 7209 // Extract the lower XLEN bits of the correct vector element. 7210 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7211 7212 // To extract the upper XLEN bits of the vector element, shift the first 7213 // element right by 32 bits and re-extract the lower XLEN bits. 7214 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7215 DAG.getUNDEF(ContainerVT), 7216 DAG.getConstant(32, DL, XLenVT), VL); 7217 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7218 ThirtyTwoV, Mask, VL); 7219 7220 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7221 7222 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7223 break; 7224 } 7225 case ISD::INTRINSIC_WO_CHAIN: { 7226 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7227 switch (IntNo) { 7228 default: 7229 llvm_unreachable( 7230 "Don't know how to custom type legalize this intrinsic!"); 7231 case Intrinsic::riscv_grev: 7232 case Intrinsic::riscv_gorc: { 7233 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7234 "Unexpected custom legalisation"); 7235 SDValue NewOp1 = 7236 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7237 SDValue NewOp2 = 7238 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7239 unsigned Opc = 7240 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7241 // If the control is a constant, promote the node by clearing any extra 7242 // bits bits in the control. isel will form greviw/gorciw if the result is 7243 // sign extended. 7244 if (isa<ConstantSDNode>(NewOp2)) { 7245 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7246 DAG.getConstant(0x1f, DL, MVT::i64)); 7247 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7248 } 7249 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7250 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7251 break; 7252 } 7253 case Intrinsic::riscv_bcompress: 7254 case Intrinsic::riscv_bdecompress: 7255 case Intrinsic::riscv_bfp: 7256 case Intrinsic::riscv_fsl: 7257 case Intrinsic::riscv_fsr: { 7258 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7259 "Unexpected custom legalisation"); 7260 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7261 break; 7262 } 7263 case Intrinsic::riscv_orc_b: { 7264 // Lower to the GORCI encoding for orc.b with the operand extended. 7265 SDValue NewOp = 7266 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7267 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7268 DAG.getConstant(7, DL, MVT::i64)); 7269 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7270 return; 7271 } 7272 case Intrinsic::riscv_shfl: 7273 case Intrinsic::riscv_unshfl: { 7274 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7275 "Unexpected custom legalisation"); 7276 SDValue NewOp1 = 7277 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7278 SDValue NewOp2 = 7279 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7280 unsigned Opc = 7281 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7282 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7283 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7284 // will be shuffled the same way as the lower 32 bit half, but the two 7285 // halves won't cross. 7286 if (isa<ConstantSDNode>(NewOp2)) { 7287 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7288 DAG.getConstant(0xf, DL, MVT::i64)); 7289 Opc = 7290 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7291 } 7292 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7293 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7294 break; 7295 } 7296 case Intrinsic::riscv_vmv_x_s: { 7297 EVT VT = N->getValueType(0); 7298 MVT XLenVT = Subtarget.getXLenVT(); 7299 if (VT.bitsLT(XLenVT)) { 7300 // Simple case just extract using vmv.x.s and truncate. 7301 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7302 Subtarget.getXLenVT(), N->getOperand(1)); 7303 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7304 return; 7305 } 7306 7307 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7308 "Unexpected custom legalization"); 7309 7310 // We need to do the move in two steps. 7311 SDValue Vec = N->getOperand(1); 7312 MVT VecVT = Vec.getSimpleValueType(); 7313 7314 // First extract the lower XLEN bits of the element. 7315 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7316 7317 // To extract the upper XLEN bits of the vector element, shift the first 7318 // element right by 32 bits and re-extract the lower XLEN bits. 7319 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7320 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7321 7322 SDValue ThirtyTwoV = 7323 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7324 DAG.getConstant(32, DL, XLenVT), VL); 7325 SDValue LShr32 = 7326 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7327 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7328 7329 Results.push_back( 7330 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7331 break; 7332 } 7333 } 7334 break; 7335 } 7336 case ISD::VECREDUCE_ADD: 7337 case ISD::VECREDUCE_AND: 7338 case ISD::VECREDUCE_OR: 7339 case ISD::VECREDUCE_XOR: 7340 case ISD::VECREDUCE_SMAX: 7341 case ISD::VECREDUCE_UMAX: 7342 case ISD::VECREDUCE_SMIN: 7343 case ISD::VECREDUCE_UMIN: 7344 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7345 Results.push_back(V); 7346 break; 7347 case ISD::VP_REDUCE_ADD: 7348 case ISD::VP_REDUCE_AND: 7349 case ISD::VP_REDUCE_OR: 7350 case ISD::VP_REDUCE_XOR: 7351 case ISD::VP_REDUCE_SMAX: 7352 case ISD::VP_REDUCE_UMAX: 7353 case ISD::VP_REDUCE_SMIN: 7354 case ISD::VP_REDUCE_UMIN: 7355 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7356 Results.push_back(V); 7357 break; 7358 case ISD::FLT_ROUNDS_: { 7359 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7360 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7361 Results.push_back(Res.getValue(0)); 7362 Results.push_back(Res.getValue(1)); 7363 break; 7364 } 7365 } 7366 } 7367 7368 // A structure to hold one of the bit-manipulation patterns below. Together, a 7369 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7370 // (or (and (shl x, 1), 0xAAAAAAAA), 7371 // (and (srl x, 1), 0x55555555)) 7372 struct RISCVBitmanipPat { 7373 SDValue Op; 7374 unsigned ShAmt; 7375 bool IsSHL; 7376 7377 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7378 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7379 } 7380 }; 7381 7382 // Matches patterns of the form 7383 // (and (shl x, C2), (C1 << C2)) 7384 // (and (srl x, C2), C1) 7385 // (shl (and x, C1), C2) 7386 // (srl (and x, (C1 << C2)), C2) 7387 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7388 // The expected masks for each shift amount are specified in BitmanipMasks where 7389 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7390 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7391 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7392 // XLen is 64. 7393 static Optional<RISCVBitmanipPat> 7394 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7395 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7396 "Unexpected number of masks"); 7397 Optional<uint64_t> Mask; 7398 // Optionally consume a mask around the shift operation. 7399 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7400 Mask = Op.getConstantOperandVal(1); 7401 Op = Op.getOperand(0); 7402 } 7403 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7404 return None; 7405 bool IsSHL = Op.getOpcode() == ISD::SHL; 7406 7407 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7408 return None; 7409 uint64_t ShAmt = Op.getConstantOperandVal(1); 7410 7411 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7412 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7413 return None; 7414 // If we don't have enough masks for 64 bit, then we must be trying to 7415 // match SHFL so we're only allowed to shift 1/4 of the width. 7416 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7417 return None; 7418 7419 SDValue Src = Op.getOperand(0); 7420 7421 // The expected mask is shifted left when the AND is found around SHL 7422 // patterns. 7423 // ((x >> 1) & 0x55555555) 7424 // ((x << 1) & 0xAAAAAAAA) 7425 bool SHLExpMask = IsSHL; 7426 7427 if (!Mask) { 7428 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7429 // the mask is all ones: consume that now. 7430 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7431 Mask = Src.getConstantOperandVal(1); 7432 Src = Src.getOperand(0); 7433 // The expected mask is now in fact shifted left for SRL, so reverse the 7434 // decision. 7435 // ((x & 0xAAAAAAAA) >> 1) 7436 // ((x & 0x55555555) << 1) 7437 SHLExpMask = !SHLExpMask; 7438 } else { 7439 // Use a default shifted mask of all-ones if there's no AND, truncated 7440 // down to the expected width. This simplifies the logic later on. 7441 Mask = maskTrailingOnes<uint64_t>(Width); 7442 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7443 } 7444 } 7445 7446 unsigned MaskIdx = Log2_32(ShAmt); 7447 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7448 7449 if (SHLExpMask) 7450 ExpMask <<= ShAmt; 7451 7452 if (Mask != ExpMask) 7453 return None; 7454 7455 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7456 } 7457 7458 // Matches any of the following bit-manipulation patterns: 7459 // (and (shl x, 1), (0x55555555 << 1)) 7460 // (and (srl x, 1), 0x55555555) 7461 // (shl (and x, 0x55555555), 1) 7462 // (srl (and x, (0x55555555 << 1)), 1) 7463 // where the shift amount and mask may vary thus: 7464 // [1] = 0x55555555 / 0xAAAAAAAA 7465 // [2] = 0x33333333 / 0xCCCCCCCC 7466 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7467 // [8] = 0x00FF00FF / 0xFF00FF00 7468 // [16] = 0x0000FFFF / 0xFFFFFFFF 7469 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7470 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7471 // These are the unshifted masks which we use to match bit-manipulation 7472 // patterns. They may be shifted left in certain circumstances. 7473 static const uint64_t BitmanipMasks[] = { 7474 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7475 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7476 7477 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7478 } 7479 7480 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7481 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7482 auto BinOpToRVVReduce = [](unsigned Opc) { 7483 switch (Opc) { 7484 default: 7485 llvm_unreachable("Unhandled binary to transfrom reduction"); 7486 case ISD::ADD: 7487 return RISCVISD::VECREDUCE_ADD_VL; 7488 case ISD::UMAX: 7489 return RISCVISD::VECREDUCE_UMAX_VL; 7490 case ISD::SMAX: 7491 return RISCVISD::VECREDUCE_SMAX_VL; 7492 case ISD::UMIN: 7493 return RISCVISD::VECREDUCE_UMIN_VL; 7494 case ISD::SMIN: 7495 return RISCVISD::VECREDUCE_SMIN_VL; 7496 case ISD::AND: 7497 return RISCVISD::VECREDUCE_AND_VL; 7498 case ISD::OR: 7499 return RISCVISD::VECREDUCE_OR_VL; 7500 case ISD::XOR: 7501 return RISCVISD::VECREDUCE_XOR_VL; 7502 case ISD::FADD: 7503 return RISCVISD::VECREDUCE_FADD_VL; 7504 case ISD::FMAXNUM: 7505 return RISCVISD::VECREDUCE_FMAX_VL; 7506 case ISD::FMINNUM: 7507 return RISCVISD::VECREDUCE_FMIN_VL; 7508 } 7509 }; 7510 7511 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7512 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7513 isNullConstant(V.getOperand(1)) && 7514 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7515 }; 7516 7517 unsigned Opc = N->getOpcode(); 7518 unsigned ReduceIdx; 7519 if (IsReduction(N->getOperand(0), Opc)) 7520 ReduceIdx = 0; 7521 else if (IsReduction(N->getOperand(1), Opc)) 7522 ReduceIdx = 1; 7523 else 7524 return SDValue(); 7525 7526 // Skip if FADD disallows reassociation but the combiner needs. 7527 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7528 return SDValue(); 7529 7530 SDValue Extract = N->getOperand(ReduceIdx); 7531 SDValue Reduce = Extract.getOperand(0); 7532 if (!Reduce.hasOneUse()) 7533 return SDValue(); 7534 7535 SDValue ScalarV = Reduce.getOperand(2); 7536 7537 // Make sure that ScalarV is a splat with VL=1. 7538 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7539 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7540 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7541 return SDValue(); 7542 7543 if (!isOneConstant(ScalarV.getOperand(2))) 7544 return SDValue(); 7545 7546 // TODO: Deal with value other than neutral element. 7547 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7548 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7549 isNullFPConstant(V)) 7550 return true; 7551 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7552 N->getFlags()) == V; 7553 }; 7554 7555 // Check the scalar of ScalarV is neutral element 7556 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7557 return SDValue(); 7558 7559 if (!ScalarV.hasOneUse()) 7560 return SDValue(); 7561 7562 EVT SplatVT = ScalarV.getValueType(); 7563 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7564 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7565 if (SplatVT.isInteger()) { 7566 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7567 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7568 SplatOpc = RISCVISD::VMV_S_X_VL; 7569 else 7570 SplatOpc = RISCVISD::VMV_V_X_VL; 7571 } 7572 7573 SDValue NewScalarV = 7574 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7575 ScalarV.getOperand(2)); 7576 SDValue NewReduce = 7577 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7578 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7579 Reduce.getOperand(3), Reduce.getOperand(4)); 7580 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7581 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7582 } 7583 7584 // Match the following pattern as a GREVI(W) operation 7585 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7586 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7587 const RISCVSubtarget &Subtarget) { 7588 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7589 EVT VT = Op.getValueType(); 7590 7591 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7592 auto LHS = matchGREVIPat(Op.getOperand(0)); 7593 auto RHS = matchGREVIPat(Op.getOperand(1)); 7594 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7595 SDLoc DL(Op); 7596 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7597 DAG.getConstant(LHS->ShAmt, DL, VT)); 7598 } 7599 } 7600 return SDValue(); 7601 } 7602 7603 // Matches any the following pattern as a GORCI(W) operation 7604 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7605 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7606 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7607 // Note that with the variant of 3., 7608 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7609 // the inner pattern will first be matched as GREVI and then the outer 7610 // pattern will be matched to GORC via the first rule above. 7611 // 4. (or (rotl/rotr x, bitwidth/2), x) 7612 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7613 const RISCVSubtarget &Subtarget) { 7614 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7615 EVT VT = Op.getValueType(); 7616 7617 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7618 SDLoc DL(Op); 7619 SDValue Op0 = Op.getOperand(0); 7620 SDValue Op1 = Op.getOperand(1); 7621 7622 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7623 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7624 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7625 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7626 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7627 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7628 if ((Reverse.getOpcode() == ISD::ROTL || 7629 Reverse.getOpcode() == ISD::ROTR) && 7630 Reverse.getOperand(0) == X && 7631 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7632 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7633 if (RotAmt == (VT.getSizeInBits() / 2)) 7634 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7635 DAG.getConstant(RotAmt, DL, VT)); 7636 } 7637 return SDValue(); 7638 }; 7639 7640 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7641 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7642 return V; 7643 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7644 return V; 7645 7646 // OR is commutable so canonicalize its OR operand to the left 7647 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7648 std::swap(Op0, Op1); 7649 if (Op0.getOpcode() != ISD::OR) 7650 return SDValue(); 7651 SDValue OrOp0 = Op0.getOperand(0); 7652 SDValue OrOp1 = Op0.getOperand(1); 7653 auto LHS = matchGREVIPat(OrOp0); 7654 // OR is commutable so swap the operands and try again: x might have been 7655 // on the left 7656 if (!LHS) { 7657 std::swap(OrOp0, OrOp1); 7658 LHS = matchGREVIPat(OrOp0); 7659 } 7660 auto RHS = matchGREVIPat(Op1); 7661 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7662 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7663 DAG.getConstant(LHS->ShAmt, DL, VT)); 7664 } 7665 } 7666 return SDValue(); 7667 } 7668 7669 // Matches any of the following bit-manipulation patterns: 7670 // (and (shl x, 1), (0x22222222 << 1)) 7671 // (and (srl x, 1), 0x22222222) 7672 // (shl (and x, 0x22222222), 1) 7673 // (srl (and x, (0x22222222 << 1)), 1) 7674 // where the shift amount and mask may vary thus: 7675 // [1] = 0x22222222 / 0x44444444 7676 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7677 // [4] = 0x00F000F0 / 0x0F000F00 7678 // [8] = 0x0000FF00 / 0x00FF0000 7679 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7680 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7681 // These are the unshifted masks which we use to match bit-manipulation 7682 // patterns. They may be shifted left in certain circumstances. 7683 static const uint64_t BitmanipMasks[] = { 7684 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7685 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7686 7687 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7688 } 7689 7690 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7691 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7692 const RISCVSubtarget &Subtarget) { 7693 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7694 EVT VT = Op.getValueType(); 7695 7696 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7697 return SDValue(); 7698 7699 SDValue Op0 = Op.getOperand(0); 7700 SDValue Op1 = Op.getOperand(1); 7701 7702 // Or is commutable so canonicalize the second OR to the LHS. 7703 if (Op0.getOpcode() != ISD::OR) 7704 std::swap(Op0, Op1); 7705 if (Op0.getOpcode() != ISD::OR) 7706 return SDValue(); 7707 7708 // We found an inner OR, so our operands are the operands of the inner OR 7709 // and the other operand of the outer OR. 7710 SDValue A = Op0.getOperand(0); 7711 SDValue B = Op0.getOperand(1); 7712 SDValue C = Op1; 7713 7714 auto Match1 = matchSHFLPat(A); 7715 auto Match2 = matchSHFLPat(B); 7716 7717 // If neither matched, we failed. 7718 if (!Match1 && !Match2) 7719 return SDValue(); 7720 7721 // We had at least one match. if one failed, try the remaining C operand. 7722 if (!Match1) { 7723 std::swap(A, C); 7724 Match1 = matchSHFLPat(A); 7725 if (!Match1) 7726 return SDValue(); 7727 } else if (!Match2) { 7728 std::swap(B, C); 7729 Match2 = matchSHFLPat(B); 7730 if (!Match2) 7731 return SDValue(); 7732 } 7733 assert(Match1 && Match2); 7734 7735 // Make sure our matches pair up. 7736 if (!Match1->formsPairWith(*Match2)) 7737 return SDValue(); 7738 7739 // All the remains is to make sure C is an AND with the same input, that masks 7740 // out the bits that are being shuffled. 7741 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7742 C.getOperand(0) != Match1->Op) 7743 return SDValue(); 7744 7745 uint64_t Mask = C.getConstantOperandVal(1); 7746 7747 static const uint64_t BitmanipMasks[] = { 7748 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7749 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7750 }; 7751 7752 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7753 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7754 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7755 7756 if (Mask != ExpMask) 7757 return SDValue(); 7758 7759 SDLoc DL(Op); 7760 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7761 DAG.getConstant(Match1->ShAmt, DL, VT)); 7762 } 7763 7764 // Optimize (add (shl x, c0), (shl y, c1)) -> 7765 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7766 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7767 const RISCVSubtarget &Subtarget) { 7768 // Perform this optimization only in the zba extension. 7769 if (!Subtarget.hasStdExtZba()) 7770 return SDValue(); 7771 7772 // Skip for vector types and larger types. 7773 EVT VT = N->getValueType(0); 7774 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7775 return SDValue(); 7776 7777 // The two operand nodes must be SHL and have no other use. 7778 SDValue N0 = N->getOperand(0); 7779 SDValue N1 = N->getOperand(1); 7780 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7781 !N0->hasOneUse() || !N1->hasOneUse()) 7782 return SDValue(); 7783 7784 // Check c0 and c1. 7785 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7786 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7787 if (!N0C || !N1C) 7788 return SDValue(); 7789 int64_t C0 = N0C->getSExtValue(); 7790 int64_t C1 = N1C->getSExtValue(); 7791 if (C0 <= 0 || C1 <= 0) 7792 return SDValue(); 7793 7794 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7795 int64_t Bits = std::min(C0, C1); 7796 int64_t Diff = std::abs(C0 - C1); 7797 if (Diff != 1 && Diff != 2 && Diff != 3) 7798 return SDValue(); 7799 7800 // Build nodes. 7801 SDLoc DL(N); 7802 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7803 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7804 SDValue NA0 = 7805 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7806 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7807 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7808 } 7809 7810 // Combine 7811 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7812 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7813 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7814 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7815 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7816 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7817 // The grev patterns represents BSWAP. 7818 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7819 // off the grev. 7820 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7821 const RISCVSubtarget &Subtarget) { 7822 bool IsWInstruction = 7823 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7824 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7825 IsWInstruction) && 7826 "Unexpected opcode!"); 7827 SDValue Src = N->getOperand(0); 7828 EVT VT = N->getValueType(0); 7829 SDLoc DL(N); 7830 7831 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7832 return SDValue(); 7833 7834 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7835 !isa<ConstantSDNode>(Src.getOperand(1))) 7836 return SDValue(); 7837 7838 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7839 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7840 7841 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7842 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7843 unsigned ShAmt1 = N->getConstantOperandVal(1); 7844 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7845 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7846 return SDValue(); 7847 7848 Src = Src.getOperand(0); 7849 7850 // Toggle bit the MSB of the shift. 7851 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7852 if (CombinedShAmt == 0) 7853 return Src; 7854 7855 SDValue Res = DAG.getNode( 7856 RISCVISD::GREV, DL, VT, Src, 7857 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7858 if (!IsWInstruction) 7859 return Res; 7860 7861 // Sign extend the result to match the behavior of the rotate. This will be 7862 // selected to GREVIW in isel. 7863 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7864 DAG.getValueType(MVT::i32)); 7865 } 7866 7867 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7868 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7869 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7870 // not undo itself, but they are redundant. 7871 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7872 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7873 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7874 SDValue Src = N->getOperand(0); 7875 7876 if (Src.getOpcode() != N->getOpcode()) 7877 return SDValue(); 7878 7879 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7880 !isa<ConstantSDNode>(Src.getOperand(1))) 7881 return SDValue(); 7882 7883 unsigned ShAmt1 = N->getConstantOperandVal(1); 7884 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7885 Src = Src.getOperand(0); 7886 7887 unsigned CombinedShAmt; 7888 if (IsGORC) 7889 CombinedShAmt = ShAmt1 | ShAmt2; 7890 else 7891 CombinedShAmt = ShAmt1 ^ ShAmt2; 7892 7893 if (CombinedShAmt == 0) 7894 return Src; 7895 7896 SDLoc DL(N); 7897 return DAG.getNode( 7898 N->getOpcode(), DL, N->getValueType(0), Src, 7899 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7900 } 7901 7902 // Combine a constant select operand into its use: 7903 // 7904 // (and (select cond, -1, c), x) 7905 // -> (select cond, x, (and x, c)) [AllOnes=1] 7906 // (or (select cond, 0, c), x) 7907 // -> (select cond, x, (or x, c)) [AllOnes=0] 7908 // (xor (select cond, 0, c), x) 7909 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7910 // (add (select cond, 0, c), x) 7911 // -> (select cond, x, (add x, c)) [AllOnes=0] 7912 // (sub x, (select cond, 0, c)) 7913 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7914 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7915 SelectionDAG &DAG, bool AllOnes) { 7916 EVT VT = N->getValueType(0); 7917 7918 // Skip vectors. 7919 if (VT.isVector()) 7920 return SDValue(); 7921 7922 if ((Slct.getOpcode() != ISD::SELECT && 7923 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7924 !Slct.hasOneUse()) 7925 return SDValue(); 7926 7927 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7928 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7929 }; 7930 7931 bool SwapSelectOps; 7932 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7933 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7934 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7935 SDValue NonConstantVal; 7936 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7937 SwapSelectOps = false; 7938 NonConstantVal = FalseVal; 7939 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7940 SwapSelectOps = true; 7941 NonConstantVal = TrueVal; 7942 } else 7943 return SDValue(); 7944 7945 // Slct is now know to be the desired identity constant when CC is true. 7946 TrueVal = OtherOp; 7947 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7948 // Unless SwapSelectOps says the condition should be false. 7949 if (SwapSelectOps) 7950 std::swap(TrueVal, FalseVal); 7951 7952 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7953 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7954 {Slct.getOperand(0), Slct.getOperand(1), 7955 Slct.getOperand(2), TrueVal, FalseVal}); 7956 7957 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7958 {Slct.getOperand(0), TrueVal, FalseVal}); 7959 } 7960 7961 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7962 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7963 bool AllOnes) { 7964 SDValue N0 = N->getOperand(0); 7965 SDValue N1 = N->getOperand(1); 7966 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7967 return Result; 7968 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7969 return Result; 7970 return SDValue(); 7971 } 7972 7973 // Transform (add (mul x, c0), c1) -> 7974 // (add (mul (add x, c1/c0), c0), c1%c0). 7975 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7976 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7977 // to an infinite loop in DAGCombine if transformed. 7978 // Or transform (add (mul x, c0), c1) -> 7979 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7980 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7981 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7982 // lead to an infinite loop in DAGCombine if transformed. 7983 // Or transform (add (mul x, c0), c1) -> 7984 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7985 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7986 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7987 // lead to an infinite loop in DAGCombine if transformed. 7988 // Or transform (add (mul x, c0), c1) -> 7989 // (mul (add x, c1/c0), c0). 7990 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7991 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7992 const RISCVSubtarget &Subtarget) { 7993 // Skip for vector types and larger types. 7994 EVT VT = N->getValueType(0); 7995 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7996 return SDValue(); 7997 // The first operand node must be a MUL and has no other use. 7998 SDValue N0 = N->getOperand(0); 7999 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 8000 return SDValue(); 8001 // Check if c0 and c1 match above conditions. 8002 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8003 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8004 if (!N0C || !N1C) 8005 return SDValue(); 8006 // If N0C has multiple uses it's possible one of the cases in 8007 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 8008 // in an infinite loop. 8009 if (!N0C->hasOneUse()) 8010 return SDValue(); 8011 int64_t C0 = N0C->getSExtValue(); 8012 int64_t C1 = N1C->getSExtValue(); 8013 int64_t CA, CB; 8014 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 8015 return SDValue(); 8016 // Search for proper CA (non-zero) and CB that both are simm12. 8017 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 8018 !isInt<12>(C0 * (C1 / C0))) { 8019 CA = C1 / C0; 8020 CB = C1 % C0; 8021 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 8022 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 8023 CA = C1 / C0 + 1; 8024 CB = C1 % C0 - C0; 8025 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 8026 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8027 CA = C1 / C0 - 1; 8028 CB = C1 % C0 + C0; 8029 } else 8030 return SDValue(); 8031 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8032 SDLoc DL(N); 8033 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8034 DAG.getConstant(CA, DL, VT)); 8035 SDValue New1 = 8036 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8037 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8038 } 8039 8040 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8041 const RISCVSubtarget &Subtarget) { 8042 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8043 return V; 8044 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8045 return V; 8046 if (SDValue V = combineBinOpToReduce(N, DAG)) 8047 return V; 8048 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8049 // (select lhs, rhs, cc, x, (add x, y)) 8050 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8051 } 8052 8053 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8054 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8055 // (select lhs, rhs, cc, x, (sub x, y)) 8056 SDValue N0 = N->getOperand(0); 8057 SDValue N1 = N->getOperand(1); 8058 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8059 } 8060 8061 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8062 const RISCVSubtarget &Subtarget) { 8063 SDValue N0 = N->getOperand(0); 8064 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8065 // extending X. This is safe since we only need the LSB after the shift and 8066 // shift amounts larger than 31 would produce poison. If we wait until 8067 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8068 // to use a BEXT instruction. 8069 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8070 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8071 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8072 N0.hasOneUse()) { 8073 SDLoc DL(N); 8074 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8075 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8076 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8077 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8078 DAG.getConstant(1, DL, MVT::i64)); 8079 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8080 } 8081 8082 if (SDValue V = combineBinOpToReduce(N, DAG)) 8083 return V; 8084 8085 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8086 // (select lhs, rhs, cc, x, (and x, y)) 8087 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8088 } 8089 8090 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8091 const RISCVSubtarget &Subtarget) { 8092 if (Subtarget.hasStdExtZbp()) { 8093 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8094 return GREV; 8095 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8096 return GORC; 8097 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8098 return SHFL; 8099 } 8100 8101 if (SDValue V = combineBinOpToReduce(N, DAG)) 8102 return V; 8103 // fold (or (select cond, 0, y), x) -> 8104 // (select cond, x, (or x, y)) 8105 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8106 } 8107 8108 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8109 SDValue N0 = N->getOperand(0); 8110 SDValue N1 = N->getOperand(1); 8111 8112 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8113 // NOTE: Assumes ROL being legal means ROLW is legal. 8114 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8115 if (N0.getOpcode() == RISCVISD::SLLW && 8116 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8117 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8118 SDLoc DL(N); 8119 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8120 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8121 } 8122 8123 if (SDValue V = combineBinOpToReduce(N, DAG)) 8124 return V; 8125 // fold (xor (select cond, 0, y), x) -> 8126 // (select cond, x, (xor x, y)) 8127 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8128 } 8129 8130 static SDValue 8131 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8132 const RISCVSubtarget &Subtarget) { 8133 SDValue Src = N->getOperand(0); 8134 EVT VT = N->getValueType(0); 8135 8136 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8137 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8138 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8139 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8140 Src.getOperand(0)); 8141 8142 // Fold (i64 (sext_inreg (abs X), i32)) -> 8143 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8144 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8145 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8146 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8147 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8148 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8149 // may get combined into an earlier operation so we need to use 8150 // ComputeNumSignBits. 8151 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8152 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8153 // we can't assume that X has 33 sign bits. We must check. 8154 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8155 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8156 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8157 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8158 SDLoc DL(N); 8159 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8160 SDValue Neg = 8161 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8162 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8163 DAG.getValueType(MVT::i32)); 8164 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8165 } 8166 8167 return SDValue(); 8168 } 8169 8170 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8171 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8172 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8173 bool Commute = false) { 8174 assert((N->getOpcode() == RISCVISD::ADD_VL || 8175 N->getOpcode() == RISCVISD::SUB_VL) && 8176 "Unexpected opcode"); 8177 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8178 SDValue Op0 = N->getOperand(0); 8179 SDValue Op1 = N->getOperand(1); 8180 if (Commute) 8181 std::swap(Op0, Op1); 8182 8183 MVT VT = N->getSimpleValueType(0); 8184 8185 // Determine the narrow size for a widening add/sub. 8186 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8187 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8188 VT.getVectorElementCount()); 8189 8190 SDValue Mask = N->getOperand(2); 8191 SDValue VL = N->getOperand(3); 8192 8193 SDLoc DL(N); 8194 8195 // If the RHS is a sext or zext, we can form a widening op. 8196 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8197 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8198 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8199 unsigned ExtOpc = Op1.getOpcode(); 8200 Op1 = Op1.getOperand(0); 8201 // Re-introduce narrower extends if needed. 8202 if (Op1.getValueType() != NarrowVT) 8203 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8204 8205 unsigned WOpc; 8206 if (ExtOpc == RISCVISD::VSEXT_VL) 8207 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8208 else 8209 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8210 8211 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8212 } 8213 8214 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8215 // sext/zext? 8216 8217 return SDValue(); 8218 } 8219 8220 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8221 // vwsub(u).vv/vx. 8222 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8223 SDValue Op0 = N->getOperand(0); 8224 SDValue Op1 = N->getOperand(1); 8225 SDValue Mask = N->getOperand(2); 8226 SDValue VL = N->getOperand(3); 8227 8228 MVT VT = N->getSimpleValueType(0); 8229 MVT NarrowVT = Op1.getSimpleValueType(); 8230 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8231 8232 unsigned VOpc; 8233 switch (N->getOpcode()) { 8234 default: llvm_unreachable("Unexpected opcode"); 8235 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8236 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8237 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8238 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8239 } 8240 8241 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8242 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8243 8244 SDLoc DL(N); 8245 8246 // If the LHS is a sext or zext, we can narrow this op to the same size as 8247 // the RHS. 8248 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8249 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8250 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8251 unsigned ExtOpc = Op0.getOpcode(); 8252 Op0 = Op0.getOperand(0); 8253 // Re-introduce narrower extends if needed. 8254 if (Op0.getValueType() != NarrowVT) 8255 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8256 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8257 } 8258 8259 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8260 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8261 8262 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8263 // to commute and use a vwadd(u).vx instead. 8264 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8265 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8266 Op0 = Op0.getOperand(1); 8267 8268 // See if have enough sign bits or zero bits in the scalar to use a 8269 // widening add/sub by splatting to smaller element size. 8270 unsigned EltBits = VT.getScalarSizeInBits(); 8271 unsigned ScalarBits = Op0.getValueSizeInBits(); 8272 // Make sure we're getting all element bits from the scalar register. 8273 // FIXME: Support implicit sign extension of vmv.v.x? 8274 if (ScalarBits < EltBits) 8275 return SDValue(); 8276 8277 if (IsSigned) { 8278 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8279 return SDValue(); 8280 } else { 8281 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8282 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8283 return SDValue(); 8284 } 8285 8286 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8287 DAG.getUNDEF(NarrowVT), Op0, VL); 8288 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8289 } 8290 8291 return SDValue(); 8292 } 8293 8294 // Try to form VWMUL, VWMULU or VWMULSU. 8295 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8296 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8297 bool Commute) { 8298 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8299 SDValue Op0 = N->getOperand(0); 8300 SDValue Op1 = N->getOperand(1); 8301 if (Commute) 8302 std::swap(Op0, Op1); 8303 8304 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8305 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8306 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8307 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8308 return SDValue(); 8309 8310 SDValue Mask = N->getOperand(2); 8311 SDValue VL = N->getOperand(3); 8312 8313 // Make sure the mask and VL match. 8314 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8315 return SDValue(); 8316 8317 MVT VT = N->getSimpleValueType(0); 8318 8319 // Determine the narrow size for a widening multiply. 8320 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8321 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8322 VT.getVectorElementCount()); 8323 8324 SDLoc DL(N); 8325 8326 // See if the other operand is the same opcode. 8327 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8328 if (!Op1.hasOneUse()) 8329 return SDValue(); 8330 8331 // Make sure the mask and VL match. 8332 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8333 return SDValue(); 8334 8335 Op1 = Op1.getOperand(0); 8336 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8337 // The operand is a splat of a scalar. 8338 8339 // The pasthru must be undef for tail agnostic 8340 if (!Op1.getOperand(0).isUndef()) 8341 return SDValue(); 8342 // The VL must be the same. 8343 if (Op1.getOperand(2) != VL) 8344 return SDValue(); 8345 8346 // Get the scalar value. 8347 Op1 = Op1.getOperand(1); 8348 8349 // See if have enough sign bits or zero bits in the scalar to use a 8350 // widening multiply by splatting to smaller element size. 8351 unsigned EltBits = VT.getScalarSizeInBits(); 8352 unsigned ScalarBits = Op1.getValueSizeInBits(); 8353 // Make sure we're getting all element bits from the scalar register. 8354 // FIXME: Support implicit sign extension of vmv.v.x? 8355 if (ScalarBits < EltBits) 8356 return SDValue(); 8357 8358 // If the LHS is a sign extend, try to use vwmul. 8359 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8360 // Can use vwmul. 8361 } else { 8362 // Otherwise try to use vwmulu or vwmulsu. 8363 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8364 if (DAG.MaskedValueIsZero(Op1, Mask)) 8365 IsVWMULSU = IsSignExt; 8366 else 8367 return SDValue(); 8368 } 8369 8370 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8371 DAG.getUNDEF(NarrowVT), Op1, VL); 8372 } else 8373 return SDValue(); 8374 8375 Op0 = Op0.getOperand(0); 8376 8377 // Re-introduce narrower extends if needed. 8378 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8379 if (Op0.getValueType() != NarrowVT) 8380 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8381 // vwmulsu requires second operand to be zero extended. 8382 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8383 if (Op1.getValueType() != NarrowVT) 8384 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8385 8386 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8387 if (!IsVWMULSU) 8388 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8389 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8390 } 8391 8392 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8393 switch (Op.getOpcode()) { 8394 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8395 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8396 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8397 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8398 case ISD::FROUND: return RISCVFPRndMode::RMM; 8399 } 8400 8401 return RISCVFPRndMode::Invalid; 8402 } 8403 8404 // Fold 8405 // (fp_to_int (froundeven X)) -> fcvt X, rne 8406 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8407 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8408 // (fp_to_int (fceil X)) -> fcvt X, rup 8409 // (fp_to_int (fround X)) -> fcvt X, rmm 8410 static SDValue performFP_TO_INTCombine(SDNode *N, 8411 TargetLowering::DAGCombinerInfo &DCI, 8412 const RISCVSubtarget &Subtarget) { 8413 SelectionDAG &DAG = DCI.DAG; 8414 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8415 MVT XLenVT = Subtarget.getXLenVT(); 8416 8417 // Only handle XLen or i32 types. Other types narrower than XLen will 8418 // eventually be legalized to XLenVT. 8419 EVT VT = N->getValueType(0); 8420 if (VT != MVT::i32 && VT != XLenVT) 8421 return SDValue(); 8422 8423 SDValue Src = N->getOperand(0); 8424 8425 // Ensure the FP type is also legal. 8426 if (!TLI.isTypeLegal(Src.getValueType())) 8427 return SDValue(); 8428 8429 // Don't do this for f16 with Zfhmin and not Zfh. 8430 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8431 return SDValue(); 8432 8433 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8434 if (FRM == RISCVFPRndMode::Invalid) 8435 return SDValue(); 8436 8437 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8438 8439 unsigned Opc; 8440 if (VT == XLenVT) 8441 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8442 else 8443 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8444 8445 SDLoc DL(N); 8446 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8447 DAG.getTargetConstant(FRM, DL, XLenVT)); 8448 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8449 } 8450 8451 // Fold 8452 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8453 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8454 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8455 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8456 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8457 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8458 TargetLowering::DAGCombinerInfo &DCI, 8459 const RISCVSubtarget &Subtarget) { 8460 SelectionDAG &DAG = DCI.DAG; 8461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8462 MVT XLenVT = Subtarget.getXLenVT(); 8463 8464 // Only handle XLen types. Other types narrower than XLen will eventually be 8465 // legalized to XLenVT. 8466 EVT DstVT = N->getValueType(0); 8467 if (DstVT != XLenVT) 8468 return SDValue(); 8469 8470 SDValue Src = N->getOperand(0); 8471 8472 // Ensure the FP type is also legal. 8473 if (!TLI.isTypeLegal(Src.getValueType())) 8474 return SDValue(); 8475 8476 // Don't do this for f16 with Zfhmin and not Zfh. 8477 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8478 return SDValue(); 8479 8480 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8481 8482 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8483 if (FRM == RISCVFPRndMode::Invalid) 8484 return SDValue(); 8485 8486 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8487 8488 unsigned Opc; 8489 if (SatVT == DstVT) 8490 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8491 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8492 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8493 else 8494 return SDValue(); 8495 // FIXME: Support other SatVTs by clamping before or after the conversion. 8496 8497 Src = Src.getOperand(0); 8498 8499 SDLoc DL(N); 8500 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8501 DAG.getTargetConstant(FRM, DL, XLenVT)); 8502 8503 // RISCV FP-to-int conversions saturate to the destination register size, but 8504 // don't produce 0 for nan. 8505 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8506 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8507 } 8508 8509 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8510 // smaller than XLenVT. 8511 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8512 const RISCVSubtarget &Subtarget) { 8513 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8514 8515 SDValue Src = N->getOperand(0); 8516 if (Src.getOpcode() != ISD::BSWAP) 8517 return SDValue(); 8518 8519 EVT VT = N->getValueType(0); 8520 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8521 !isPowerOf2_32(VT.getSizeInBits())) 8522 return SDValue(); 8523 8524 SDLoc DL(N); 8525 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8526 DAG.getConstant(7, DL, VT)); 8527 } 8528 8529 // Convert from one FMA opcode to another based on whether we are negating the 8530 // multiply result and/or the accumulator. 8531 // NOTE: Only supports RVV operations with VL. 8532 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8533 assert((NegMul || NegAcc) && "Not negating anything?"); 8534 8535 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8536 if (NegMul) { 8537 // clang-format off 8538 switch (Opcode) { 8539 default: llvm_unreachable("Unexpected opcode"); 8540 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8541 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8542 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8543 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8544 } 8545 // clang-format on 8546 } 8547 8548 // Negating the accumulator changes ADD<->SUB. 8549 if (NegAcc) { 8550 // clang-format off 8551 switch (Opcode) { 8552 default: llvm_unreachable("Unexpected opcode"); 8553 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8554 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8555 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8556 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8557 } 8558 // clang-format on 8559 } 8560 8561 return Opcode; 8562 } 8563 8564 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8565 const RISCVSubtarget &Subtarget) { 8566 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8567 8568 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8569 return SDValue(); 8570 8571 if (!isa<ConstantSDNode>(N->getOperand(1))) 8572 return SDValue(); 8573 uint64_t ShAmt = N->getConstantOperandVal(1); 8574 if (ShAmt > 32) 8575 return SDValue(); 8576 8577 SDValue N0 = N->getOperand(0); 8578 8579 // Combine (sra (sext_inreg (shl X, C1), i32), C2) -> 8580 // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of 8581 // SLLIW+SRAIW. SLLI+SRAI have compressed forms. 8582 if (ShAmt < 32 && 8583 N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() && 8584 cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 && 8585 N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() && 8586 isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 8587 uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1); 8588 if (LShAmt < 32) { 8589 SDLoc ShlDL(N0.getOperand(0)); 8590 SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64, 8591 N0.getOperand(0).getOperand(0), 8592 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64)); 8593 SDLoc DL(N); 8594 return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl, 8595 DAG.getConstant(ShAmt + 32, DL, MVT::i64)); 8596 } 8597 } 8598 8599 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8600 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8601 // 8602 // Also try these folds where an add or sub is in the middle. 8603 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8604 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8605 SDValue Shl; 8606 ConstantSDNode *AddC = nullptr; 8607 8608 // We might have an ADD or SUB between the SRA and SHL. 8609 bool IsAdd = N0.getOpcode() == ISD::ADD; 8610 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8611 if (!N0.hasOneUse()) 8612 return SDValue(); 8613 // Other operand needs to be a constant we can modify. 8614 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8615 if (!AddC) 8616 return SDValue(); 8617 8618 // AddC needs to have at least 32 trailing zeros. 8619 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8620 return SDValue(); 8621 8622 Shl = N0.getOperand(IsAdd ? 0 : 1); 8623 } else { 8624 // Not an ADD or SUB. 8625 Shl = N0; 8626 } 8627 8628 // Look for a shift left by 32. 8629 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8630 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8631 Shl.getConstantOperandVal(1) != 32) 8632 return SDValue(); 8633 8634 SDLoc DL(N); 8635 SDValue In = Shl.getOperand(0); 8636 8637 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8638 // constant. 8639 if (AddC) { 8640 SDValue ShiftedAddC = 8641 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8642 if (IsAdd) 8643 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8644 else 8645 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8646 } 8647 8648 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8649 DAG.getValueType(MVT::i32)); 8650 if (ShAmt == 32) 8651 return SExt; 8652 8653 return DAG.getNode( 8654 ISD::SHL, DL, MVT::i64, SExt, 8655 DAG.getConstant(32 - ShAmt, DL, MVT::i64)); 8656 } 8657 8658 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8659 DAGCombinerInfo &DCI) const { 8660 SelectionDAG &DAG = DCI.DAG; 8661 8662 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8663 // bits are demanded. N will be added to the Worklist if it was not deleted. 8664 // Caller should return SDValue(N, 0) if this returns true. 8665 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8666 SDValue Op = N->getOperand(OpNo); 8667 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8668 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8669 return false; 8670 8671 if (N->getOpcode() != ISD::DELETED_NODE) 8672 DCI.AddToWorklist(N); 8673 return true; 8674 }; 8675 8676 switch (N->getOpcode()) { 8677 default: 8678 break; 8679 case RISCVISD::SplitF64: { 8680 SDValue Op0 = N->getOperand(0); 8681 // If the input to SplitF64 is just BuildPairF64 then the operation is 8682 // redundant. Instead, use BuildPairF64's operands directly. 8683 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8684 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8685 8686 if (Op0->isUndef()) { 8687 SDValue Lo = DAG.getUNDEF(MVT::i32); 8688 SDValue Hi = DAG.getUNDEF(MVT::i32); 8689 return DCI.CombineTo(N, Lo, Hi); 8690 } 8691 8692 SDLoc DL(N); 8693 8694 // It's cheaper to materialise two 32-bit integers than to load a double 8695 // from the constant pool and transfer it to integer registers through the 8696 // stack. 8697 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8698 APInt V = C->getValueAPF().bitcastToAPInt(); 8699 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8700 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8701 return DCI.CombineTo(N, Lo, Hi); 8702 } 8703 8704 // This is a target-specific version of a DAGCombine performed in 8705 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8706 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8707 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8708 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8709 !Op0.getNode()->hasOneUse()) 8710 break; 8711 SDValue NewSplitF64 = 8712 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8713 Op0.getOperand(0)); 8714 SDValue Lo = NewSplitF64.getValue(0); 8715 SDValue Hi = NewSplitF64.getValue(1); 8716 APInt SignBit = APInt::getSignMask(32); 8717 if (Op0.getOpcode() == ISD::FNEG) { 8718 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8719 DAG.getConstant(SignBit, DL, MVT::i32)); 8720 return DCI.CombineTo(N, Lo, NewHi); 8721 } 8722 assert(Op0.getOpcode() == ISD::FABS); 8723 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8724 DAG.getConstant(~SignBit, DL, MVT::i32)); 8725 return DCI.CombineTo(N, Lo, NewHi); 8726 } 8727 case RISCVISD::SLLW: 8728 case RISCVISD::SRAW: 8729 case RISCVISD::SRLW: { 8730 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8731 if (SimplifyDemandedLowBitsHelper(0, 32) || 8732 SimplifyDemandedLowBitsHelper(1, 5)) 8733 return SDValue(N, 0); 8734 8735 break; 8736 } 8737 case ISD::ROTR: 8738 case ISD::ROTL: 8739 case RISCVISD::RORW: 8740 case RISCVISD::ROLW: { 8741 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8742 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8743 if (SimplifyDemandedLowBitsHelper(0, 32) || 8744 SimplifyDemandedLowBitsHelper(1, 5)) 8745 return SDValue(N, 0); 8746 } 8747 8748 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8749 } 8750 case RISCVISD::CLZW: 8751 case RISCVISD::CTZW: { 8752 // Only the lower 32 bits of the first operand are read 8753 if (SimplifyDemandedLowBitsHelper(0, 32)) 8754 return SDValue(N, 0); 8755 break; 8756 } 8757 case RISCVISD::GREV: 8758 case RISCVISD::GORC: { 8759 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8760 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8761 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8762 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8763 return SDValue(N, 0); 8764 8765 return combineGREVI_GORCI(N, DAG); 8766 } 8767 case RISCVISD::GREVW: 8768 case RISCVISD::GORCW: { 8769 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8770 if (SimplifyDemandedLowBitsHelper(0, 32) || 8771 SimplifyDemandedLowBitsHelper(1, 5)) 8772 return SDValue(N, 0); 8773 8774 break; 8775 } 8776 case RISCVISD::SHFL: 8777 case RISCVISD::UNSHFL: { 8778 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8779 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8780 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8781 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8782 return SDValue(N, 0); 8783 8784 break; 8785 } 8786 case RISCVISD::SHFLW: 8787 case RISCVISD::UNSHFLW: { 8788 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8789 if (SimplifyDemandedLowBitsHelper(0, 32) || 8790 SimplifyDemandedLowBitsHelper(1, 4)) 8791 return SDValue(N, 0); 8792 8793 break; 8794 } 8795 case RISCVISD::BCOMPRESSW: 8796 case RISCVISD::BDECOMPRESSW: { 8797 // Only the lower 32 bits of LHS and RHS are read. 8798 if (SimplifyDemandedLowBitsHelper(0, 32) || 8799 SimplifyDemandedLowBitsHelper(1, 32)) 8800 return SDValue(N, 0); 8801 8802 break; 8803 } 8804 case RISCVISD::FSR: 8805 case RISCVISD::FSL: 8806 case RISCVISD::FSRW: 8807 case RISCVISD::FSLW: { 8808 bool IsWInstruction = 8809 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8810 unsigned BitWidth = 8811 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8812 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8813 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8814 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8815 return SDValue(N, 0); 8816 8817 break; 8818 } 8819 case RISCVISD::FMV_X_ANYEXTH: 8820 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8821 SDLoc DL(N); 8822 SDValue Op0 = N->getOperand(0); 8823 MVT VT = N->getSimpleValueType(0); 8824 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8825 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8826 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8827 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8828 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8829 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8830 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8831 assert(Op0.getOperand(0).getValueType() == VT && 8832 "Unexpected value type!"); 8833 return Op0.getOperand(0); 8834 } 8835 8836 // This is a target-specific version of a DAGCombine performed in 8837 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8838 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8839 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8840 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8841 !Op0.getNode()->hasOneUse()) 8842 break; 8843 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8844 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8845 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8846 if (Op0.getOpcode() == ISD::FNEG) 8847 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8848 DAG.getConstant(SignBit, DL, VT)); 8849 8850 assert(Op0.getOpcode() == ISD::FABS); 8851 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8852 DAG.getConstant(~SignBit, DL, VT)); 8853 } 8854 case ISD::ADD: 8855 return performADDCombine(N, DAG, Subtarget); 8856 case ISD::SUB: 8857 return performSUBCombine(N, DAG); 8858 case ISD::AND: 8859 return performANDCombine(N, DAG, Subtarget); 8860 case ISD::OR: 8861 return performORCombine(N, DAG, Subtarget); 8862 case ISD::XOR: 8863 return performXORCombine(N, DAG); 8864 case ISD::FADD: 8865 case ISD::UMAX: 8866 case ISD::UMIN: 8867 case ISD::SMAX: 8868 case ISD::SMIN: 8869 case ISD::FMAXNUM: 8870 case ISD::FMINNUM: 8871 return combineBinOpToReduce(N, DAG); 8872 case ISD::SIGN_EXTEND_INREG: 8873 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8874 case ISD::ZERO_EXTEND: 8875 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8876 // type legalization. This is safe because fp_to_uint produces poison if 8877 // it overflows. 8878 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8879 SDValue Src = N->getOperand(0); 8880 if (Src.getOpcode() == ISD::FP_TO_UINT && 8881 isTypeLegal(Src.getOperand(0).getValueType())) 8882 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8883 Src.getOperand(0)); 8884 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8885 isTypeLegal(Src.getOperand(1).getValueType())) { 8886 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8887 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8888 Src.getOperand(0), Src.getOperand(1)); 8889 DCI.CombineTo(N, Res); 8890 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8891 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8892 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8893 } 8894 } 8895 return SDValue(); 8896 case RISCVISD::SELECT_CC: { 8897 // Transform 8898 SDValue LHS = N->getOperand(0); 8899 SDValue RHS = N->getOperand(1); 8900 SDValue TrueV = N->getOperand(3); 8901 SDValue FalseV = N->getOperand(4); 8902 8903 // If the True and False values are the same, we don't need a select_cc. 8904 if (TrueV == FalseV) 8905 return TrueV; 8906 8907 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8908 if (!ISD::isIntEqualitySetCC(CCVal)) 8909 break; 8910 8911 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8912 // (select_cc X, Y, lt, trueV, falseV) 8913 // Sometimes the setcc is introduced after select_cc has been formed. 8914 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8915 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8916 // If we're looking for eq 0 instead of ne 0, we need to invert the 8917 // condition. 8918 bool Invert = CCVal == ISD::SETEQ; 8919 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8920 if (Invert) 8921 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8922 8923 SDLoc DL(N); 8924 RHS = LHS.getOperand(1); 8925 LHS = LHS.getOperand(0); 8926 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8927 8928 SDValue TargetCC = DAG.getCondCode(CCVal); 8929 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8930 {LHS, RHS, TargetCC, TrueV, FalseV}); 8931 } 8932 8933 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8934 // (select_cc X, Y, eq/ne, trueV, falseV) 8935 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8936 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8937 {LHS.getOperand(0), LHS.getOperand(1), 8938 N->getOperand(2), TrueV, FalseV}); 8939 // (select_cc X, 1, setne, trueV, falseV) -> 8940 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8941 // This can occur when legalizing some floating point comparisons. 8942 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8943 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8944 SDLoc DL(N); 8945 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8946 SDValue TargetCC = DAG.getCondCode(CCVal); 8947 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8948 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8949 {LHS, RHS, TargetCC, TrueV, FalseV}); 8950 } 8951 8952 break; 8953 } 8954 case RISCVISD::BR_CC: { 8955 SDValue LHS = N->getOperand(1); 8956 SDValue RHS = N->getOperand(2); 8957 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8958 if (!ISD::isIntEqualitySetCC(CCVal)) 8959 break; 8960 8961 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8962 // (br_cc X, Y, lt, dest) 8963 // Sometimes the setcc is introduced after br_cc has been formed. 8964 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8965 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8966 // If we're looking for eq 0 instead of ne 0, we need to invert the 8967 // condition. 8968 bool Invert = CCVal == ISD::SETEQ; 8969 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8970 if (Invert) 8971 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8972 8973 SDLoc DL(N); 8974 RHS = LHS.getOperand(1); 8975 LHS = LHS.getOperand(0); 8976 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8977 8978 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8979 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8980 N->getOperand(4)); 8981 } 8982 8983 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8984 // (br_cc X, Y, eq/ne, trueV, falseV) 8985 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8986 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8987 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8988 N->getOperand(3), N->getOperand(4)); 8989 8990 // (br_cc X, 1, setne, br_cc) -> 8991 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8992 // This can occur when legalizing some floating point comparisons. 8993 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8994 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8995 SDLoc DL(N); 8996 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8997 SDValue TargetCC = DAG.getCondCode(CCVal); 8998 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8999 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 9000 N->getOperand(0), LHS, RHS, TargetCC, 9001 N->getOperand(4)); 9002 } 9003 break; 9004 } 9005 case ISD::BITREVERSE: 9006 return performBITREVERSECombine(N, DAG, Subtarget); 9007 case ISD::FP_TO_SINT: 9008 case ISD::FP_TO_UINT: 9009 return performFP_TO_INTCombine(N, DCI, Subtarget); 9010 case ISD::FP_TO_SINT_SAT: 9011 case ISD::FP_TO_UINT_SAT: 9012 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 9013 case ISD::FCOPYSIGN: { 9014 EVT VT = N->getValueType(0); 9015 if (!VT.isVector()) 9016 break; 9017 // There is a form of VFSGNJ which injects the negated sign of its second 9018 // operand. Try and bubble any FNEG up after the extend/round to produce 9019 // this optimized pattern. Avoid modifying cases where FP_ROUND and 9020 // TRUNC=1. 9021 SDValue In2 = N->getOperand(1); 9022 // Avoid cases where the extend/round has multiple uses, as duplicating 9023 // those is typically more expensive than removing a fneg. 9024 if (!In2.hasOneUse()) 9025 break; 9026 if (In2.getOpcode() != ISD::FP_EXTEND && 9027 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 9028 break; 9029 In2 = In2.getOperand(0); 9030 if (In2.getOpcode() != ISD::FNEG) 9031 break; 9032 SDLoc DL(N); 9033 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 9034 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 9035 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 9036 } 9037 case ISD::MGATHER: 9038 case ISD::MSCATTER: 9039 case ISD::VP_GATHER: 9040 case ISD::VP_SCATTER: { 9041 if (!DCI.isBeforeLegalize()) 9042 break; 9043 SDValue Index, ScaleOp; 9044 bool IsIndexScaled = false; 9045 bool IsIndexSigned = false; 9046 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 9047 Index = VPGSN->getIndex(); 9048 ScaleOp = VPGSN->getScale(); 9049 IsIndexScaled = VPGSN->isIndexScaled(); 9050 IsIndexSigned = VPGSN->isIndexSigned(); 9051 } else { 9052 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9053 Index = MGSN->getIndex(); 9054 ScaleOp = MGSN->getScale(); 9055 IsIndexScaled = MGSN->isIndexScaled(); 9056 IsIndexSigned = MGSN->isIndexSigned(); 9057 } 9058 EVT IndexVT = Index.getValueType(); 9059 MVT XLenVT = Subtarget.getXLenVT(); 9060 // RISCV indexed loads only support the "unsigned unscaled" addressing 9061 // mode, so anything else must be manually legalized. 9062 bool NeedsIdxLegalization = 9063 IsIndexScaled || 9064 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9065 if (!NeedsIdxLegalization) 9066 break; 9067 9068 SDLoc DL(N); 9069 9070 // Any index legalization should first promote to XLenVT, so we don't lose 9071 // bits when scaling. This may create an illegal index type so we let 9072 // LLVM's legalization take care of the splitting. 9073 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9074 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9075 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9076 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9077 DL, IndexVT, Index); 9078 } 9079 9080 if (IsIndexScaled) { 9081 // Manually scale the indices. 9082 // TODO: Sanitize the scale operand here? 9083 // TODO: For VP nodes, should we use VP_SHL here? 9084 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9085 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9086 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9087 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9088 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9089 } 9090 9091 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9092 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9093 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9094 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9095 ScaleOp, VPGN->getMask(), 9096 VPGN->getVectorLength()}, 9097 VPGN->getMemOperand(), NewIndexTy); 9098 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9099 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9100 {VPSN->getChain(), VPSN->getValue(), 9101 VPSN->getBasePtr(), Index, ScaleOp, 9102 VPSN->getMask(), VPSN->getVectorLength()}, 9103 VPSN->getMemOperand(), NewIndexTy); 9104 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9105 return DAG.getMaskedGather( 9106 N->getVTList(), MGN->getMemoryVT(), DL, 9107 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9108 MGN->getBasePtr(), Index, ScaleOp}, 9109 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9110 const auto *MSN = cast<MaskedScatterSDNode>(N); 9111 return DAG.getMaskedScatter( 9112 N->getVTList(), MSN->getMemoryVT(), DL, 9113 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9114 Index, ScaleOp}, 9115 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9116 } 9117 case RISCVISD::SRA_VL: 9118 case RISCVISD::SRL_VL: 9119 case RISCVISD::SHL_VL: { 9120 SDValue ShAmt = N->getOperand(1); 9121 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9122 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9123 SDLoc DL(N); 9124 SDValue VL = N->getOperand(3); 9125 EVT VT = N->getValueType(0); 9126 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9127 ShAmt.getOperand(1), VL); 9128 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9129 N->getOperand(2), N->getOperand(3)); 9130 } 9131 break; 9132 } 9133 case ISD::SRA: 9134 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9135 return V; 9136 LLVM_FALLTHROUGH; 9137 case ISD::SRL: 9138 case ISD::SHL: { 9139 SDValue ShAmt = N->getOperand(1); 9140 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9141 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9142 SDLoc DL(N); 9143 EVT VT = N->getValueType(0); 9144 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9145 ShAmt.getOperand(1), 9146 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9147 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9148 } 9149 break; 9150 } 9151 case RISCVISD::ADD_VL: 9152 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9153 return V; 9154 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9155 case RISCVISD::SUB_VL: 9156 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9157 case RISCVISD::VWADD_W_VL: 9158 case RISCVISD::VWADDU_W_VL: 9159 case RISCVISD::VWSUB_W_VL: 9160 case RISCVISD::VWSUBU_W_VL: 9161 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9162 case RISCVISD::MUL_VL: 9163 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9164 return V; 9165 // Mul is commutative. 9166 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9167 case RISCVISD::VFMADD_VL: 9168 case RISCVISD::VFNMADD_VL: 9169 case RISCVISD::VFMSUB_VL: 9170 case RISCVISD::VFNMSUB_VL: { 9171 // Fold FNEG_VL into FMA opcodes. 9172 SDValue A = N->getOperand(0); 9173 SDValue B = N->getOperand(1); 9174 SDValue C = N->getOperand(2); 9175 SDValue Mask = N->getOperand(3); 9176 SDValue VL = N->getOperand(4); 9177 9178 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9179 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9180 V.getOperand(2) == VL) { 9181 // Return the negated input. 9182 V = V.getOperand(0); 9183 return true; 9184 } 9185 9186 return false; 9187 }; 9188 9189 bool NegA = invertIfNegative(A); 9190 bool NegB = invertIfNegative(B); 9191 bool NegC = invertIfNegative(C); 9192 9193 // If no operands are negated, we're done. 9194 if (!NegA && !NegB && !NegC) 9195 return SDValue(); 9196 9197 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9198 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9199 VL); 9200 } 9201 case ISD::STORE: { 9202 auto *Store = cast<StoreSDNode>(N); 9203 SDValue Val = Store->getValue(); 9204 // Combine store of vmv.x.s to vse with VL of 1. 9205 // FIXME: Support FP. 9206 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9207 SDValue Src = Val.getOperand(0); 9208 MVT VecVT = Src.getSimpleValueType(); 9209 EVT MemVT = Store->getMemoryVT(); 9210 // The memory VT and the element type must match. 9211 if (MemVT == VecVT.getVectorElementType()) { 9212 SDLoc DL(N); 9213 MVT MaskVT = getMaskTypeFor(VecVT); 9214 return DAG.getStoreVP( 9215 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9216 DAG.getConstant(1, DL, MaskVT), 9217 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9218 Store->getMemOperand(), Store->getAddressingMode(), 9219 Store->isTruncatingStore(), /*IsCompress*/ false); 9220 } 9221 } 9222 9223 break; 9224 } 9225 case ISD::SPLAT_VECTOR: { 9226 EVT VT = N->getValueType(0); 9227 // Only perform this combine on legal MVT types. 9228 if (!isTypeLegal(VT)) 9229 break; 9230 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9231 DAG, Subtarget)) 9232 return Gather; 9233 break; 9234 } 9235 case RISCVISD::VMV_V_X_VL: { 9236 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9237 // scalar input. 9238 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9239 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9240 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9241 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9242 return SDValue(N, 0); 9243 9244 break; 9245 } 9246 case ISD::INTRINSIC_WO_CHAIN: { 9247 unsigned IntNo = N->getConstantOperandVal(0); 9248 switch (IntNo) { 9249 // By default we do not combine any intrinsic. 9250 default: 9251 return SDValue(); 9252 case Intrinsic::riscv_vcpop: 9253 case Intrinsic::riscv_vcpop_mask: 9254 case Intrinsic::riscv_vfirst: 9255 case Intrinsic::riscv_vfirst_mask: { 9256 SDValue VL = N->getOperand(2); 9257 if (IntNo == Intrinsic::riscv_vcpop_mask || 9258 IntNo == Intrinsic::riscv_vfirst_mask) 9259 VL = N->getOperand(3); 9260 if (!isNullConstant(VL)) 9261 return SDValue(); 9262 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9263 SDLoc DL(N); 9264 EVT VT = N->getValueType(0); 9265 if (IntNo == Intrinsic::riscv_vfirst || 9266 IntNo == Intrinsic::riscv_vfirst_mask) 9267 return DAG.getConstant(-1, DL, VT); 9268 return DAG.getConstant(0, DL, VT); 9269 } 9270 } 9271 } 9272 case ISD::BITCAST: { 9273 assert(Subtarget.useRVVForFixedLengthVectors()); 9274 SDValue N0 = N->getOperand(0); 9275 EVT VT = N->getValueType(0); 9276 EVT SrcVT = N0.getValueType(); 9277 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9278 // type, widen both sides to avoid a trip through memory. 9279 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9280 VT.isScalarInteger()) { 9281 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9282 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9283 Ops[0] = N0; 9284 SDLoc DL(N); 9285 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9286 N0 = DAG.getBitcast(MVT::i8, N0); 9287 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9288 } 9289 9290 return SDValue(); 9291 } 9292 } 9293 9294 return SDValue(); 9295 } 9296 9297 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9298 const SDNode *N, CombineLevel Level) const { 9299 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9300 // materialised in fewer instructions than `(OP _, c1)`: 9301 // 9302 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9303 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9304 SDValue N0 = N->getOperand(0); 9305 EVT Ty = N0.getValueType(); 9306 if (Ty.isScalarInteger() && 9307 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9308 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9309 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9310 if (C1 && C2) { 9311 const APInt &C1Int = C1->getAPIntValue(); 9312 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9313 9314 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9315 // and the combine should happen, to potentially allow further combines 9316 // later. 9317 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9318 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9319 return true; 9320 9321 // We can materialise `c1` in an add immediate, so it's "free", and the 9322 // combine should be prevented. 9323 if (C1Int.getMinSignedBits() <= 64 && 9324 isLegalAddImmediate(C1Int.getSExtValue())) 9325 return false; 9326 9327 // Neither constant will fit into an immediate, so find materialisation 9328 // costs. 9329 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9330 Subtarget.getFeatureBits(), 9331 /*CompressionCost*/true); 9332 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9333 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9334 /*CompressionCost*/true); 9335 9336 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9337 // combine should be prevented. 9338 if (C1Cost < ShiftedC1Cost) 9339 return false; 9340 } 9341 } 9342 return true; 9343 } 9344 9345 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9346 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9347 TargetLoweringOpt &TLO) const { 9348 // Delay this optimization as late as possible. 9349 if (!TLO.LegalOps) 9350 return false; 9351 9352 EVT VT = Op.getValueType(); 9353 if (VT.isVector()) 9354 return false; 9355 9356 // Only handle AND for now. 9357 unsigned Opcode = Op.getOpcode(); 9358 if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR) 9359 return false; 9360 9361 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9362 if (!C) 9363 return false; 9364 9365 const APInt &Mask = C->getAPIntValue(); 9366 9367 // Clear all non-demanded bits initially. 9368 APInt ShrunkMask = Mask & DemandedBits; 9369 9370 // Try to make a smaller immediate by setting undemanded bits. 9371 9372 APInt ExpandedMask = Mask | ~DemandedBits; 9373 9374 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9375 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9376 }; 9377 auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool { 9378 if (NewMask == Mask) 9379 return true; 9380 SDLoc DL(Op); 9381 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType()); 9382 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), 9383 Op.getOperand(0), NewC); 9384 return TLO.CombineTo(Op, NewOp); 9385 }; 9386 9387 // If the shrunk mask fits in sign extended 12 bits, let the target 9388 // independent code apply it. 9389 if (ShrunkMask.isSignedIntN(12)) 9390 return false; 9391 9392 // And has a few special cases for zext. 9393 if (Opcode == ISD::AND) { 9394 // Preserve (and X, 0xffff) when zext.h is supported. 9395 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9396 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9397 if (IsLegalMask(NewMask)) 9398 return UseMask(NewMask); 9399 } 9400 9401 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9402 if (VT == MVT::i64) { 9403 APInt NewMask = APInt(64, 0xffffffff); 9404 if (IsLegalMask(NewMask)) 9405 return UseMask(NewMask); 9406 } 9407 } 9408 9409 // For the remaining optimizations, we need to be able to make a negative 9410 // number through a combination of mask and undemanded bits. 9411 if (!ExpandedMask.isNegative()) 9412 return false; 9413 9414 // What is the fewest number of bits we need to represent the negative number. 9415 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9416 9417 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9418 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9419 // If we can't create a simm12, we shouldn't change opaque constants. 9420 APInt NewMask = ShrunkMask; 9421 if (MinSignedBits <= 12) 9422 NewMask.setBitsFrom(11); 9423 else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9424 NewMask.setBitsFrom(31); 9425 else 9426 return false; 9427 9428 // Check that our new mask is a subset of the demanded mask. 9429 assert(IsLegalMask(NewMask)); 9430 return UseMask(NewMask); 9431 } 9432 9433 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9434 static const uint64_t GREVMasks[] = { 9435 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9436 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9437 9438 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9439 unsigned Shift = 1 << Stage; 9440 if (ShAmt & Shift) { 9441 uint64_t Mask = GREVMasks[Stage]; 9442 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9443 if (IsGORC) 9444 Res |= x; 9445 x = Res; 9446 } 9447 } 9448 9449 return x; 9450 } 9451 9452 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9453 KnownBits &Known, 9454 const APInt &DemandedElts, 9455 const SelectionDAG &DAG, 9456 unsigned Depth) const { 9457 unsigned BitWidth = Known.getBitWidth(); 9458 unsigned Opc = Op.getOpcode(); 9459 assert((Opc >= ISD::BUILTIN_OP_END || 9460 Opc == ISD::INTRINSIC_WO_CHAIN || 9461 Opc == ISD::INTRINSIC_W_CHAIN || 9462 Opc == ISD::INTRINSIC_VOID) && 9463 "Should use MaskedValueIsZero if you don't know whether Op" 9464 " is a target node!"); 9465 9466 Known.resetAll(); 9467 switch (Opc) { 9468 default: break; 9469 case RISCVISD::SELECT_CC: { 9470 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9471 // If we don't know any bits, early out. 9472 if (Known.isUnknown()) 9473 break; 9474 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9475 9476 // Only known if known in both the LHS and RHS. 9477 Known = KnownBits::commonBits(Known, Known2); 9478 break; 9479 } 9480 case RISCVISD::REMUW: { 9481 KnownBits Known2; 9482 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9483 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9484 // We only care about the lower 32 bits. 9485 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9486 // Restore the original width by sign extending. 9487 Known = Known.sext(BitWidth); 9488 break; 9489 } 9490 case RISCVISD::DIVUW: { 9491 KnownBits Known2; 9492 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9493 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9494 // We only care about the lower 32 bits. 9495 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9496 // Restore the original width by sign extending. 9497 Known = Known.sext(BitWidth); 9498 break; 9499 } 9500 case RISCVISD::CTZW: { 9501 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9502 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9503 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9504 Known.Zero.setBitsFrom(LowBits); 9505 break; 9506 } 9507 case RISCVISD::CLZW: { 9508 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9509 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9510 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9511 Known.Zero.setBitsFrom(LowBits); 9512 break; 9513 } 9514 case RISCVISD::GREV: 9515 case RISCVISD::GORC: { 9516 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9517 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9518 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9519 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9520 // To compute zeros, we need to invert the value and invert it back after. 9521 Known.Zero = 9522 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9523 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9524 } 9525 break; 9526 } 9527 case RISCVISD::READ_VLENB: { 9528 // We can use the minimum and maximum VLEN values to bound VLENB. We 9529 // know VLEN must be a power of two. 9530 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9531 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9532 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9533 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9534 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9535 if (MaxVLenB == MinVLenB) 9536 Known.One.setBit(Log2_32(MinVLenB)); 9537 break; 9538 } 9539 case ISD::INTRINSIC_W_CHAIN: 9540 case ISD::INTRINSIC_WO_CHAIN: { 9541 unsigned IntNo = 9542 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9543 switch (IntNo) { 9544 default: 9545 // We can't do anything for most intrinsics. 9546 break; 9547 case Intrinsic::riscv_vsetvli: 9548 case Intrinsic::riscv_vsetvlimax: 9549 case Intrinsic::riscv_vsetvli_opt: 9550 case Intrinsic::riscv_vsetvlimax_opt: 9551 // Assume that VL output is positive and would fit in an int32_t. 9552 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9553 if (BitWidth >= 32) 9554 Known.Zero.setBitsFrom(31); 9555 break; 9556 } 9557 break; 9558 } 9559 } 9560 } 9561 9562 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9563 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9564 unsigned Depth) const { 9565 switch (Op.getOpcode()) { 9566 default: 9567 break; 9568 case RISCVISD::SELECT_CC: { 9569 unsigned Tmp = 9570 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9571 if (Tmp == 1) return 1; // Early out. 9572 unsigned Tmp2 = 9573 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9574 return std::min(Tmp, Tmp2); 9575 } 9576 case RISCVISD::SLLW: 9577 case RISCVISD::SRAW: 9578 case RISCVISD::SRLW: 9579 case RISCVISD::DIVW: 9580 case RISCVISD::DIVUW: 9581 case RISCVISD::REMUW: 9582 case RISCVISD::ROLW: 9583 case RISCVISD::RORW: 9584 case RISCVISD::GREVW: 9585 case RISCVISD::GORCW: 9586 case RISCVISD::FSLW: 9587 case RISCVISD::FSRW: 9588 case RISCVISD::SHFLW: 9589 case RISCVISD::UNSHFLW: 9590 case RISCVISD::BCOMPRESSW: 9591 case RISCVISD::BDECOMPRESSW: 9592 case RISCVISD::BFPW: 9593 case RISCVISD::FCVT_W_RV64: 9594 case RISCVISD::FCVT_WU_RV64: 9595 case RISCVISD::STRICT_FCVT_W_RV64: 9596 case RISCVISD::STRICT_FCVT_WU_RV64: 9597 // TODO: As the result is sign-extended, this is conservatively correct. A 9598 // more precise answer could be calculated for SRAW depending on known 9599 // bits in the shift amount. 9600 return 33; 9601 case RISCVISD::SHFL: 9602 case RISCVISD::UNSHFL: { 9603 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9604 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9605 // will stay within the upper 32 bits. If there were more than 32 sign bits 9606 // before there will be at least 33 sign bits after. 9607 if (Op.getValueType() == MVT::i64 && 9608 isa<ConstantSDNode>(Op.getOperand(1)) && 9609 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9610 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9611 if (Tmp > 32) 9612 return 33; 9613 } 9614 break; 9615 } 9616 case RISCVISD::VMV_X_S: { 9617 // The number of sign bits of the scalar result is computed by obtaining the 9618 // element type of the input vector operand, subtracting its width from the 9619 // XLEN, and then adding one (sign bit within the element type). If the 9620 // element type is wider than XLen, the least-significant XLEN bits are 9621 // taken. 9622 unsigned XLen = Subtarget.getXLen(); 9623 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9624 if (EltBits <= XLen) 9625 return XLen - EltBits + 1; 9626 break; 9627 } 9628 } 9629 9630 return 1; 9631 } 9632 9633 const Constant * 9634 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9635 assert(Ld && "Unexpected null LoadSDNode"); 9636 if (!ISD::isNormalLoad(Ld)) 9637 return nullptr; 9638 9639 SDValue Ptr = Ld->getBasePtr(); 9640 9641 // Only constant pools with no offset are supported. 9642 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9643 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9644 if (!CNode || CNode->isMachineConstantPoolEntry() || 9645 CNode->getOffset() != 0) 9646 return nullptr; 9647 9648 return CNode; 9649 }; 9650 9651 // Simple case, LLA. 9652 if (Ptr.getOpcode() == RISCVISD::LLA) { 9653 auto *CNode = GetSupportedConstantPool(Ptr); 9654 if (!CNode || CNode->getTargetFlags() != 0) 9655 return nullptr; 9656 9657 return CNode->getConstVal(); 9658 } 9659 9660 // Look for a HI and ADD_LO pair. 9661 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9662 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9663 return nullptr; 9664 9665 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9666 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9667 9668 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9669 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9670 return nullptr; 9671 9672 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9673 return nullptr; 9674 9675 return CNodeLo->getConstVal(); 9676 } 9677 9678 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9679 MachineBasicBlock *BB) { 9680 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9681 9682 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9683 // Should the count have wrapped while it was being read, we need to try 9684 // again. 9685 // ... 9686 // read: 9687 // rdcycleh x3 # load high word of cycle 9688 // rdcycle x2 # load low word of cycle 9689 // rdcycleh x4 # load high word of cycle 9690 // bne x3, x4, read # check if high word reads match, otherwise try again 9691 // ... 9692 9693 MachineFunction &MF = *BB->getParent(); 9694 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9695 MachineFunction::iterator It = ++BB->getIterator(); 9696 9697 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9698 MF.insert(It, LoopMBB); 9699 9700 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9701 MF.insert(It, DoneMBB); 9702 9703 // Transfer the remainder of BB and its successor edges to DoneMBB. 9704 DoneMBB->splice(DoneMBB->begin(), BB, 9705 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9706 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9707 9708 BB->addSuccessor(LoopMBB); 9709 9710 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9711 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9712 Register LoReg = MI.getOperand(0).getReg(); 9713 Register HiReg = MI.getOperand(1).getReg(); 9714 DebugLoc DL = MI.getDebugLoc(); 9715 9716 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9717 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9718 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9719 .addReg(RISCV::X0); 9720 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9721 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9722 .addReg(RISCV::X0); 9723 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9724 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9725 .addReg(RISCV::X0); 9726 9727 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9728 .addReg(HiReg) 9729 .addReg(ReadAgainReg) 9730 .addMBB(LoopMBB); 9731 9732 LoopMBB->addSuccessor(LoopMBB); 9733 LoopMBB->addSuccessor(DoneMBB); 9734 9735 MI.eraseFromParent(); 9736 9737 return DoneMBB; 9738 } 9739 9740 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9741 MachineBasicBlock *BB) { 9742 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9743 9744 MachineFunction &MF = *BB->getParent(); 9745 DebugLoc DL = MI.getDebugLoc(); 9746 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9747 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9748 Register LoReg = MI.getOperand(0).getReg(); 9749 Register HiReg = MI.getOperand(1).getReg(); 9750 Register SrcReg = MI.getOperand(2).getReg(); 9751 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9752 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9753 9754 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9755 RI); 9756 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9757 MachineMemOperand *MMOLo = 9758 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9759 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9760 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9761 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9762 .addFrameIndex(FI) 9763 .addImm(0) 9764 .addMemOperand(MMOLo); 9765 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9766 .addFrameIndex(FI) 9767 .addImm(4) 9768 .addMemOperand(MMOHi); 9769 MI.eraseFromParent(); // The pseudo instruction is gone now. 9770 return BB; 9771 } 9772 9773 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9774 MachineBasicBlock *BB) { 9775 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9776 "Unexpected instruction"); 9777 9778 MachineFunction &MF = *BB->getParent(); 9779 DebugLoc DL = MI.getDebugLoc(); 9780 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9781 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9782 Register DstReg = MI.getOperand(0).getReg(); 9783 Register LoReg = MI.getOperand(1).getReg(); 9784 Register HiReg = MI.getOperand(2).getReg(); 9785 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9786 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9787 9788 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9789 MachineMemOperand *MMOLo = 9790 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9791 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9792 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9793 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9794 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9795 .addFrameIndex(FI) 9796 .addImm(0) 9797 .addMemOperand(MMOLo); 9798 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9799 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9800 .addFrameIndex(FI) 9801 .addImm(4) 9802 .addMemOperand(MMOHi); 9803 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9804 MI.eraseFromParent(); // The pseudo instruction is gone now. 9805 return BB; 9806 } 9807 9808 static bool isSelectPseudo(MachineInstr &MI) { 9809 switch (MI.getOpcode()) { 9810 default: 9811 return false; 9812 case RISCV::Select_GPR_Using_CC_GPR: 9813 case RISCV::Select_FPR16_Using_CC_GPR: 9814 case RISCV::Select_FPR32_Using_CC_GPR: 9815 case RISCV::Select_FPR64_Using_CC_GPR: 9816 return true; 9817 } 9818 } 9819 9820 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9821 unsigned RelOpcode, unsigned EqOpcode, 9822 const RISCVSubtarget &Subtarget) { 9823 DebugLoc DL = MI.getDebugLoc(); 9824 Register DstReg = MI.getOperand(0).getReg(); 9825 Register Src1Reg = MI.getOperand(1).getReg(); 9826 Register Src2Reg = MI.getOperand(2).getReg(); 9827 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9828 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9829 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9830 9831 // Save the current FFLAGS. 9832 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9833 9834 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9835 .addReg(Src1Reg) 9836 .addReg(Src2Reg); 9837 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9838 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9839 9840 // Restore the FFLAGS. 9841 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9842 .addReg(SavedFFlags, RegState::Kill); 9843 9844 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9845 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9846 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9847 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9848 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9849 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9850 9851 // Erase the pseudoinstruction. 9852 MI.eraseFromParent(); 9853 return BB; 9854 } 9855 9856 static MachineBasicBlock * 9857 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second, 9858 MachineBasicBlock *ThisMBB, 9859 const RISCVSubtarget &Subtarget) { 9860 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5) 9861 // Without this, custom-inserter would have generated: 9862 // 9863 // A 9864 // | \ 9865 // | B 9866 // | / 9867 // C 9868 // | \ 9869 // | D 9870 // | / 9871 // E 9872 // 9873 // A: X = ...; Y = ... 9874 // B: empty 9875 // C: Z = PHI [X, A], [Y, B] 9876 // D: empty 9877 // E: PHI [X, C], [Z, D] 9878 // 9879 // If we lower both Select_FPRX_ in a single step, we can instead generate: 9880 // 9881 // A 9882 // | \ 9883 // | C 9884 // | /| 9885 // |/ | 9886 // | | 9887 // | D 9888 // | / 9889 // E 9890 // 9891 // A: X = ...; Y = ... 9892 // D: empty 9893 // E: PHI [X, A], [X, C], [Y, D] 9894 9895 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9896 const DebugLoc &DL = First.getDebugLoc(); 9897 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock(); 9898 MachineFunction *F = ThisMBB->getParent(); 9899 MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB); 9900 MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB); 9901 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9902 MachineFunction::iterator It = ++ThisMBB->getIterator(); 9903 F->insert(It, FirstMBB); 9904 F->insert(It, SecondMBB); 9905 F->insert(It, SinkMBB); 9906 9907 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB. 9908 SinkMBB->splice(SinkMBB->begin(), ThisMBB, 9909 std::next(MachineBasicBlock::iterator(First)), 9910 ThisMBB->end()); 9911 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB); 9912 9913 // Fallthrough block for ThisMBB. 9914 ThisMBB->addSuccessor(FirstMBB); 9915 // Fallthrough block for FirstMBB. 9916 FirstMBB->addSuccessor(SecondMBB); 9917 ThisMBB->addSuccessor(SinkMBB); 9918 FirstMBB->addSuccessor(SinkMBB); 9919 // This is fallthrough. 9920 SecondMBB->addSuccessor(SinkMBB); 9921 9922 auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm()); 9923 Register FLHS = First.getOperand(1).getReg(); 9924 Register FRHS = First.getOperand(2).getReg(); 9925 // Insert appropriate branch. 9926 BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC)) 9927 .addReg(FLHS) 9928 .addReg(FRHS) 9929 .addMBB(SinkMBB); 9930 9931 Register SLHS = Second.getOperand(1).getReg(); 9932 Register SRHS = Second.getOperand(2).getReg(); 9933 Register Op1Reg4 = First.getOperand(4).getReg(); 9934 Register Op1Reg5 = First.getOperand(5).getReg(); 9935 9936 auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm()); 9937 // Insert appropriate branch. 9938 BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC)) 9939 .addReg(SLHS) 9940 .addReg(SRHS) 9941 .addMBB(SinkMBB); 9942 9943 Register DestReg = Second.getOperand(0).getReg(); 9944 Register Op2Reg4 = Second.getOperand(4).getReg(); 9945 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg) 9946 .addReg(Op2Reg4) 9947 .addMBB(ThisMBB) 9948 .addReg(Op1Reg4) 9949 .addMBB(FirstMBB) 9950 .addReg(Op1Reg5) 9951 .addMBB(SecondMBB); 9952 9953 // Now remove the Select_FPRX_s. 9954 First.eraseFromParent(); 9955 Second.eraseFromParent(); 9956 return SinkMBB; 9957 } 9958 9959 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9960 MachineBasicBlock *BB, 9961 const RISCVSubtarget &Subtarget) { 9962 // To "insert" Select_* instructions, we actually have to insert the triangle 9963 // control-flow pattern. The incoming instructions know the destination vreg 9964 // to set, the condition code register to branch on, the true/false values to 9965 // select between, and the condcode to use to select the appropriate branch. 9966 // 9967 // We produce the following control flow: 9968 // HeadMBB 9969 // | \ 9970 // | IfFalseMBB 9971 // | / 9972 // TailMBB 9973 // 9974 // When we find a sequence of selects we attempt to optimize their emission 9975 // by sharing the control flow. Currently we only handle cases where we have 9976 // multiple selects with the exact same condition (same LHS, RHS and CC). 9977 // The selects may be interleaved with other instructions if the other 9978 // instructions meet some requirements we deem safe: 9979 // - They are debug instructions. Otherwise, 9980 // - They do not have side-effects, do not access memory and their inputs do 9981 // not depend on the results of the select pseudo-instructions. 9982 // The TrueV/FalseV operands of the selects cannot depend on the result of 9983 // previous selects in the sequence. 9984 // These conditions could be further relaxed. See the X86 target for a 9985 // related approach and more information. 9986 // 9987 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)) 9988 // is checked here and handled by a separate function - 9989 // EmitLoweredCascadedSelect. 9990 Register LHS = MI.getOperand(1).getReg(); 9991 Register RHS = MI.getOperand(2).getReg(); 9992 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9993 9994 SmallVector<MachineInstr *, 4> SelectDebugValues; 9995 SmallSet<Register, 4> SelectDests; 9996 SelectDests.insert(MI.getOperand(0).getReg()); 9997 9998 MachineInstr *LastSelectPseudo = &MI; 9999 auto Next = next_nodbg(MI.getIterator(), BB->instr_end()); 10000 if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() && 10001 Next->getOpcode() == MI.getOpcode() && 10002 Next->getOperand(5).getReg() == MI.getOperand(0).getReg() && 10003 Next->getOperand(5).isKill()) { 10004 return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget); 10005 } 10006 10007 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 10008 SequenceMBBI != E; ++SequenceMBBI) { 10009 if (SequenceMBBI->isDebugInstr()) 10010 continue; 10011 if (isSelectPseudo(*SequenceMBBI)) { 10012 if (SequenceMBBI->getOperand(1).getReg() != LHS || 10013 SequenceMBBI->getOperand(2).getReg() != RHS || 10014 SequenceMBBI->getOperand(3).getImm() != CC || 10015 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 10016 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 10017 break; 10018 LastSelectPseudo = &*SequenceMBBI; 10019 SequenceMBBI->collectDebugValues(SelectDebugValues); 10020 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 10021 } else { 10022 if (SequenceMBBI->hasUnmodeledSideEffects() || 10023 SequenceMBBI->mayLoadOrStore()) 10024 break; 10025 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 10026 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 10027 })) 10028 break; 10029 } 10030 } 10031 10032 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 10033 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10034 DebugLoc DL = MI.getDebugLoc(); 10035 MachineFunction::iterator I = ++BB->getIterator(); 10036 10037 MachineBasicBlock *HeadMBB = BB; 10038 MachineFunction *F = BB->getParent(); 10039 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 10040 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 10041 10042 F->insert(I, IfFalseMBB); 10043 F->insert(I, TailMBB); 10044 10045 // Transfer debug instructions associated with the selects to TailMBB. 10046 for (MachineInstr *DebugInstr : SelectDebugValues) { 10047 TailMBB->push_back(DebugInstr->removeFromParent()); 10048 } 10049 10050 // Move all instructions after the sequence to TailMBB. 10051 TailMBB->splice(TailMBB->end(), HeadMBB, 10052 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 10053 // Update machine-CFG edges by transferring all successors of the current 10054 // block to the new block which will contain the Phi nodes for the selects. 10055 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 10056 // Set the successors for HeadMBB. 10057 HeadMBB->addSuccessor(IfFalseMBB); 10058 HeadMBB->addSuccessor(TailMBB); 10059 10060 // Insert appropriate branch. 10061 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 10062 .addReg(LHS) 10063 .addReg(RHS) 10064 .addMBB(TailMBB); 10065 10066 // IfFalseMBB just falls through to TailMBB. 10067 IfFalseMBB->addSuccessor(TailMBB); 10068 10069 // Create PHIs for all of the select pseudo-instructions. 10070 auto SelectMBBI = MI.getIterator(); 10071 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 10072 auto InsertionPoint = TailMBB->begin(); 10073 while (SelectMBBI != SelectEnd) { 10074 auto Next = std::next(SelectMBBI); 10075 if (isSelectPseudo(*SelectMBBI)) { 10076 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 10077 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 10078 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 10079 .addReg(SelectMBBI->getOperand(4).getReg()) 10080 .addMBB(HeadMBB) 10081 .addReg(SelectMBBI->getOperand(5).getReg()) 10082 .addMBB(IfFalseMBB); 10083 SelectMBBI->eraseFromParent(); 10084 } 10085 SelectMBBI = Next; 10086 } 10087 10088 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 10089 return TailMBB; 10090 } 10091 10092 MachineBasicBlock * 10093 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10094 MachineBasicBlock *BB) const { 10095 switch (MI.getOpcode()) { 10096 default: 10097 llvm_unreachable("Unexpected instr type to insert"); 10098 case RISCV::ReadCycleWide: 10099 assert(!Subtarget.is64Bit() && 10100 "ReadCycleWrite is only to be used on riscv32"); 10101 return emitReadCycleWidePseudo(MI, BB); 10102 case RISCV::Select_GPR_Using_CC_GPR: 10103 case RISCV::Select_FPR16_Using_CC_GPR: 10104 case RISCV::Select_FPR32_Using_CC_GPR: 10105 case RISCV::Select_FPR64_Using_CC_GPR: 10106 return emitSelectPseudo(MI, BB, Subtarget); 10107 case RISCV::BuildPairF64Pseudo: 10108 return emitBuildPairF64Pseudo(MI, BB); 10109 case RISCV::SplitF64Pseudo: 10110 return emitSplitF64Pseudo(MI, BB); 10111 case RISCV::PseudoQuietFLE_H: 10112 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 10113 case RISCV::PseudoQuietFLT_H: 10114 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 10115 case RISCV::PseudoQuietFLE_S: 10116 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 10117 case RISCV::PseudoQuietFLT_S: 10118 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 10119 case RISCV::PseudoQuietFLE_D: 10120 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 10121 case RISCV::PseudoQuietFLT_D: 10122 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 10123 } 10124 } 10125 10126 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10127 SDNode *Node) const { 10128 // Add FRM dependency to any instructions with dynamic rounding mode. 10129 unsigned Opc = MI.getOpcode(); 10130 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 10131 if (Idx < 0) 10132 return; 10133 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 10134 return; 10135 // If the instruction already reads FRM, don't add another read. 10136 if (MI.readsRegister(RISCV::FRM)) 10137 return; 10138 MI.addOperand( 10139 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 10140 } 10141 10142 // Calling Convention Implementation. 10143 // The expectations for frontend ABI lowering vary from target to target. 10144 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 10145 // details, but this is a longer term goal. For now, we simply try to keep the 10146 // role of the frontend as simple and well-defined as possible. The rules can 10147 // be summarised as: 10148 // * Never split up large scalar arguments. We handle them here. 10149 // * If a hardfloat calling convention is being used, and the struct may be 10150 // passed in a pair of registers (fp+fp, int+fp), and both registers are 10151 // available, then pass as two separate arguments. If either the GPRs or FPRs 10152 // are exhausted, then pass according to the rule below. 10153 // * If a struct could never be passed in registers or directly in a stack 10154 // slot (as it is larger than 2*XLEN and the floating point rules don't 10155 // apply), then pass it using a pointer with the byval attribute. 10156 // * If a struct is less than 2*XLEN, then coerce to either a two-element 10157 // word-sized array or a 2*XLEN scalar (depending on alignment). 10158 // * The frontend can determine whether a struct is returned by reference or 10159 // not based on its size and fields. If it will be returned by reference, the 10160 // frontend must modify the prototype so a pointer with the sret annotation is 10161 // passed as the first argument. This is not necessary for large scalar 10162 // returns. 10163 // * Struct return values and varargs should be coerced to structs containing 10164 // register-size fields in the same situations they would be for fixed 10165 // arguments. 10166 10167 static const MCPhysReg ArgGPRs[] = { 10168 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 10169 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 10170 }; 10171 static const MCPhysReg ArgFPR16s[] = { 10172 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10173 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10174 }; 10175 static const MCPhysReg ArgFPR32s[] = { 10176 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10177 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10178 }; 10179 static const MCPhysReg ArgFPR64s[] = { 10180 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10181 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10182 }; 10183 // This is an interim calling convention and it may be changed in the future. 10184 static const MCPhysReg ArgVRs[] = { 10185 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10186 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10187 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10188 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10189 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10190 RISCV::V20M2, RISCV::V22M2}; 10191 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10192 RISCV::V20M4}; 10193 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10194 10195 // Pass a 2*XLEN argument that has been split into two XLEN values through 10196 // registers or the stack as necessary. 10197 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10198 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10199 MVT ValVT2, MVT LocVT2, 10200 ISD::ArgFlagsTy ArgFlags2) { 10201 unsigned XLenInBytes = XLen / 8; 10202 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10203 // At least one half can be passed via register. 10204 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10205 VA1.getLocVT(), CCValAssign::Full)); 10206 } else { 10207 // Both halves must be passed on the stack, with proper alignment. 10208 Align StackAlign = 10209 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10210 State.addLoc( 10211 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10212 State.AllocateStack(XLenInBytes, StackAlign), 10213 VA1.getLocVT(), CCValAssign::Full)); 10214 State.addLoc(CCValAssign::getMem( 10215 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10216 LocVT2, CCValAssign::Full)); 10217 return false; 10218 } 10219 10220 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10221 // The second half can also be passed via register. 10222 State.addLoc( 10223 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10224 } else { 10225 // The second half is passed via the stack, without additional alignment. 10226 State.addLoc(CCValAssign::getMem( 10227 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10228 LocVT2, CCValAssign::Full)); 10229 } 10230 10231 return false; 10232 } 10233 10234 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10235 Optional<unsigned> FirstMaskArgument, 10236 CCState &State, const RISCVTargetLowering &TLI) { 10237 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10238 if (RC == &RISCV::VRRegClass) { 10239 // Assign the first mask argument to V0. 10240 // This is an interim calling convention and it may be changed in the 10241 // future. 10242 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10243 return State.AllocateReg(RISCV::V0); 10244 return State.AllocateReg(ArgVRs); 10245 } 10246 if (RC == &RISCV::VRM2RegClass) 10247 return State.AllocateReg(ArgVRM2s); 10248 if (RC == &RISCV::VRM4RegClass) 10249 return State.AllocateReg(ArgVRM4s); 10250 if (RC == &RISCV::VRM8RegClass) 10251 return State.AllocateReg(ArgVRM8s); 10252 llvm_unreachable("Unhandled register class for ValueType"); 10253 } 10254 10255 // Implements the RISC-V calling convention. Returns true upon failure. 10256 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10257 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10258 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10259 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10260 Optional<unsigned> FirstMaskArgument) { 10261 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10262 assert(XLen == 32 || XLen == 64); 10263 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10264 10265 // Any return value split in to more than two values can't be returned 10266 // directly. Vectors are returned via the available vector registers. 10267 if (!LocVT.isVector() && IsRet && ValNo > 1) 10268 return true; 10269 10270 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10271 // variadic argument, or if no F16/F32 argument registers are available. 10272 bool UseGPRForF16_F32 = true; 10273 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10274 // variadic argument, or if no F64 argument registers are available. 10275 bool UseGPRForF64 = true; 10276 10277 switch (ABI) { 10278 default: 10279 llvm_unreachable("Unexpected ABI"); 10280 case RISCVABI::ABI_ILP32: 10281 case RISCVABI::ABI_LP64: 10282 break; 10283 case RISCVABI::ABI_ILP32F: 10284 case RISCVABI::ABI_LP64F: 10285 UseGPRForF16_F32 = !IsFixed; 10286 break; 10287 case RISCVABI::ABI_ILP32D: 10288 case RISCVABI::ABI_LP64D: 10289 UseGPRForF16_F32 = !IsFixed; 10290 UseGPRForF64 = !IsFixed; 10291 break; 10292 } 10293 10294 // FPR16, FPR32, and FPR64 alias each other. 10295 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10296 UseGPRForF16_F32 = true; 10297 UseGPRForF64 = true; 10298 } 10299 10300 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10301 // similar local variables rather than directly checking against the target 10302 // ABI. 10303 10304 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10305 LocVT = XLenVT; 10306 LocInfo = CCValAssign::BCvt; 10307 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10308 LocVT = MVT::i64; 10309 LocInfo = CCValAssign::BCvt; 10310 } 10311 10312 // If this is a variadic argument, the RISC-V calling convention requires 10313 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10314 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10315 // be used regardless of whether the original argument was split during 10316 // legalisation or not. The argument will not be passed by registers if the 10317 // original type is larger than 2*XLEN, so the register alignment rule does 10318 // not apply. 10319 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10320 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10321 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10322 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10323 // Skip 'odd' register if necessary. 10324 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10325 State.AllocateReg(ArgGPRs); 10326 } 10327 10328 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10329 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10330 State.getPendingArgFlags(); 10331 10332 assert(PendingLocs.size() == PendingArgFlags.size() && 10333 "PendingLocs and PendingArgFlags out of sync"); 10334 10335 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10336 // registers are exhausted. 10337 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10338 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10339 "Can't lower f64 if it is split"); 10340 // Depending on available argument GPRS, f64 may be passed in a pair of 10341 // GPRs, split between a GPR and the stack, or passed completely on the 10342 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10343 // cases. 10344 Register Reg = State.AllocateReg(ArgGPRs); 10345 LocVT = MVT::i32; 10346 if (!Reg) { 10347 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10348 State.addLoc( 10349 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10350 return false; 10351 } 10352 if (!State.AllocateReg(ArgGPRs)) 10353 State.AllocateStack(4, Align(4)); 10354 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10355 return false; 10356 } 10357 10358 // Fixed-length vectors are located in the corresponding scalable-vector 10359 // container types. 10360 if (ValVT.isFixedLengthVector()) 10361 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10362 10363 // Split arguments might be passed indirectly, so keep track of the pending 10364 // values. Split vectors are passed via a mix of registers and indirectly, so 10365 // treat them as we would any other argument. 10366 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10367 LocVT = XLenVT; 10368 LocInfo = CCValAssign::Indirect; 10369 PendingLocs.push_back( 10370 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10371 PendingArgFlags.push_back(ArgFlags); 10372 if (!ArgFlags.isSplitEnd()) { 10373 return false; 10374 } 10375 } 10376 10377 // If the split argument only had two elements, it should be passed directly 10378 // in registers or on the stack. 10379 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10380 PendingLocs.size() <= 2) { 10381 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10382 // Apply the normal calling convention rules to the first half of the 10383 // split argument. 10384 CCValAssign VA = PendingLocs[0]; 10385 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10386 PendingLocs.clear(); 10387 PendingArgFlags.clear(); 10388 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10389 ArgFlags); 10390 } 10391 10392 // Allocate to a register if possible, or else a stack slot. 10393 Register Reg; 10394 unsigned StoreSizeBytes = XLen / 8; 10395 Align StackAlign = Align(XLen / 8); 10396 10397 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10398 Reg = State.AllocateReg(ArgFPR16s); 10399 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10400 Reg = State.AllocateReg(ArgFPR32s); 10401 else if (ValVT == MVT::f64 && !UseGPRForF64) 10402 Reg = State.AllocateReg(ArgFPR64s); 10403 else if (ValVT.isVector()) { 10404 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10405 if (!Reg) { 10406 // For return values, the vector must be passed fully via registers or 10407 // via the stack. 10408 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10409 // but we're using all of them. 10410 if (IsRet) 10411 return true; 10412 // Try using a GPR to pass the address 10413 if ((Reg = State.AllocateReg(ArgGPRs))) { 10414 LocVT = XLenVT; 10415 LocInfo = CCValAssign::Indirect; 10416 } else if (ValVT.isScalableVector()) { 10417 LocVT = XLenVT; 10418 LocInfo = CCValAssign::Indirect; 10419 } else { 10420 // Pass fixed-length vectors on the stack. 10421 LocVT = ValVT; 10422 StoreSizeBytes = ValVT.getStoreSize(); 10423 // Align vectors to their element sizes, being careful for vXi1 10424 // vectors. 10425 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10426 } 10427 } 10428 } else { 10429 Reg = State.AllocateReg(ArgGPRs); 10430 } 10431 10432 unsigned StackOffset = 10433 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10434 10435 // If we reach this point and PendingLocs is non-empty, we must be at the 10436 // end of a split argument that must be passed indirectly. 10437 if (!PendingLocs.empty()) { 10438 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10439 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10440 10441 for (auto &It : PendingLocs) { 10442 if (Reg) 10443 It.convertToReg(Reg); 10444 else 10445 It.convertToMem(StackOffset); 10446 State.addLoc(It); 10447 } 10448 PendingLocs.clear(); 10449 PendingArgFlags.clear(); 10450 return false; 10451 } 10452 10453 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10454 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10455 "Expected an XLenVT or vector types at this stage"); 10456 10457 if (Reg) { 10458 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10459 return false; 10460 } 10461 10462 // When a floating-point value is passed on the stack, no bit-conversion is 10463 // needed. 10464 if (ValVT.isFloatingPoint()) { 10465 LocVT = ValVT; 10466 LocInfo = CCValAssign::Full; 10467 } 10468 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10469 return false; 10470 } 10471 10472 template <typename ArgTy> 10473 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10474 for (const auto &ArgIdx : enumerate(Args)) { 10475 MVT ArgVT = ArgIdx.value().VT; 10476 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10477 return ArgIdx.index(); 10478 } 10479 return None; 10480 } 10481 10482 void RISCVTargetLowering::analyzeInputArgs( 10483 MachineFunction &MF, CCState &CCInfo, 10484 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10485 RISCVCCAssignFn Fn) const { 10486 unsigned NumArgs = Ins.size(); 10487 FunctionType *FType = MF.getFunction().getFunctionType(); 10488 10489 Optional<unsigned> FirstMaskArgument; 10490 if (Subtarget.hasVInstructions()) 10491 FirstMaskArgument = preAssignMask(Ins); 10492 10493 for (unsigned i = 0; i != NumArgs; ++i) { 10494 MVT ArgVT = Ins[i].VT; 10495 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10496 10497 Type *ArgTy = nullptr; 10498 if (IsRet) 10499 ArgTy = FType->getReturnType(); 10500 else if (Ins[i].isOrigArg()) 10501 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10502 10503 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10504 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10505 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10506 FirstMaskArgument)) { 10507 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10508 << EVT(ArgVT).getEVTString() << '\n'); 10509 llvm_unreachable(nullptr); 10510 } 10511 } 10512 } 10513 10514 void RISCVTargetLowering::analyzeOutputArgs( 10515 MachineFunction &MF, CCState &CCInfo, 10516 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10517 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10518 unsigned NumArgs = Outs.size(); 10519 10520 Optional<unsigned> FirstMaskArgument; 10521 if (Subtarget.hasVInstructions()) 10522 FirstMaskArgument = preAssignMask(Outs); 10523 10524 for (unsigned i = 0; i != NumArgs; i++) { 10525 MVT ArgVT = Outs[i].VT; 10526 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10527 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10528 10529 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10530 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10531 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10532 FirstMaskArgument)) { 10533 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10534 << EVT(ArgVT).getEVTString() << "\n"); 10535 llvm_unreachable(nullptr); 10536 } 10537 } 10538 } 10539 10540 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10541 // values. 10542 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10543 const CCValAssign &VA, const SDLoc &DL, 10544 const RISCVSubtarget &Subtarget) { 10545 switch (VA.getLocInfo()) { 10546 default: 10547 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10548 case CCValAssign::Full: 10549 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10550 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10551 break; 10552 case CCValAssign::BCvt: 10553 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10554 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10555 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10556 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10557 else 10558 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10559 break; 10560 } 10561 return Val; 10562 } 10563 10564 // The caller is responsible for loading the full value if the argument is 10565 // passed with CCValAssign::Indirect. 10566 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10567 const CCValAssign &VA, const SDLoc &DL, 10568 const RISCVTargetLowering &TLI) { 10569 MachineFunction &MF = DAG.getMachineFunction(); 10570 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10571 EVT LocVT = VA.getLocVT(); 10572 SDValue Val; 10573 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10574 Register VReg = RegInfo.createVirtualRegister(RC); 10575 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10576 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10577 10578 if (VA.getLocInfo() == CCValAssign::Indirect) 10579 return Val; 10580 10581 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10582 } 10583 10584 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10585 const CCValAssign &VA, const SDLoc &DL, 10586 const RISCVSubtarget &Subtarget) { 10587 EVT LocVT = VA.getLocVT(); 10588 10589 switch (VA.getLocInfo()) { 10590 default: 10591 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10592 case CCValAssign::Full: 10593 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10594 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10595 break; 10596 case CCValAssign::BCvt: 10597 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10598 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10599 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10600 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10601 else 10602 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10603 break; 10604 } 10605 return Val; 10606 } 10607 10608 // The caller is responsible for loading the full value if the argument is 10609 // passed with CCValAssign::Indirect. 10610 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10611 const CCValAssign &VA, const SDLoc &DL) { 10612 MachineFunction &MF = DAG.getMachineFunction(); 10613 MachineFrameInfo &MFI = MF.getFrameInfo(); 10614 EVT LocVT = VA.getLocVT(); 10615 EVT ValVT = VA.getValVT(); 10616 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10617 if (ValVT.isScalableVector()) { 10618 // When the value is a scalable vector, we save the pointer which points to 10619 // the scalable vector value in the stack. The ValVT will be the pointer 10620 // type, instead of the scalable vector type. 10621 ValVT = LocVT; 10622 } 10623 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10624 /*IsImmutable=*/true); 10625 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10626 SDValue Val; 10627 10628 ISD::LoadExtType ExtType; 10629 switch (VA.getLocInfo()) { 10630 default: 10631 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10632 case CCValAssign::Full: 10633 case CCValAssign::Indirect: 10634 case CCValAssign::BCvt: 10635 ExtType = ISD::NON_EXTLOAD; 10636 break; 10637 } 10638 Val = DAG.getExtLoad( 10639 ExtType, DL, LocVT, Chain, FIN, 10640 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10641 return Val; 10642 } 10643 10644 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10645 const CCValAssign &VA, const SDLoc &DL) { 10646 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10647 "Unexpected VA"); 10648 MachineFunction &MF = DAG.getMachineFunction(); 10649 MachineFrameInfo &MFI = MF.getFrameInfo(); 10650 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10651 10652 if (VA.isMemLoc()) { 10653 // f64 is passed on the stack. 10654 int FI = 10655 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10656 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10657 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10658 MachinePointerInfo::getFixedStack(MF, FI)); 10659 } 10660 10661 assert(VA.isRegLoc() && "Expected register VA assignment"); 10662 10663 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10664 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10665 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10666 SDValue Hi; 10667 if (VA.getLocReg() == RISCV::X17) { 10668 // Second half of f64 is passed on the stack. 10669 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10670 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10671 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10672 MachinePointerInfo::getFixedStack(MF, FI)); 10673 } else { 10674 // Second half of f64 is passed in another GPR. 10675 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10676 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10677 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10678 } 10679 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10680 } 10681 10682 // FastCC has less than 1% performance improvement for some particular 10683 // benchmark. But theoretically, it may has benenfit for some cases. 10684 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10685 unsigned ValNo, MVT ValVT, MVT LocVT, 10686 CCValAssign::LocInfo LocInfo, 10687 ISD::ArgFlagsTy ArgFlags, CCState &State, 10688 bool IsFixed, bool IsRet, Type *OrigTy, 10689 const RISCVTargetLowering &TLI, 10690 Optional<unsigned> FirstMaskArgument) { 10691 10692 // X5 and X6 might be used for save-restore libcall. 10693 static const MCPhysReg GPRList[] = { 10694 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10695 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10696 RISCV::X29, RISCV::X30, RISCV::X31}; 10697 10698 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10699 if (unsigned Reg = State.AllocateReg(GPRList)) { 10700 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10701 return false; 10702 } 10703 } 10704 10705 if (LocVT == MVT::f16) { 10706 static const MCPhysReg FPR16List[] = { 10707 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10708 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10709 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10710 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10711 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10712 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10713 return false; 10714 } 10715 } 10716 10717 if (LocVT == MVT::f32) { 10718 static const MCPhysReg FPR32List[] = { 10719 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10720 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10721 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10722 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10723 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10724 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10725 return false; 10726 } 10727 } 10728 10729 if (LocVT == MVT::f64) { 10730 static const MCPhysReg FPR64List[] = { 10731 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10732 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10733 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10734 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10735 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10736 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10737 return false; 10738 } 10739 } 10740 10741 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10742 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10743 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10744 return false; 10745 } 10746 10747 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10748 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10749 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10750 return false; 10751 } 10752 10753 if (LocVT.isVector()) { 10754 if (unsigned Reg = 10755 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10756 // Fixed-length vectors are located in the corresponding scalable-vector 10757 // container types. 10758 if (ValVT.isFixedLengthVector()) 10759 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10760 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10761 } else { 10762 // Try and pass the address via a "fast" GPR. 10763 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10764 LocInfo = CCValAssign::Indirect; 10765 LocVT = TLI.getSubtarget().getXLenVT(); 10766 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10767 } else if (ValVT.isFixedLengthVector()) { 10768 auto StackAlign = 10769 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10770 unsigned StackOffset = 10771 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10772 State.addLoc( 10773 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10774 } else { 10775 // Can't pass scalable vectors on the stack. 10776 return true; 10777 } 10778 } 10779 10780 return false; 10781 } 10782 10783 return true; // CC didn't match. 10784 } 10785 10786 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10787 CCValAssign::LocInfo LocInfo, 10788 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10789 10790 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10791 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10792 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10793 static const MCPhysReg GPRList[] = { 10794 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10795 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10796 if (unsigned Reg = State.AllocateReg(GPRList)) { 10797 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10798 return false; 10799 } 10800 } 10801 10802 if (LocVT == MVT::f32) { 10803 // Pass in STG registers: F1, ..., F6 10804 // fs0 ... fs5 10805 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10806 RISCV::F18_F, RISCV::F19_F, 10807 RISCV::F20_F, RISCV::F21_F}; 10808 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10809 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10810 return false; 10811 } 10812 } 10813 10814 if (LocVT == MVT::f64) { 10815 // Pass in STG registers: D1, ..., D6 10816 // fs6 ... fs11 10817 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10818 RISCV::F24_D, RISCV::F25_D, 10819 RISCV::F26_D, RISCV::F27_D}; 10820 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10821 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10822 return false; 10823 } 10824 } 10825 10826 report_fatal_error("No registers left in GHC calling convention"); 10827 return true; 10828 } 10829 10830 // Transform physical registers into virtual registers. 10831 SDValue RISCVTargetLowering::LowerFormalArguments( 10832 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10833 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10834 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10835 10836 MachineFunction &MF = DAG.getMachineFunction(); 10837 10838 switch (CallConv) { 10839 default: 10840 report_fatal_error("Unsupported calling convention"); 10841 case CallingConv::C: 10842 case CallingConv::Fast: 10843 break; 10844 case CallingConv::GHC: 10845 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10846 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10847 report_fatal_error( 10848 "GHC calling convention requires the F and D instruction set extensions"); 10849 } 10850 10851 const Function &Func = MF.getFunction(); 10852 if (Func.hasFnAttribute("interrupt")) { 10853 if (!Func.arg_empty()) 10854 report_fatal_error( 10855 "Functions with the interrupt attribute cannot have arguments!"); 10856 10857 StringRef Kind = 10858 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10859 10860 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10861 report_fatal_error( 10862 "Function interrupt attribute argument not supported!"); 10863 } 10864 10865 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10866 MVT XLenVT = Subtarget.getXLenVT(); 10867 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10868 // Used with vargs to acumulate store chains. 10869 std::vector<SDValue> OutChains; 10870 10871 // Assign locations to all of the incoming arguments. 10872 SmallVector<CCValAssign, 16> ArgLocs; 10873 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10874 10875 if (CallConv == CallingConv::GHC) 10876 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10877 else 10878 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10879 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10880 : CC_RISCV); 10881 10882 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10883 CCValAssign &VA = ArgLocs[i]; 10884 SDValue ArgValue; 10885 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10886 // case. 10887 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10888 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10889 else if (VA.isRegLoc()) 10890 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10891 else 10892 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10893 10894 if (VA.getLocInfo() == CCValAssign::Indirect) { 10895 // If the original argument was split and passed by reference (e.g. i128 10896 // on RV32), we need to load all parts of it here (using the same 10897 // address). Vectors may be partly split to registers and partly to the 10898 // stack, in which case the base address is partly offset and subsequent 10899 // stores are relative to that. 10900 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10901 MachinePointerInfo())); 10902 unsigned ArgIndex = Ins[i].OrigArgIndex; 10903 unsigned ArgPartOffset = Ins[i].PartOffset; 10904 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10905 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10906 CCValAssign &PartVA = ArgLocs[i + 1]; 10907 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10908 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10909 if (PartVA.getValVT().isScalableVector()) 10910 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10911 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10912 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10913 MachinePointerInfo())); 10914 ++i; 10915 } 10916 continue; 10917 } 10918 InVals.push_back(ArgValue); 10919 } 10920 10921 if (IsVarArg) { 10922 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10923 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10924 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10925 MachineFrameInfo &MFI = MF.getFrameInfo(); 10926 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10927 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10928 10929 // Offset of the first variable argument from stack pointer, and size of 10930 // the vararg save area. For now, the varargs save area is either zero or 10931 // large enough to hold a0-a7. 10932 int VaArgOffset, VarArgsSaveSize; 10933 10934 // If all registers are allocated, then all varargs must be passed on the 10935 // stack and we don't need to save any argregs. 10936 if (ArgRegs.size() == Idx) { 10937 VaArgOffset = CCInfo.getNextStackOffset(); 10938 VarArgsSaveSize = 0; 10939 } else { 10940 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10941 VaArgOffset = -VarArgsSaveSize; 10942 } 10943 10944 // Record the frame index of the first variable argument 10945 // which is a value necessary to VASTART. 10946 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10947 RVFI->setVarArgsFrameIndex(FI); 10948 10949 // If saving an odd number of registers then create an extra stack slot to 10950 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10951 // offsets to even-numbered registered remain 2*XLEN-aligned. 10952 if (Idx % 2) { 10953 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10954 VarArgsSaveSize += XLenInBytes; 10955 } 10956 10957 // Copy the integer registers that may have been used for passing varargs 10958 // to the vararg save area. 10959 for (unsigned I = Idx; I < ArgRegs.size(); 10960 ++I, VaArgOffset += XLenInBytes) { 10961 const Register Reg = RegInfo.createVirtualRegister(RC); 10962 RegInfo.addLiveIn(ArgRegs[I], Reg); 10963 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10964 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10965 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10966 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10967 MachinePointerInfo::getFixedStack(MF, FI)); 10968 cast<StoreSDNode>(Store.getNode()) 10969 ->getMemOperand() 10970 ->setValue((Value *)nullptr); 10971 OutChains.push_back(Store); 10972 } 10973 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10974 } 10975 10976 // All stores are grouped in one node to allow the matching between 10977 // the size of Ins and InVals. This only happens for vararg functions. 10978 if (!OutChains.empty()) { 10979 OutChains.push_back(Chain); 10980 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10981 } 10982 10983 return Chain; 10984 } 10985 10986 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10987 /// for tail call optimization. 10988 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10989 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10990 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10991 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10992 10993 auto &Callee = CLI.Callee; 10994 auto CalleeCC = CLI.CallConv; 10995 auto &Outs = CLI.Outs; 10996 auto &Caller = MF.getFunction(); 10997 auto CallerCC = Caller.getCallingConv(); 10998 10999 // Exception-handling functions need a special set of instructions to 11000 // indicate a return to the hardware. Tail-calling another function would 11001 // probably break this. 11002 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 11003 // should be expanded as new function attributes are introduced. 11004 if (Caller.hasFnAttribute("interrupt")) 11005 return false; 11006 11007 // Do not tail call opt if the stack is used to pass parameters. 11008 if (CCInfo.getNextStackOffset() != 0) 11009 return false; 11010 11011 // Do not tail call opt if any parameters need to be passed indirectly. 11012 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 11013 // passed indirectly. So the address of the value will be passed in a 11014 // register, or if not available, then the address is put on the stack. In 11015 // order to pass indirectly, space on the stack often needs to be allocated 11016 // in order to store the value. In this case the CCInfo.getNextStackOffset() 11017 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 11018 // are passed CCValAssign::Indirect. 11019 for (auto &VA : ArgLocs) 11020 if (VA.getLocInfo() == CCValAssign::Indirect) 11021 return false; 11022 11023 // Do not tail call opt if either caller or callee uses struct return 11024 // semantics. 11025 auto IsCallerStructRet = Caller.hasStructRetAttr(); 11026 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 11027 if (IsCallerStructRet || IsCalleeStructRet) 11028 return false; 11029 11030 // Externally-defined functions with weak linkage should not be 11031 // tail-called. The behaviour of branch instructions in this situation (as 11032 // used for tail calls) is implementation-defined, so we cannot rely on the 11033 // linker replacing the tail call with a return. 11034 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 11035 const GlobalValue *GV = G->getGlobal(); 11036 if (GV->hasExternalWeakLinkage()) 11037 return false; 11038 } 11039 11040 // The callee has to preserve all registers the caller needs to preserve. 11041 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11042 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 11043 if (CalleeCC != CallerCC) { 11044 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 11045 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 11046 return false; 11047 } 11048 11049 // Byval parameters hand the function a pointer directly into the stack area 11050 // we want to reuse during a tail call. Working around this *is* possible 11051 // but less efficient and uglier in LowerCall. 11052 for (auto &Arg : Outs) 11053 if (Arg.Flags.isByVal()) 11054 return false; 11055 11056 return true; 11057 } 11058 11059 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 11060 return DAG.getDataLayout().getPrefTypeAlign( 11061 VT.getTypeForEVT(*DAG.getContext())); 11062 } 11063 11064 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 11065 // and output parameter nodes. 11066 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 11067 SmallVectorImpl<SDValue> &InVals) const { 11068 SelectionDAG &DAG = CLI.DAG; 11069 SDLoc &DL = CLI.DL; 11070 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 11071 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 11072 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 11073 SDValue Chain = CLI.Chain; 11074 SDValue Callee = CLI.Callee; 11075 bool &IsTailCall = CLI.IsTailCall; 11076 CallingConv::ID CallConv = CLI.CallConv; 11077 bool IsVarArg = CLI.IsVarArg; 11078 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 11079 MVT XLenVT = Subtarget.getXLenVT(); 11080 11081 MachineFunction &MF = DAG.getMachineFunction(); 11082 11083 // Analyze the operands of the call, assigning locations to each operand. 11084 SmallVector<CCValAssign, 16> ArgLocs; 11085 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 11086 11087 if (CallConv == CallingConv::GHC) 11088 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 11089 else 11090 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 11091 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 11092 : CC_RISCV); 11093 11094 // Check if it's really possible to do a tail call. 11095 if (IsTailCall) 11096 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 11097 11098 if (IsTailCall) 11099 ++NumTailCalls; 11100 else if (CLI.CB && CLI.CB->isMustTailCall()) 11101 report_fatal_error("failed to perform tail call elimination on a call " 11102 "site marked musttail"); 11103 11104 // Get a count of how many bytes are to be pushed on the stack. 11105 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 11106 11107 // Create local copies for byval args 11108 SmallVector<SDValue, 8> ByValArgs; 11109 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11110 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11111 if (!Flags.isByVal()) 11112 continue; 11113 11114 SDValue Arg = OutVals[i]; 11115 unsigned Size = Flags.getByValSize(); 11116 Align Alignment = Flags.getNonZeroByValAlign(); 11117 11118 int FI = 11119 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 11120 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11121 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 11122 11123 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 11124 /*IsVolatile=*/false, 11125 /*AlwaysInline=*/false, IsTailCall, 11126 MachinePointerInfo(), MachinePointerInfo()); 11127 ByValArgs.push_back(FIPtr); 11128 } 11129 11130 if (!IsTailCall) 11131 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 11132 11133 // Copy argument values to their designated locations. 11134 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 11135 SmallVector<SDValue, 8> MemOpChains; 11136 SDValue StackPtr; 11137 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 11138 CCValAssign &VA = ArgLocs[i]; 11139 SDValue ArgValue = OutVals[i]; 11140 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11141 11142 // Handle passing f64 on RV32D with a soft float ABI as a special case. 11143 bool IsF64OnRV32DSoftABI = 11144 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 11145 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 11146 SDValue SplitF64 = DAG.getNode( 11147 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 11148 SDValue Lo = SplitF64.getValue(0); 11149 SDValue Hi = SplitF64.getValue(1); 11150 11151 Register RegLo = VA.getLocReg(); 11152 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 11153 11154 if (RegLo == RISCV::X17) { 11155 // Second half of f64 is passed on the stack. 11156 // Work out the address of the stack slot. 11157 if (!StackPtr.getNode()) 11158 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11159 // Emit the store. 11160 MemOpChains.push_back( 11161 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 11162 } else { 11163 // Second half of f64 is passed in another GPR. 11164 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11165 Register RegHigh = RegLo + 1; 11166 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 11167 } 11168 continue; 11169 } 11170 11171 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 11172 // as any other MemLoc. 11173 11174 // Promote the value if needed. 11175 // For now, only handle fully promoted and indirect arguments. 11176 if (VA.getLocInfo() == CCValAssign::Indirect) { 11177 // Store the argument in a stack slot and pass its address. 11178 Align StackAlign = 11179 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11180 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11181 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11182 // If the original argument was split (e.g. i128), we need 11183 // to store the required parts of it here (and pass just one address). 11184 // Vectors may be partly split to registers and partly to the stack, in 11185 // which case the base address is partly offset and subsequent stores are 11186 // relative to that. 11187 unsigned ArgIndex = Outs[i].OrigArgIndex; 11188 unsigned ArgPartOffset = Outs[i].PartOffset; 11189 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11190 // Calculate the total size to store. We don't have access to what we're 11191 // actually storing other than performing the loop and collecting the 11192 // info. 11193 SmallVector<std::pair<SDValue, SDValue>> Parts; 11194 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11195 SDValue PartValue = OutVals[i + 1]; 11196 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11197 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11198 EVT PartVT = PartValue.getValueType(); 11199 if (PartVT.isScalableVector()) 11200 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11201 StoredSize += PartVT.getStoreSize(); 11202 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11203 Parts.push_back(std::make_pair(PartValue, Offset)); 11204 ++i; 11205 } 11206 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11207 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11208 MemOpChains.push_back( 11209 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11210 MachinePointerInfo::getFixedStack(MF, FI))); 11211 for (const auto &Part : Parts) { 11212 SDValue PartValue = Part.first; 11213 SDValue PartOffset = Part.second; 11214 SDValue Address = 11215 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11216 MemOpChains.push_back( 11217 DAG.getStore(Chain, DL, PartValue, Address, 11218 MachinePointerInfo::getFixedStack(MF, FI))); 11219 } 11220 ArgValue = SpillSlot; 11221 } else { 11222 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11223 } 11224 11225 // Use local copy if it is a byval arg. 11226 if (Flags.isByVal()) 11227 ArgValue = ByValArgs[j++]; 11228 11229 if (VA.isRegLoc()) { 11230 // Queue up the argument copies and emit them at the end. 11231 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11232 } else { 11233 assert(VA.isMemLoc() && "Argument not register or memory"); 11234 assert(!IsTailCall && "Tail call not allowed if stack is used " 11235 "for passing parameters"); 11236 11237 // Work out the address of the stack slot. 11238 if (!StackPtr.getNode()) 11239 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11240 SDValue Address = 11241 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11242 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11243 11244 // Emit the store. 11245 MemOpChains.push_back( 11246 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11247 } 11248 } 11249 11250 // Join the stores, which are independent of one another. 11251 if (!MemOpChains.empty()) 11252 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11253 11254 SDValue Glue; 11255 11256 // Build a sequence of copy-to-reg nodes, chained and glued together. 11257 for (auto &Reg : RegsToPass) { 11258 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11259 Glue = Chain.getValue(1); 11260 } 11261 11262 // Validate that none of the argument registers have been marked as 11263 // reserved, if so report an error. Do the same for the return address if this 11264 // is not a tailcall. 11265 validateCCReservedRegs(RegsToPass, MF); 11266 if (!IsTailCall && 11267 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11268 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11269 MF.getFunction(), 11270 "Return address register required, but has been reserved."}); 11271 11272 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11273 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11274 // split it and then direct call can be matched by PseudoCALL. 11275 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11276 const GlobalValue *GV = S->getGlobal(); 11277 11278 unsigned OpFlags = RISCVII::MO_CALL; 11279 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11280 OpFlags = RISCVII::MO_PLT; 11281 11282 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11283 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11284 unsigned OpFlags = RISCVII::MO_CALL; 11285 11286 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11287 nullptr)) 11288 OpFlags = RISCVII::MO_PLT; 11289 11290 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11291 } 11292 11293 // The first call operand is the chain and the second is the target address. 11294 SmallVector<SDValue, 8> Ops; 11295 Ops.push_back(Chain); 11296 Ops.push_back(Callee); 11297 11298 // Add argument registers to the end of the list so that they are 11299 // known live into the call. 11300 for (auto &Reg : RegsToPass) 11301 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11302 11303 if (!IsTailCall) { 11304 // Add a register mask operand representing the call-preserved registers. 11305 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11306 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11307 assert(Mask && "Missing call preserved mask for calling convention"); 11308 Ops.push_back(DAG.getRegisterMask(Mask)); 11309 } 11310 11311 // Glue the call to the argument copies, if any. 11312 if (Glue.getNode()) 11313 Ops.push_back(Glue); 11314 11315 // Emit the call. 11316 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11317 11318 if (IsTailCall) { 11319 MF.getFrameInfo().setHasTailCall(); 11320 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11321 } 11322 11323 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11324 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11325 Glue = Chain.getValue(1); 11326 11327 // Mark the end of the call, which is glued to the call itself. 11328 Chain = DAG.getCALLSEQ_END(Chain, 11329 DAG.getConstant(NumBytes, DL, PtrVT, true), 11330 DAG.getConstant(0, DL, PtrVT, true), 11331 Glue, DL); 11332 Glue = Chain.getValue(1); 11333 11334 // Assign locations to each value returned by this call. 11335 SmallVector<CCValAssign, 16> RVLocs; 11336 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11337 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11338 11339 // Copy all of the result registers out of their specified physreg. 11340 for (auto &VA : RVLocs) { 11341 // Copy the value out 11342 SDValue RetValue = 11343 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11344 // Glue the RetValue to the end of the call sequence 11345 Chain = RetValue.getValue(1); 11346 Glue = RetValue.getValue(2); 11347 11348 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11349 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11350 SDValue RetValue2 = 11351 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11352 Chain = RetValue2.getValue(1); 11353 Glue = RetValue2.getValue(2); 11354 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11355 RetValue2); 11356 } 11357 11358 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11359 11360 InVals.push_back(RetValue); 11361 } 11362 11363 return Chain; 11364 } 11365 11366 bool RISCVTargetLowering::CanLowerReturn( 11367 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11368 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11369 SmallVector<CCValAssign, 16> RVLocs; 11370 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11371 11372 Optional<unsigned> FirstMaskArgument; 11373 if (Subtarget.hasVInstructions()) 11374 FirstMaskArgument = preAssignMask(Outs); 11375 11376 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11377 MVT VT = Outs[i].VT; 11378 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11379 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11380 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11381 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11382 *this, FirstMaskArgument)) 11383 return false; 11384 } 11385 return true; 11386 } 11387 11388 SDValue 11389 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11390 bool IsVarArg, 11391 const SmallVectorImpl<ISD::OutputArg> &Outs, 11392 const SmallVectorImpl<SDValue> &OutVals, 11393 const SDLoc &DL, SelectionDAG &DAG) const { 11394 const MachineFunction &MF = DAG.getMachineFunction(); 11395 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11396 11397 // Stores the assignment of the return value to a location. 11398 SmallVector<CCValAssign, 16> RVLocs; 11399 11400 // Info about the registers and stack slot. 11401 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11402 *DAG.getContext()); 11403 11404 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11405 nullptr, CC_RISCV); 11406 11407 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11408 report_fatal_error("GHC functions return void only"); 11409 11410 SDValue Glue; 11411 SmallVector<SDValue, 4> RetOps(1, Chain); 11412 11413 // Copy the result values into the output registers. 11414 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11415 SDValue Val = OutVals[i]; 11416 CCValAssign &VA = RVLocs[i]; 11417 assert(VA.isRegLoc() && "Can only return in registers!"); 11418 11419 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11420 // Handle returning f64 on RV32D with a soft float ABI. 11421 assert(VA.isRegLoc() && "Expected return via registers"); 11422 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11423 DAG.getVTList(MVT::i32, MVT::i32), Val); 11424 SDValue Lo = SplitF64.getValue(0); 11425 SDValue Hi = SplitF64.getValue(1); 11426 Register RegLo = VA.getLocReg(); 11427 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11428 Register RegHi = RegLo + 1; 11429 11430 if (STI.isRegisterReservedByUser(RegLo) || 11431 STI.isRegisterReservedByUser(RegHi)) 11432 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11433 MF.getFunction(), 11434 "Return value register required, but has been reserved."}); 11435 11436 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11437 Glue = Chain.getValue(1); 11438 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11439 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11440 Glue = Chain.getValue(1); 11441 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11442 } else { 11443 // Handle a 'normal' return. 11444 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11445 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11446 11447 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11448 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11449 MF.getFunction(), 11450 "Return value register required, but has been reserved."}); 11451 11452 // Guarantee that all emitted copies are stuck together. 11453 Glue = Chain.getValue(1); 11454 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11455 } 11456 } 11457 11458 RetOps[0] = Chain; // Update chain. 11459 11460 // Add the glue node if we have it. 11461 if (Glue.getNode()) { 11462 RetOps.push_back(Glue); 11463 } 11464 11465 unsigned RetOpc = RISCVISD::RET_FLAG; 11466 // Interrupt service routines use different return instructions. 11467 const Function &Func = DAG.getMachineFunction().getFunction(); 11468 if (Func.hasFnAttribute("interrupt")) { 11469 if (!Func.getReturnType()->isVoidTy()) 11470 report_fatal_error( 11471 "Functions with the interrupt attribute must have void return type!"); 11472 11473 MachineFunction &MF = DAG.getMachineFunction(); 11474 StringRef Kind = 11475 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11476 11477 if (Kind == "user") 11478 RetOpc = RISCVISD::URET_FLAG; 11479 else if (Kind == "supervisor") 11480 RetOpc = RISCVISD::SRET_FLAG; 11481 else 11482 RetOpc = RISCVISD::MRET_FLAG; 11483 } 11484 11485 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11486 } 11487 11488 void RISCVTargetLowering::validateCCReservedRegs( 11489 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11490 MachineFunction &MF) const { 11491 const Function &F = MF.getFunction(); 11492 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11493 11494 if (llvm::any_of(Regs, [&STI](auto Reg) { 11495 return STI.isRegisterReservedByUser(Reg.first); 11496 })) 11497 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11498 F, "Argument register required, but has been reserved."}); 11499 } 11500 11501 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11502 return CI->isTailCall(); 11503 } 11504 11505 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11506 #define NODE_NAME_CASE(NODE) \ 11507 case RISCVISD::NODE: \ 11508 return "RISCVISD::" #NODE; 11509 // clang-format off 11510 switch ((RISCVISD::NodeType)Opcode) { 11511 case RISCVISD::FIRST_NUMBER: 11512 break; 11513 NODE_NAME_CASE(RET_FLAG) 11514 NODE_NAME_CASE(URET_FLAG) 11515 NODE_NAME_CASE(SRET_FLAG) 11516 NODE_NAME_CASE(MRET_FLAG) 11517 NODE_NAME_CASE(CALL) 11518 NODE_NAME_CASE(SELECT_CC) 11519 NODE_NAME_CASE(BR_CC) 11520 NODE_NAME_CASE(BuildPairF64) 11521 NODE_NAME_CASE(SplitF64) 11522 NODE_NAME_CASE(TAIL) 11523 NODE_NAME_CASE(ADD_LO) 11524 NODE_NAME_CASE(HI) 11525 NODE_NAME_CASE(LLA) 11526 NODE_NAME_CASE(ADD_TPREL) 11527 NODE_NAME_CASE(LA) 11528 NODE_NAME_CASE(LA_TLS_IE) 11529 NODE_NAME_CASE(LA_TLS_GD) 11530 NODE_NAME_CASE(MULHSU) 11531 NODE_NAME_CASE(SLLW) 11532 NODE_NAME_CASE(SRAW) 11533 NODE_NAME_CASE(SRLW) 11534 NODE_NAME_CASE(DIVW) 11535 NODE_NAME_CASE(DIVUW) 11536 NODE_NAME_CASE(REMUW) 11537 NODE_NAME_CASE(ROLW) 11538 NODE_NAME_CASE(RORW) 11539 NODE_NAME_CASE(CLZW) 11540 NODE_NAME_CASE(CTZW) 11541 NODE_NAME_CASE(FSLW) 11542 NODE_NAME_CASE(FSRW) 11543 NODE_NAME_CASE(FSL) 11544 NODE_NAME_CASE(FSR) 11545 NODE_NAME_CASE(FMV_H_X) 11546 NODE_NAME_CASE(FMV_X_ANYEXTH) 11547 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11548 NODE_NAME_CASE(FMV_W_X_RV64) 11549 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11550 NODE_NAME_CASE(FCVT_X) 11551 NODE_NAME_CASE(FCVT_XU) 11552 NODE_NAME_CASE(FCVT_W_RV64) 11553 NODE_NAME_CASE(FCVT_WU_RV64) 11554 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11555 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11556 NODE_NAME_CASE(READ_CYCLE_WIDE) 11557 NODE_NAME_CASE(GREV) 11558 NODE_NAME_CASE(GREVW) 11559 NODE_NAME_CASE(GORC) 11560 NODE_NAME_CASE(GORCW) 11561 NODE_NAME_CASE(SHFL) 11562 NODE_NAME_CASE(SHFLW) 11563 NODE_NAME_CASE(UNSHFL) 11564 NODE_NAME_CASE(UNSHFLW) 11565 NODE_NAME_CASE(BFP) 11566 NODE_NAME_CASE(BFPW) 11567 NODE_NAME_CASE(BCOMPRESS) 11568 NODE_NAME_CASE(BCOMPRESSW) 11569 NODE_NAME_CASE(BDECOMPRESS) 11570 NODE_NAME_CASE(BDECOMPRESSW) 11571 NODE_NAME_CASE(VMV_V_X_VL) 11572 NODE_NAME_CASE(VFMV_V_F_VL) 11573 NODE_NAME_CASE(VMV_X_S) 11574 NODE_NAME_CASE(VMV_S_X_VL) 11575 NODE_NAME_CASE(VFMV_S_F_VL) 11576 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11577 NODE_NAME_CASE(READ_VLENB) 11578 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11579 NODE_NAME_CASE(VSLIDEUP_VL) 11580 NODE_NAME_CASE(VSLIDE1UP_VL) 11581 NODE_NAME_CASE(VSLIDEDOWN_VL) 11582 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11583 NODE_NAME_CASE(VID_VL) 11584 NODE_NAME_CASE(VFNCVT_ROD_VL) 11585 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11586 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11587 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11588 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11589 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11590 NODE_NAME_CASE(VECREDUCE_AND_VL) 11591 NODE_NAME_CASE(VECREDUCE_OR_VL) 11592 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11593 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11594 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11595 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11596 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11597 NODE_NAME_CASE(ADD_VL) 11598 NODE_NAME_CASE(AND_VL) 11599 NODE_NAME_CASE(MUL_VL) 11600 NODE_NAME_CASE(OR_VL) 11601 NODE_NAME_CASE(SDIV_VL) 11602 NODE_NAME_CASE(SHL_VL) 11603 NODE_NAME_CASE(SREM_VL) 11604 NODE_NAME_CASE(SRA_VL) 11605 NODE_NAME_CASE(SRL_VL) 11606 NODE_NAME_CASE(SUB_VL) 11607 NODE_NAME_CASE(UDIV_VL) 11608 NODE_NAME_CASE(UREM_VL) 11609 NODE_NAME_CASE(XOR_VL) 11610 NODE_NAME_CASE(SADDSAT_VL) 11611 NODE_NAME_CASE(UADDSAT_VL) 11612 NODE_NAME_CASE(SSUBSAT_VL) 11613 NODE_NAME_CASE(USUBSAT_VL) 11614 NODE_NAME_CASE(FADD_VL) 11615 NODE_NAME_CASE(FSUB_VL) 11616 NODE_NAME_CASE(FMUL_VL) 11617 NODE_NAME_CASE(FDIV_VL) 11618 NODE_NAME_CASE(FNEG_VL) 11619 NODE_NAME_CASE(FABS_VL) 11620 NODE_NAME_CASE(FSQRT_VL) 11621 NODE_NAME_CASE(VFMADD_VL) 11622 NODE_NAME_CASE(VFNMADD_VL) 11623 NODE_NAME_CASE(VFMSUB_VL) 11624 NODE_NAME_CASE(VFNMSUB_VL) 11625 NODE_NAME_CASE(FCOPYSIGN_VL) 11626 NODE_NAME_CASE(SMIN_VL) 11627 NODE_NAME_CASE(SMAX_VL) 11628 NODE_NAME_CASE(UMIN_VL) 11629 NODE_NAME_CASE(UMAX_VL) 11630 NODE_NAME_CASE(FMINNUM_VL) 11631 NODE_NAME_CASE(FMAXNUM_VL) 11632 NODE_NAME_CASE(MULHS_VL) 11633 NODE_NAME_CASE(MULHU_VL) 11634 NODE_NAME_CASE(FP_TO_SINT_VL) 11635 NODE_NAME_CASE(FP_TO_UINT_VL) 11636 NODE_NAME_CASE(SINT_TO_FP_VL) 11637 NODE_NAME_CASE(UINT_TO_FP_VL) 11638 NODE_NAME_CASE(FP_EXTEND_VL) 11639 NODE_NAME_CASE(FP_ROUND_VL) 11640 NODE_NAME_CASE(VWMUL_VL) 11641 NODE_NAME_CASE(VWMULU_VL) 11642 NODE_NAME_CASE(VWMULSU_VL) 11643 NODE_NAME_CASE(VWADD_VL) 11644 NODE_NAME_CASE(VWADDU_VL) 11645 NODE_NAME_CASE(VWSUB_VL) 11646 NODE_NAME_CASE(VWSUBU_VL) 11647 NODE_NAME_CASE(VWADD_W_VL) 11648 NODE_NAME_CASE(VWADDU_W_VL) 11649 NODE_NAME_CASE(VWSUB_W_VL) 11650 NODE_NAME_CASE(VWSUBU_W_VL) 11651 NODE_NAME_CASE(SETCC_VL) 11652 NODE_NAME_CASE(VSELECT_VL) 11653 NODE_NAME_CASE(VP_MERGE_VL) 11654 NODE_NAME_CASE(VMAND_VL) 11655 NODE_NAME_CASE(VMOR_VL) 11656 NODE_NAME_CASE(VMXOR_VL) 11657 NODE_NAME_CASE(VMCLR_VL) 11658 NODE_NAME_CASE(VMSET_VL) 11659 NODE_NAME_CASE(VRGATHER_VX_VL) 11660 NODE_NAME_CASE(VRGATHER_VV_VL) 11661 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11662 NODE_NAME_CASE(VSEXT_VL) 11663 NODE_NAME_CASE(VZEXT_VL) 11664 NODE_NAME_CASE(VCPOP_VL) 11665 NODE_NAME_CASE(READ_CSR) 11666 NODE_NAME_CASE(WRITE_CSR) 11667 NODE_NAME_CASE(SWAP_CSR) 11668 } 11669 // clang-format on 11670 return nullptr; 11671 #undef NODE_NAME_CASE 11672 } 11673 11674 /// getConstraintType - Given a constraint letter, return the type of 11675 /// constraint it is for this target. 11676 RISCVTargetLowering::ConstraintType 11677 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11678 if (Constraint.size() == 1) { 11679 switch (Constraint[0]) { 11680 default: 11681 break; 11682 case 'f': 11683 return C_RegisterClass; 11684 case 'I': 11685 case 'J': 11686 case 'K': 11687 return C_Immediate; 11688 case 'A': 11689 return C_Memory; 11690 case 'S': // A symbolic address 11691 return C_Other; 11692 } 11693 } else { 11694 if (Constraint == "vr" || Constraint == "vm") 11695 return C_RegisterClass; 11696 } 11697 return TargetLowering::getConstraintType(Constraint); 11698 } 11699 11700 std::pair<unsigned, const TargetRegisterClass *> 11701 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11702 StringRef Constraint, 11703 MVT VT) const { 11704 // First, see if this is a constraint that directly corresponds to a 11705 // RISCV register class. 11706 if (Constraint.size() == 1) { 11707 switch (Constraint[0]) { 11708 case 'r': 11709 // TODO: Support fixed vectors up to XLen for P extension? 11710 if (VT.isVector()) 11711 break; 11712 return std::make_pair(0U, &RISCV::GPRRegClass); 11713 case 'f': 11714 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11715 return std::make_pair(0U, &RISCV::FPR16RegClass); 11716 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11717 return std::make_pair(0U, &RISCV::FPR32RegClass); 11718 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11719 return std::make_pair(0U, &RISCV::FPR64RegClass); 11720 break; 11721 default: 11722 break; 11723 } 11724 } else if (Constraint == "vr") { 11725 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11726 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11727 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11728 return std::make_pair(0U, RC); 11729 } 11730 } else if (Constraint == "vm") { 11731 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11732 return std::make_pair(0U, &RISCV::VMV0RegClass); 11733 } 11734 11735 // Clang will correctly decode the usage of register name aliases into their 11736 // official names. However, other frontends like `rustc` do not. This allows 11737 // users of these frontends to use the ABI names for registers in LLVM-style 11738 // register constraints. 11739 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11740 .Case("{zero}", RISCV::X0) 11741 .Case("{ra}", RISCV::X1) 11742 .Case("{sp}", RISCV::X2) 11743 .Case("{gp}", RISCV::X3) 11744 .Case("{tp}", RISCV::X4) 11745 .Case("{t0}", RISCV::X5) 11746 .Case("{t1}", RISCV::X6) 11747 .Case("{t2}", RISCV::X7) 11748 .Cases("{s0}", "{fp}", RISCV::X8) 11749 .Case("{s1}", RISCV::X9) 11750 .Case("{a0}", RISCV::X10) 11751 .Case("{a1}", RISCV::X11) 11752 .Case("{a2}", RISCV::X12) 11753 .Case("{a3}", RISCV::X13) 11754 .Case("{a4}", RISCV::X14) 11755 .Case("{a5}", RISCV::X15) 11756 .Case("{a6}", RISCV::X16) 11757 .Case("{a7}", RISCV::X17) 11758 .Case("{s2}", RISCV::X18) 11759 .Case("{s3}", RISCV::X19) 11760 .Case("{s4}", RISCV::X20) 11761 .Case("{s5}", RISCV::X21) 11762 .Case("{s6}", RISCV::X22) 11763 .Case("{s7}", RISCV::X23) 11764 .Case("{s8}", RISCV::X24) 11765 .Case("{s9}", RISCV::X25) 11766 .Case("{s10}", RISCV::X26) 11767 .Case("{s11}", RISCV::X27) 11768 .Case("{t3}", RISCV::X28) 11769 .Case("{t4}", RISCV::X29) 11770 .Case("{t5}", RISCV::X30) 11771 .Case("{t6}", RISCV::X31) 11772 .Default(RISCV::NoRegister); 11773 if (XRegFromAlias != RISCV::NoRegister) 11774 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11775 11776 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11777 // TableGen record rather than the AsmName to choose registers for InlineAsm 11778 // constraints, plus we want to match those names to the widest floating point 11779 // register type available, manually select floating point registers here. 11780 // 11781 // The second case is the ABI name of the register, so that frontends can also 11782 // use the ABI names in register constraint lists. 11783 if (Subtarget.hasStdExtF()) { 11784 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11785 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11786 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11787 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11788 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11789 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11790 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11791 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11792 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11793 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11794 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11795 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11796 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11797 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11798 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11799 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11800 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11801 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11802 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11803 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11804 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11805 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11806 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11807 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11808 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11809 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11810 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11811 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11812 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11813 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11814 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11815 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11816 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11817 .Default(RISCV::NoRegister); 11818 if (FReg != RISCV::NoRegister) { 11819 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11820 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11821 unsigned RegNo = FReg - RISCV::F0_F; 11822 unsigned DReg = RISCV::F0_D + RegNo; 11823 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11824 } 11825 if (VT == MVT::f32 || VT == MVT::Other) 11826 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11827 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11828 unsigned RegNo = FReg - RISCV::F0_F; 11829 unsigned HReg = RISCV::F0_H + RegNo; 11830 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11831 } 11832 } 11833 } 11834 11835 if (Subtarget.hasVInstructions()) { 11836 Register VReg = StringSwitch<Register>(Constraint.lower()) 11837 .Case("{v0}", RISCV::V0) 11838 .Case("{v1}", RISCV::V1) 11839 .Case("{v2}", RISCV::V2) 11840 .Case("{v3}", RISCV::V3) 11841 .Case("{v4}", RISCV::V4) 11842 .Case("{v5}", RISCV::V5) 11843 .Case("{v6}", RISCV::V6) 11844 .Case("{v7}", RISCV::V7) 11845 .Case("{v8}", RISCV::V8) 11846 .Case("{v9}", RISCV::V9) 11847 .Case("{v10}", RISCV::V10) 11848 .Case("{v11}", RISCV::V11) 11849 .Case("{v12}", RISCV::V12) 11850 .Case("{v13}", RISCV::V13) 11851 .Case("{v14}", RISCV::V14) 11852 .Case("{v15}", RISCV::V15) 11853 .Case("{v16}", RISCV::V16) 11854 .Case("{v17}", RISCV::V17) 11855 .Case("{v18}", RISCV::V18) 11856 .Case("{v19}", RISCV::V19) 11857 .Case("{v20}", RISCV::V20) 11858 .Case("{v21}", RISCV::V21) 11859 .Case("{v22}", RISCV::V22) 11860 .Case("{v23}", RISCV::V23) 11861 .Case("{v24}", RISCV::V24) 11862 .Case("{v25}", RISCV::V25) 11863 .Case("{v26}", RISCV::V26) 11864 .Case("{v27}", RISCV::V27) 11865 .Case("{v28}", RISCV::V28) 11866 .Case("{v29}", RISCV::V29) 11867 .Case("{v30}", RISCV::V30) 11868 .Case("{v31}", RISCV::V31) 11869 .Default(RISCV::NoRegister); 11870 if (VReg != RISCV::NoRegister) { 11871 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11872 return std::make_pair(VReg, &RISCV::VMRegClass); 11873 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11874 return std::make_pair(VReg, &RISCV::VRRegClass); 11875 for (const auto *RC : 11876 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11877 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11878 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11879 return std::make_pair(VReg, RC); 11880 } 11881 } 11882 } 11883 } 11884 11885 std::pair<Register, const TargetRegisterClass *> Res = 11886 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11887 11888 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11889 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11890 // Subtarget into account. 11891 if (Res.second == &RISCV::GPRF16RegClass || 11892 Res.second == &RISCV::GPRF32RegClass || 11893 Res.second == &RISCV::GPRF64RegClass) 11894 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11895 11896 return Res; 11897 } 11898 11899 unsigned 11900 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11901 // Currently only support length 1 constraints. 11902 if (ConstraintCode.size() == 1) { 11903 switch (ConstraintCode[0]) { 11904 case 'A': 11905 return InlineAsm::Constraint_A; 11906 default: 11907 break; 11908 } 11909 } 11910 11911 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11912 } 11913 11914 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11915 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11916 SelectionDAG &DAG) const { 11917 // Currently only support length 1 constraints. 11918 if (Constraint.length() == 1) { 11919 switch (Constraint[0]) { 11920 case 'I': 11921 // Validate & create a 12-bit signed immediate operand. 11922 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11923 uint64_t CVal = C->getSExtValue(); 11924 if (isInt<12>(CVal)) 11925 Ops.push_back( 11926 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11927 } 11928 return; 11929 case 'J': 11930 // Validate & create an integer zero operand. 11931 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11932 if (C->getZExtValue() == 0) 11933 Ops.push_back( 11934 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11935 return; 11936 case 'K': 11937 // Validate & create a 5-bit unsigned immediate operand. 11938 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11939 uint64_t CVal = C->getZExtValue(); 11940 if (isUInt<5>(CVal)) 11941 Ops.push_back( 11942 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11943 } 11944 return; 11945 case 'S': 11946 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11947 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11948 GA->getValueType(0))); 11949 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11950 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11951 BA->getValueType(0))); 11952 } 11953 return; 11954 default: 11955 break; 11956 } 11957 } 11958 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11959 } 11960 11961 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11962 Instruction *Inst, 11963 AtomicOrdering Ord) const { 11964 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11965 return Builder.CreateFence(Ord); 11966 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11967 return Builder.CreateFence(AtomicOrdering::Release); 11968 return nullptr; 11969 } 11970 11971 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11972 Instruction *Inst, 11973 AtomicOrdering Ord) const { 11974 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11975 return Builder.CreateFence(AtomicOrdering::Acquire); 11976 return nullptr; 11977 } 11978 11979 TargetLowering::AtomicExpansionKind 11980 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11981 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11982 // point operations can't be used in an lr/sc sequence without breaking the 11983 // forward-progress guarantee. 11984 if (AI->isFloatingPointOperation()) 11985 return AtomicExpansionKind::CmpXChg; 11986 11987 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11988 if (Size == 8 || Size == 16) 11989 return AtomicExpansionKind::MaskedIntrinsic; 11990 return AtomicExpansionKind::None; 11991 } 11992 11993 static Intrinsic::ID 11994 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11995 if (XLen == 32) { 11996 switch (BinOp) { 11997 default: 11998 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11999 case AtomicRMWInst::Xchg: 12000 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 12001 case AtomicRMWInst::Add: 12002 return Intrinsic::riscv_masked_atomicrmw_add_i32; 12003 case AtomicRMWInst::Sub: 12004 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 12005 case AtomicRMWInst::Nand: 12006 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 12007 case AtomicRMWInst::Max: 12008 return Intrinsic::riscv_masked_atomicrmw_max_i32; 12009 case AtomicRMWInst::Min: 12010 return Intrinsic::riscv_masked_atomicrmw_min_i32; 12011 case AtomicRMWInst::UMax: 12012 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 12013 case AtomicRMWInst::UMin: 12014 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 12015 } 12016 } 12017 12018 if (XLen == 64) { 12019 switch (BinOp) { 12020 default: 12021 llvm_unreachable("Unexpected AtomicRMW BinOp"); 12022 case AtomicRMWInst::Xchg: 12023 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 12024 case AtomicRMWInst::Add: 12025 return Intrinsic::riscv_masked_atomicrmw_add_i64; 12026 case AtomicRMWInst::Sub: 12027 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 12028 case AtomicRMWInst::Nand: 12029 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 12030 case AtomicRMWInst::Max: 12031 return Intrinsic::riscv_masked_atomicrmw_max_i64; 12032 case AtomicRMWInst::Min: 12033 return Intrinsic::riscv_masked_atomicrmw_min_i64; 12034 case AtomicRMWInst::UMax: 12035 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 12036 case AtomicRMWInst::UMin: 12037 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 12038 } 12039 } 12040 12041 llvm_unreachable("Unexpected XLen\n"); 12042 } 12043 12044 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 12045 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 12046 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 12047 unsigned XLen = Subtarget.getXLen(); 12048 Value *Ordering = 12049 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 12050 Type *Tys[] = {AlignedAddr->getType()}; 12051 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 12052 AI->getModule(), 12053 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 12054 12055 if (XLen == 64) { 12056 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 12057 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12058 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 12059 } 12060 12061 Value *Result; 12062 12063 // Must pass the shift amount needed to sign extend the loaded value prior 12064 // to performing a signed comparison for min/max. ShiftAmt is the number of 12065 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 12066 // is the number of bits to left+right shift the value in order to 12067 // sign-extend. 12068 if (AI->getOperation() == AtomicRMWInst::Min || 12069 AI->getOperation() == AtomicRMWInst::Max) { 12070 const DataLayout &DL = AI->getModule()->getDataLayout(); 12071 unsigned ValWidth = 12072 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 12073 Value *SextShamt = 12074 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 12075 Result = Builder.CreateCall(LrwOpScwLoop, 12076 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 12077 } else { 12078 Result = 12079 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 12080 } 12081 12082 if (XLen == 64) 12083 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12084 return Result; 12085 } 12086 12087 TargetLowering::AtomicExpansionKind 12088 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 12089 AtomicCmpXchgInst *CI) const { 12090 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 12091 if (Size == 8 || Size == 16) 12092 return AtomicExpansionKind::MaskedIntrinsic; 12093 return AtomicExpansionKind::None; 12094 } 12095 12096 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 12097 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 12098 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 12099 unsigned XLen = Subtarget.getXLen(); 12100 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 12101 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 12102 if (XLen == 64) { 12103 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 12104 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 12105 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12106 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 12107 } 12108 Type *Tys[] = {AlignedAddr->getType()}; 12109 Function *MaskedCmpXchg = 12110 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 12111 Value *Result = Builder.CreateCall( 12112 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 12113 if (XLen == 64) 12114 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12115 return Result; 12116 } 12117 12118 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 12119 EVT DataVT) const { 12120 return false; 12121 } 12122 12123 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 12124 EVT VT) const { 12125 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 12126 return false; 12127 12128 switch (FPVT.getSimpleVT().SimpleTy) { 12129 case MVT::f16: 12130 return Subtarget.hasStdExtZfh(); 12131 case MVT::f32: 12132 return Subtarget.hasStdExtF(); 12133 case MVT::f64: 12134 return Subtarget.hasStdExtD(); 12135 default: 12136 return false; 12137 } 12138 } 12139 12140 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 12141 // If we are using the small code model, we can reduce size of jump table 12142 // entry to 4 bytes. 12143 if (Subtarget.is64Bit() && !isPositionIndependent() && 12144 getTargetMachine().getCodeModel() == CodeModel::Small) { 12145 return MachineJumpTableInfo::EK_Custom32; 12146 } 12147 return TargetLowering::getJumpTableEncoding(); 12148 } 12149 12150 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 12151 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 12152 unsigned uid, MCContext &Ctx) const { 12153 assert(Subtarget.is64Bit() && !isPositionIndependent() && 12154 getTargetMachine().getCodeModel() == CodeModel::Small); 12155 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 12156 } 12157 12158 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const { 12159 // We define vscale to be VLEN/RVVBitsPerBlock. VLEN is always a power 12160 // of two >= 64, and RVVBitsPerBlock is 64. Thus, vscale must be 12161 // a power of two as well. 12162 // FIXME: This doesn't work for zve32, but that's already broken 12163 // elsewhere for the same reason. 12164 assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported"); 12165 assert(RISCV::RVVBitsPerBlock == 64 && "RVVBitsPerBlock changed, audit needed"); 12166 return true; 12167 } 12168 12169 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 12170 EVT VT) const { 12171 VT = VT.getScalarType(); 12172 12173 if (!VT.isSimple()) 12174 return false; 12175 12176 switch (VT.getSimpleVT().SimpleTy) { 12177 case MVT::f16: 12178 return Subtarget.hasStdExtZfh(); 12179 case MVT::f32: 12180 return Subtarget.hasStdExtF(); 12181 case MVT::f64: 12182 return Subtarget.hasStdExtD(); 12183 default: 12184 break; 12185 } 12186 12187 return false; 12188 } 12189 12190 Register RISCVTargetLowering::getExceptionPointerRegister( 12191 const Constant *PersonalityFn) const { 12192 return RISCV::X10; 12193 } 12194 12195 Register RISCVTargetLowering::getExceptionSelectorRegister( 12196 const Constant *PersonalityFn) const { 12197 return RISCV::X11; 12198 } 12199 12200 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12201 // Return false to suppress the unnecessary extensions if the LibCall 12202 // arguments or return value is f32 type for LP64 ABI. 12203 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12204 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12205 return false; 12206 12207 return true; 12208 } 12209 12210 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12211 if (Subtarget.is64Bit() && Type == MVT::i32) 12212 return true; 12213 12214 return IsSigned; 12215 } 12216 12217 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12218 SDValue C) const { 12219 // Check integral scalar types. 12220 if (VT.isScalarInteger()) { 12221 // Omit the optimization if the sub target has the M extension and the data 12222 // size exceeds XLen. 12223 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 12224 return false; 12225 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12226 // Break the MUL to a SLLI and an ADD/SUB. 12227 const APInt &Imm = ConstNode->getAPIntValue(); 12228 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12229 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12230 return true; 12231 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12232 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12233 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12234 (Imm - 8).isPowerOf2())) 12235 return true; 12236 // Omit the following optimization if the sub target has the M extension 12237 // and the data size >= XLen. 12238 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 12239 return false; 12240 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12241 // a pair of LUI/ADDI. 12242 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12243 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12244 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12245 (1 - ImmS).isPowerOf2()) 12246 return true; 12247 } 12248 } 12249 } 12250 12251 return false; 12252 } 12253 12254 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12255 SDValue ConstNode) const { 12256 // Let the DAGCombiner decide for vectors. 12257 EVT VT = AddNode.getValueType(); 12258 if (VT.isVector()) 12259 return true; 12260 12261 // Let the DAGCombiner decide for larger types. 12262 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12263 return true; 12264 12265 // It is worse if c1 is simm12 while c1*c2 is not. 12266 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12267 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12268 const APInt &C1 = C1Node->getAPIntValue(); 12269 const APInt &C2 = C2Node->getAPIntValue(); 12270 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12271 return false; 12272 12273 // Default to true and let the DAGCombiner decide. 12274 return true; 12275 } 12276 12277 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12278 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12279 bool *Fast) const { 12280 if (!VT.isVector()) { 12281 if (Fast) 12282 *Fast = false; 12283 return Subtarget.enableUnalignedScalarMem(); 12284 } 12285 12286 // All vector implementations must support element alignment 12287 EVT ElemVT = VT.getVectorElementType(); 12288 if (Alignment >= ElemVT.getStoreSize()) { 12289 if (Fast) 12290 *Fast = true; 12291 return true; 12292 } 12293 12294 return false; 12295 } 12296 12297 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12298 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12299 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12300 bool IsABIRegCopy = CC.has_value(); 12301 EVT ValueVT = Val.getValueType(); 12302 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12303 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12304 // and cast to f32. 12305 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12306 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12307 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12308 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12309 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12310 Parts[0] = Val; 12311 return true; 12312 } 12313 12314 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12315 LLVMContext &Context = *DAG.getContext(); 12316 EVT ValueEltVT = ValueVT.getVectorElementType(); 12317 EVT PartEltVT = PartVT.getVectorElementType(); 12318 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12319 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12320 if (PartVTBitSize % ValueVTBitSize == 0) { 12321 assert(PartVTBitSize >= ValueVTBitSize); 12322 // If the element types are different, bitcast to the same element type of 12323 // PartVT first. 12324 // Give an example here, we want copy a <vscale x 1 x i8> value to 12325 // <vscale x 4 x i16>. 12326 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12327 // subvector, then we can bitcast to <vscale x 4 x i16>. 12328 if (ValueEltVT != PartEltVT) { 12329 if (PartVTBitSize > ValueVTBitSize) { 12330 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12331 assert(Count != 0 && "The number of element should not be zero."); 12332 EVT SameEltTypeVT = 12333 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12334 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12335 DAG.getUNDEF(SameEltTypeVT), Val, 12336 DAG.getVectorIdxConstant(0, DL)); 12337 } 12338 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12339 } else { 12340 Val = 12341 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12342 Val, DAG.getVectorIdxConstant(0, DL)); 12343 } 12344 Parts[0] = Val; 12345 return true; 12346 } 12347 } 12348 return false; 12349 } 12350 12351 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12352 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12353 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12354 bool IsABIRegCopy = CC.has_value(); 12355 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12356 SDValue Val = Parts[0]; 12357 12358 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12359 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12360 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12361 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12362 return Val; 12363 } 12364 12365 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12366 LLVMContext &Context = *DAG.getContext(); 12367 SDValue Val = Parts[0]; 12368 EVT ValueEltVT = ValueVT.getVectorElementType(); 12369 EVT PartEltVT = PartVT.getVectorElementType(); 12370 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12371 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12372 if (PartVTBitSize % ValueVTBitSize == 0) { 12373 assert(PartVTBitSize >= ValueVTBitSize); 12374 EVT SameEltTypeVT = ValueVT; 12375 // If the element types are different, convert it to the same element type 12376 // of PartVT. 12377 // Give an example here, we want copy a <vscale x 1 x i8> value from 12378 // <vscale x 4 x i16>. 12379 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12380 // then we can extract <vscale x 1 x i8>. 12381 if (ValueEltVT != PartEltVT) { 12382 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12383 assert(Count != 0 && "The number of element should not be zero."); 12384 SameEltTypeVT = 12385 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12386 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12387 } 12388 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12389 DAG.getVectorIdxConstant(0, DL)); 12390 return Val; 12391 } 12392 } 12393 return SDValue(); 12394 } 12395 12396 SDValue 12397 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12398 SelectionDAG &DAG, 12399 SmallVectorImpl<SDNode *> &Created) const { 12400 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12401 if (isIntDivCheap(N->getValueType(0), Attr)) 12402 return SDValue(N, 0); // Lower SDIV as SDIV 12403 12404 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12405 "Unexpected divisor!"); 12406 12407 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12408 if (!Subtarget.hasStdExtZbt()) 12409 return SDValue(); 12410 12411 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12412 // Besides, more critical path instructions will be generated when dividing 12413 // by 2. So we keep using the original DAGs for these cases. 12414 unsigned Lg2 = Divisor.countTrailingZeros(); 12415 if (Lg2 == 1 || Lg2 >= 12) 12416 return SDValue(); 12417 12418 // fold (sdiv X, pow2) 12419 EVT VT = N->getValueType(0); 12420 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12421 return SDValue(); 12422 12423 SDLoc DL(N); 12424 SDValue N0 = N->getOperand(0); 12425 SDValue Zero = DAG.getConstant(0, DL, VT); 12426 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12427 12428 // Add (N0 < 0) ? Pow2 - 1 : 0; 12429 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12430 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12431 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12432 12433 Created.push_back(Cmp.getNode()); 12434 Created.push_back(Add.getNode()); 12435 Created.push_back(Sel.getNode()); 12436 12437 // Divide by pow2. 12438 SDValue SRA = 12439 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12440 12441 // If we're dividing by a positive value, we're done. Otherwise, we must 12442 // negate the result. 12443 if (Divisor.isNonNegative()) 12444 return SRA; 12445 12446 Created.push_back(SRA.getNode()); 12447 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12448 } 12449 12450 #define GET_REGISTER_MATCHER 12451 #include "RISCVGenAsmMatcher.inc" 12452 12453 Register 12454 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12455 const MachineFunction &MF) const { 12456 Register Reg = MatchRegisterAltName(RegName); 12457 if (Reg == RISCV::NoRegister) 12458 Reg = MatchRegisterName(RegName); 12459 if (Reg == RISCV::NoRegister) 12460 report_fatal_error( 12461 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12462 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12463 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12464 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12465 StringRef(RegName) + "\".")); 12466 return Reg; 12467 } 12468 12469 namespace llvm { 12470 namespace RISCVVIntrinsicsTable { 12471 12472 #define GET_RISCVVIntrinsicsTable_IMPL 12473 #include "RISCVGenSearchableTables.inc" 12474 12475 } // namespace RISCVVIntrinsicsTable 12476 12477 } // namespace llvm 12478