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 // Prefer to keep the load if it would require many instructions. 1178 // This uses the same threshold we use for constant pools but doesn't 1179 // check useConstantPoolForLargeInts. 1180 // TODO: Should we keep the load only when we're definitely going to emit a 1181 // constant pool? 1182 1183 RISCVMatInt::InstSeq Seq = 1184 RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits()); 1185 return Seq.size() <= Subtarget.getMaxBuildIntsCost(); 1186 } 1187 1188 bool RISCVTargetLowering:: 1189 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1190 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1191 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1192 SelectionDAG &DAG) const { 1193 // One interesting pattern that we'd want to form is 'bit extract': 1194 // ((1 >> Y) & 1) ==/!= 0 1195 // But we also need to be careful not to try to reverse that fold. 1196 1197 // Is this '((1 >> Y) & 1)'? 1198 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1199 return false; // Keep the 'bit extract' pattern. 1200 1201 // Will this be '((1 >> Y) & 1)' after the transform? 1202 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1203 return true; // Do form the 'bit extract' pattern. 1204 1205 // If 'X' is a constant, and we transform, then we will immediately 1206 // try to undo the fold, thus causing endless combine loop. 1207 // So only do the transform if X is not a constant. This matches the default 1208 // implementation of this function. 1209 return !XC; 1210 } 1211 1212 /// Check if sinking \p I's operands to I's basic block is profitable, because 1213 /// the operands can be folded into a target instruction, e.g. 1214 /// splats of scalars can fold into vector instructions. 1215 bool RISCVTargetLowering::shouldSinkOperands( 1216 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1217 using namespace llvm::PatternMatch; 1218 1219 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1220 return false; 1221 1222 auto IsSinker = [&](Instruction *I, int Operand) { 1223 switch (I->getOpcode()) { 1224 case Instruction::Add: 1225 case Instruction::Sub: 1226 case Instruction::Mul: 1227 case Instruction::And: 1228 case Instruction::Or: 1229 case Instruction::Xor: 1230 case Instruction::FAdd: 1231 case Instruction::FSub: 1232 case Instruction::FMul: 1233 case Instruction::FDiv: 1234 case Instruction::ICmp: 1235 case Instruction::FCmp: 1236 return true; 1237 case Instruction::Shl: 1238 case Instruction::LShr: 1239 case Instruction::AShr: 1240 case Instruction::UDiv: 1241 case Instruction::SDiv: 1242 case Instruction::URem: 1243 case Instruction::SRem: 1244 return Operand == 1; 1245 case Instruction::Call: 1246 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1247 switch (II->getIntrinsicID()) { 1248 case Intrinsic::fma: 1249 case Intrinsic::vp_fma: 1250 return Operand == 0 || Operand == 1; 1251 // FIXME: Our patterns can only match vx/vf instructions when the splat 1252 // it on the RHS, because TableGen doesn't recognize our VP operations 1253 // as commutative. 1254 case Intrinsic::vp_add: 1255 case Intrinsic::vp_mul: 1256 case Intrinsic::vp_and: 1257 case Intrinsic::vp_or: 1258 case Intrinsic::vp_xor: 1259 case Intrinsic::vp_fadd: 1260 case Intrinsic::vp_fmul: 1261 case Intrinsic::vp_shl: 1262 case Intrinsic::vp_lshr: 1263 case Intrinsic::vp_ashr: 1264 case Intrinsic::vp_udiv: 1265 case Intrinsic::vp_sdiv: 1266 case Intrinsic::vp_urem: 1267 case Intrinsic::vp_srem: 1268 return Operand == 1; 1269 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1270 // explicit patterns for both LHS and RHS (as 'vr' versions). 1271 case Intrinsic::vp_sub: 1272 case Intrinsic::vp_fsub: 1273 case Intrinsic::vp_fdiv: 1274 return Operand == 0 || Operand == 1; 1275 default: 1276 return false; 1277 } 1278 } 1279 return false; 1280 default: 1281 return false; 1282 } 1283 }; 1284 1285 for (auto OpIdx : enumerate(I->operands())) { 1286 if (!IsSinker(I, OpIdx.index())) 1287 continue; 1288 1289 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1290 // Make sure we are not already sinking this operand 1291 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1292 continue; 1293 1294 // We are looking for a splat that can be sunk. 1295 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1296 m_Undef(), m_ZeroMask()))) 1297 continue; 1298 1299 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1300 // and vector registers 1301 for (Use &U : Op->uses()) { 1302 Instruction *Insn = cast<Instruction>(U.getUser()); 1303 if (!IsSinker(Insn, U.getOperandNo())) 1304 return false; 1305 } 1306 1307 Ops.push_back(&Op->getOperandUse(0)); 1308 Ops.push_back(&OpIdx.value()); 1309 } 1310 return true; 1311 } 1312 1313 bool RISCVTargetLowering::isOffsetFoldingLegal( 1314 const GlobalAddressSDNode *GA) const { 1315 // In order to maximise the opportunity for common subexpression elimination, 1316 // keep a separate ADD node for the global address offset instead of folding 1317 // it in the global address node. Later peephole optimisations may choose to 1318 // fold it back in when profitable. 1319 return false; 1320 } 1321 1322 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1323 bool ForCodeSize) const { 1324 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1325 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1326 return false; 1327 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1328 return false; 1329 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1330 return false; 1331 return Imm.isZero(); 1332 } 1333 1334 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1335 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1336 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1337 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1338 } 1339 1340 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1341 CallingConv::ID CC, 1342 EVT VT) const { 1343 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1344 // We might still end up using a GPR but that will be decided based on ABI. 1345 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1346 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1347 return MVT::f32; 1348 1349 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1350 } 1351 1352 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1353 CallingConv::ID CC, 1354 EVT VT) const { 1355 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1356 // We might still end up using a GPR but that will be decided based on ABI. 1357 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1358 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1359 return 1; 1360 1361 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1362 } 1363 1364 // Changes the condition code and swaps operands if necessary, so the SetCC 1365 // operation matches one of the comparisons supported directly by branches 1366 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1367 // with 1/-1. 1368 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1369 ISD::CondCode &CC, SelectionDAG &DAG) { 1370 // Convert X > -1 to X >= 0. 1371 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1372 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1373 CC = ISD::SETGE; 1374 return; 1375 } 1376 // Convert X < 1 to 0 >= X. 1377 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1378 RHS = LHS; 1379 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1380 CC = ISD::SETGE; 1381 return; 1382 } 1383 1384 switch (CC) { 1385 default: 1386 break; 1387 case ISD::SETGT: 1388 case ISD::SETLE: 1389 case ISD::SETUGT: 1390 case ISD::SETULE: 1391 CC = ISD::getSetCCSwappedOperands(CC); 1392 std::swap(LHS, RHS); 1393 break; 1394 } 1395 } 1396 1397 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1398 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1399 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1400 if (VT.getVectorElementType() == MVT::i1) 1401 KnownSize *= 8; 1402 1403 switch (KnownSize) { 1404 default: 1405 llvm_unreachable("Invalid LMUL."); 1406 case 8: 1407 return RISCVII::VLMUL::LMUL_F8; 1408 case 16: 1409 return RISCVII::VLMUL::LMUL_F4; 1410 case 32: 1411 return RISCVII::VLMUL::LMUL_F2; 1412 case 64: 1413 return RISCVII::VLMUL::LMUL_1; 1414 case 128: 1415 return RISCVII::VLMUL::LMUL_2; 1416 case 256: 1417 return RISCVII::VLMUL::LMUL_4; 1418 case 512: 1419 return RISCVII::VLMUL::LMUL_8; 1420 } 1421 } 1422 1423 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1424 switch (LMul) { 1425 default: 1426 llvm_unreachable("Invalid LMUL."); 1427 case RISCVII::VLMUL::LMUL_F8: 1428 case RISCVII::VLMUL::LMUL_F4: 1429 case RISCVII::VLMUL::LMUL_F2: 1430 case RISCVII::VLMUL::LMUL_1: 1431 return RISCV::VRRegClassID; 1432 case RISCVII::VLMUL::LMUL_2: 1433 return RISCV::VRM2RegClassID; 1434 case RISCVII::VLMUL::LMUL_4: 1435 return RISCV::VRM4RegClassID; 1436 case RISCVII::VLMUL::LMUL_8: 1437 return RISCV::VRM8RegClassID; 1438 } 1439 } 1440 1441 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1442 RISCVII::VLMUL LMUL = getLMUL(VT); 1443 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1444 LMUL == RISCVII::VLMUL::LMUL_F4 || 1445 LMUL == RISCVII::VLMUL::LMUL_F2 || 1446 LMUL == RISCVII::VLMUL::LMUL_1) { 1447 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1448 "Unexpected subreg numbering"); 1449 return RISCV::sub_vrm1_0 + Index; 1450 } 1451 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1452 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1453 "Unexpected subreg numbering"); 1454 return RISCV::sub_vrm2_0 + Index; 1455 } 1456 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1457 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1458 "Unexpected subreg numbering"); 1459 return RISCV::sub_vrm4_0 + Index; 1460 } 1461 llvm_unreachable("Invalid vector type."); 1462 } 1463 1464 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1465 if (VT.getVectorElementType() == MVT::i1) 1466 return RISCV::VRRegClassID; 1467 return getRegClassIDForLMUL(getLMUL(VT)); 1468 } 1469 1470 // Attempt to decompose a subvector insert/extract between VecVT and 1471 // SubVecVT via subregister indices. Returns the subregister index that 1472 // can perform the subvector insert/extract with the given element index, as 1473 // well as the index corresponding to any leftover subvectors that must be 1474 // further inserted/extracted within the register class for SubVecVT. 1475 std::pair<unsigned, unsigned> 1476 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1477 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1478 const RISCVRegisterInfo *TRI) { 1479 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1480 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1481 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1482 "Register classes not ordered"); 1483 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1484 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1485 // Try to compose a subregister index that takes us from the incoming 1486 // LMUL>1 register class down to the outgoing one. At each step we half 1487 // the LMUL: 1488 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1489 // Note that this is not guaranteed to find a subregister index, such as 1490 // when we are extracting from one VR type to another. 1491 unsigned SubRegIdx = RISCV::NoSubRegister; 1492 for (const unsigned RCID : 1493 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1494 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1495 VecVT = VecVT.getHalfNumVectorElementsVT(); 1496 bool IsHi = 1497 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1498 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1499 getSubregIndexByMVT(VecVT, IsHi)); 1500 if (IsHi) 1501 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1502 } 1503 return {SubRegIdx, InsertExtractIdx}; 1504 } 1505 1506 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1507 // stores for those types. 1508 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1509 return !Subtarget.useRVVForFixedLengthVectors() || 1510 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1511 } 1512 1513 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1514 if (ScalarTy->isPointerTy()) 1515 return true; 1516 1517 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1518 ScalarTy->isIntegerTy(32)) 1519 return true; 1520 1521 if (ScalarTy->isIntegerTy(64)) 1522 return Subtarget.hasVInstructionsI64(); 1523 1524 if (ScalarTy->isHalfTy()) 1525 return Subtarget.hasVInstructionsF16(); 1526 if (ScalarTy->isFloatTy()) 1527 return Subtarget.hasVInstructionsF32(); 1528 if (ScalarTy->isDoubleTy()) 1529 return Subtarget.hasVInstructionsF64(); 1530 1531 return false; 1532 } 1533 1534 static SDValue getVLOperand(SDValue Op) { 1535 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1536 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1537 "Unexpected opcode"); 1538 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1539 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1540 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1541 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1542 if (!II) 1543 return SDValue(); 1544 return Op.getOperand(II->VLOperand + 1 + HasChain); 1545 } 1546 1547 static bool useRVVForFixedLengthVectorVT(MVT VT, 1548 const RISCVSubtarget &Subtarget) { 1549 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1550 if (!Subtarget.useRVVForFixedLengthVectors()) 1551 return false; 1552 1553 // We only support a set of vector types with a consistent maximum fixed size 1554 // across all supported vector element types to avoid legalization issues. 1555 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1556 // fixed-length vector type we support is 1024 bytes. 1557 if (VT.getFixedSizeInBits() > 1024 * 8) 1558 return false; 1559 1560 unsigned MinVLen = Subtarget.getRealMinVLen(); 1561 1562 MVT EltVT = VT.getVectorElementType(); 1563 1564 // Don't use RVV for vectors we cannot scalarize if required. 1565 switch (EltVT.SimpleTy) { 1566 // i1 is supported but has different rules. 1567 default: 1568 return false; 1569 case MVT::i1: 1570 // Masks can only use a single register. 1571 if (VT.getVectorNumElements() > MinVLen) 1572 return false; 1573 MinVLen /= 8; 1574 break; 1575 case MVT::i8: 1576 case MVT::i16: 1577 case MVT::i32: 1578 break; 1579 case MVT::i64: 1580 if (!Subtarget.hasVInstructionsI64()) 1581 return false; 1582 break; 1583 case MVT::f16: 1584 if (!Subtarget.hasVInstructionsF16()) 1585 return false; 1586 break; 1587 case MVT::f32: 1588 if (!Subtarget.hasVInstructionsF32()) 1589 return false; 1590 break; 1591 case MVT::f64: 1592 if (!Subtarget.hasVInstructionsF64()) 1593 return false; 1594 break; 1595 } 1596 1597 // Reject elements larger than ELEN. 1598 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1599 return false; 1600 1601 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1602 // Don't use RVV for types that don't fit. 1603 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1604 return false; 1605 1606 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1607 // the base fixed length RVV support in place. 1608 if (!VT.isPow2VectorType()) 1609 return false; 1610 1611 return true; 1612 } 1613 1614 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1615 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1616 } 1617 1618 // Return the largest legal scalable vector type that matches VT's element type. 1619 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1620 const RISCVSubtarget &Subtarget) { 1621 // This may be called before legal types are setup. 1622 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1623 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1624 "Expected legal fixed length vector!"); 1625 1626 unsigned MinVLen = Subtarget.getRealMinVLen(); 1627 unsigned MaxELen = Subtarget.getELEN(); 1628 1629 MVT EltVT = VT.getVectorElementType(); 1630 switch (EltVT.SimpleTy) { 1631 default: 1632 llvm_unreachable("unexpected element type for RVV container"); 1633 case MVT::i1: 1634 case MVT::i8: 1635 case MVT::i16: 1636 case MVT::i32: 1637 case MVT::i64: 1638 case MVT::f16: 1639 case MVT::f32: 1640 case MVT::f64: { 1641 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1642 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1643 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1644 unsigned NumElts = 1645 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1646 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1647 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1648 return MVT::getScalableVectorVT(EltVT, NumElts); 1649 } 1650 } 1651 } 1652 1653 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1654 const RISCVSubtarget &Subtarget) { 1655 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1656 Subtarget); 1657 } 1658 1659 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1660 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1661 } 1662 1663 // Grow V to consume an entire RVV register. 1664 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1665 const RISCVSubtarget &Subtarget) { 1666 assert(VT.isScalableVector() && 1667 "Expected to convert into a scalable vector!"); 1668 assert(V.getValueType().isFixedLengthVector() && 1669 "Expected a fixed length vector operand!"); 1670 SDLoc DL(V); 1671 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1672 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1673 } 1674 1675 // Shrink V so it's just big enough to maintain a VT's worth of data. 1676 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1677 const RISCVSubtarget &Subtarget) { 1678 assert(VT.isFixedLengthVector() && 1679 "Expected to convert into a fixed length vector!"); 1680 assert(V.getValueType().isScalableVector() && 1681 "Expected a scalable vector operand!"); 1682 SDLoc DL(V); 1683 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1684 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1685 } 1686 1687 /// Return the type of the mask type suitable for masking the provided 1688 /// vector type. This is simply an i1 element type vector of the same 1689 /// (possibly scalable) length. 1690 static MVT getMaskTypeFor(EVT VecVT) { 1691 assert(VecVT.isVector()); 1692 ElementCount EC = VecVT.getVectorElementCount(); 1693 return MVT::getVectorVT(MVT::i1, EC); 1694 } 1695 1696 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1697 /// vector length VL. . 1698 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1699 SelectionDAG &DAG) { 1700 MVT MaskVT = getMaskTypeFor(VecVT); 1701 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1702 } 1703 1704 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1705 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1706 // the vector type that it is contained in. 1707 static std::pair<SDValue, SDValue> 1708 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1709 const RISCVSubtarget &Subtarget) { 1710 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1711 MVT XLenVT = Subtarget.getXLenVT(); 1712 SDValue VL = VecVT.isFixedLengthVector() 1713 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1714 : DAG.getRegister(RISCV::X0, XLenVT); 1715 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1716 return {Mask, VL}; 1717 } 1718 1719 // As above but assuming the given type is a scalable vector type. 1720 static std::pair<SDValue, SDValue> 1721 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1722 const RISCVSubtarget &Subtarget) { 1723 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1724 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1725 } 1726 1727 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1728 // of either is (currently) supported. This can get us into an infinite loop 1729 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1730 // as a ..., etc. 1731 // Until either (or both) of these can reliably lower any node, reporting that 1732 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1733 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1734 // which is not desirable. 1735 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1736 EVT VT, unsigned DefinedValues) const { 1737 return false; 1738 } 1739 1740 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1741 const RISCVSubtarget &Subtarget) { 1742 // RISCV FP-to-int conversions saturate to the destination register size, but 1743 // don't produce 0 for nan. We can use a conversion instruction and fix the 1744 // nan case with a compare and a select. 1745 SDValue Src = Op.getOperand(0); 1746 1747 EVT DstVT = Op.getValueType(); 1748 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1749 1750 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1751 unsigned Opc; 1752 if (SatVT == DstVT) 1753 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1754 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1755 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1756 else 1757 return SDValue(); 1758 // FIXME: Support other SatVTs by clamping before or after the conversion. 1759 1760 SDLoc DL(Op); 1761 SDValue FpToInt = DAG.getNode( 1762 Opc, DL, DstVT, Src, 1763 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1764 1765 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1766 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1767 } 1768 1769 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1770 // and back. Taking care to avoid converting values that are nan or already 1771 // correct. 1772 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1773 // have FRM dependencies modeled yet. 1774 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1775 MVT VT = Op.getSimpleValueType(); 1776 assert(VT.isVector() && "Unexpected type"); 1777 1778 SDLoc DL(Op); 1779 1780 // Freeze the source since we are increasing the number of uses. 1781 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1782 1783 // Truncate to integer and convert back to FP. 1784 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1785 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1786 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1787 1788 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1789 1790 if (Op.getOpcode() == ISD::FCEIL) { 1791 // If the truncated value is the greater than or equal to the original 1792 // value, we've computed the ceil. Otherwise, we went the wrong way and 1793 // need to increase by 1. 1794 // FIXME: This should use a masked operation. Handle here or in isel? 1795 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1796 DAG.getConstantFP(1.0, DL, VT)); 1797 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1798 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1799 } else if (Op.getOpcode() == ISD::FFLOOR) { 1800 // If the truncated value is the less than or equal to the original value, 1801 // we've computed the floor. Otherwise, we went the wrong way and need to 1802 // decrease by 1. 1803 // FIXME: This should use a masked operation. Handle here or in isel? 1804 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1805 DAG.getConstantFP(1.0, DL, VT)); 1806 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1807 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1808 } 1809 1810 // Restore the original sign so that -0.0 is preserved. 1811 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1812 1813 // Determine the largest integer that can be represented exactly. This and 1814 // values larger than it don't have any fractional bits so don't need to 1815 // be converted. 1816 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1817 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1818 APFloat MaxVal = APFloat(FltSem); 1819 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1820 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1821 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1822 1823 // If abs(Src) was larger than MaxVal or nan, keep it. 1824 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1825 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1826 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1827 } 1828 1829 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1830 // This mode isn't supported in vector hardware on RISCV. But as long as we 1831 // aren't compiling with trapping math, we can emulate this with 1832 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1833 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1834 // dependencies modeled yet. 1835 // FIXME: Use masked operations to avoid final merge. 1836 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1837 MVT VT = Op.getSimpleValueType(); 1838 assert(VT.isVector() && "Unexpected type"); 1839 1840 SDLoc DL(Op); 1841 1842 // Freeze the source since we are increasing the number of uses. 1843 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1844 1845 // We do the conversion on the absolute value and fix the sign at the end. 1846 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1847 1848 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1849 bool Ignored; 1850 APFloat Point5Pred = APFloat(0.5f); 1851 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1852 Point5Pred.next(/*nextDown*/ true); 1853 1854 // Add the adjustment. 1855 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1856 DAG.getConstantFP(Point5Pred, DL, VT)); 1857 1858 // Truncate to integer and convert back to fp. 1859 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1860 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1861 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1862 1863 // Restore the original sign. 1864 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1865 1866 // Determine the largest integer that can be represented exactly. This and 1867 // values larger than it don't have any fractional bits so don't need to 1868 // be converted. 1869 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1870 APFloat MaxVal = APFloat(FltSem); 1871 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1872 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1873 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1874 1875 // If abs(Src) was larger than MaxVal or nan, keep it. 1876 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1877 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1878 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1879 } 1880 1881 struct VIDSequence { 1882 int64_t StepNumerator; 1883 unsigned StepDenominator; 1884 int64_t Addend; 1885 }; 1886 1887 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1888 // to the (non-zero) step S and start value X. This can be then lowered as the 1889 // RVV sequence (VID * S) + X, for example. 1890 // The step S is represented as an integer numerator divided by a positive 1891 // denominator. Note that the implementation currently only identifies 1892 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1893 // cannot detect 2/3, for example. 1894 // Note that this method will also match potentially unappealing index 1895 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1896 // determine whether this is worth generating code for. 1897 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1898 unsigned NumElts = Op.getNumOperands(); 1899 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1900 if (!Op.getValueType().isInteger()) 1901 return None; 1902 1903 Optional<unsigned> SeqStepDenom; 1904 Optional<int64_t> SeqStepNum, SeqAddend; 1905 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1906 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1907 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1908 // Assume undef elements match the sequence; we just have to be careful 1909 // when interpolating across them. 1910 if (Op.getOperand(Idx).isUndef()) 1911 continue; 1912 // The BUILD_VECTOR must be all constants. 1913 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1914 return None; 1915 1916 uint64_t Val = Op.getConstantOperandVal(Idx) & 1917 maskTrailingOnes<uint64_t>(EltSizeInBits); 1918 1919 if (PrevElt) { 1920 // Calculate the step since the last non-undef element, and ensure 1921 // it's consistent across the entire sequence. 1922 unsigned IdxDiff = Idx - PrevElt->second; 1923 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1924 1925 // A zero-value value difference means that we're somewhere in the middle 1926 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1927 // step change before evaluating the sequence. 1928 if (ValDiff == 0) 1929 continue; 1930 1931 int64_t Remainder = ValDiff % IdxDiff; 1932 // Normalize the step if it's greater than 1. 1933 if (Remainder != ValDiff) { 1934 // The difference must cleanly divide the element span. 1935 if (Remainder != 0) 1936 return None; 1937 ValDiff /= IdxDiff; 1938 IdxDiff = 1; 1939 } 1940 1941 if (!SeqStepNum) 1942 SeqStepNum = ValDiff; 1943 else if (ValDiff != SeqStepNum) 1944 return None; 1945 1946 if (!SeqStepDenom) 1947 SeqStepDenom = IdxDiff; 1948 else if (IdxDiff != *SeqStepDenom) 1949 return None; 1950 } 1951 1952 // Record this non-undef element for later. 1953 if (!PrevElt || PrevElt->first != Val) 1954 PrevElt = std::make_pair(Val, Idx); 1955 } 1956 1957 // We need to have logged a step for this to count as a legal index sequence. 1958 if (!SeqStepNum || !SeqStepDenom) 1959 return None; 1960 1961 // Loop back through the sequence and validate elements we might have skipped 1962 // while waiting for a valid step. While doing this, log any sequence addend. 1963 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1964 if (Op.getOperand(Idx).isUndef()) 1965 continue; 1966 uint64_t Val = Op.getConstantOperandVal(Idx) & 1967 maskTrailingOnes<uint64_t>(EltSizeInBits); 1968 uint64_t ExpectedVal = 1969 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1970 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1971 if (!SeqAddend) 1972 SeqAddend = Addend; 1973 else if (Addend != SeqAddend) 1974 return None; 1975 } 1976 1977 assert(SeqAddend && "Must have an addend if we have a step"); 1978 1979 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1980 } 1981 1982 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1983 // and lower it as a VRGATHER_VX_VL from the source vector. 1984 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1985 SelectionDAG &DAG, 1986 const RISCVSubtarget &Subtarget) { 1987 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1988 return SDValue(); 1989 SDValue Vec = SplatVal.getOperand(0); 1990 // Only perform this optimization on vectors of the same size for simplicity. 1991 // Don't perform this optimization for i1 vectors. 1992 // FIXME: Support i1 vectors, maybe by promoting to i8? 1993 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 1994 return SDValue(); 1995 SDValue Idx = SplatVal.getOperand(1); 1996 // The index must be a legal type. 1997 if (Idx.getValueType() != Subtarget.getXLenVT()) 1998 return SDValue(); 1999 2000 MVT ContainerVT = VT; 2001 if (VT.isFixedLengthVector()) { 2002 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2003 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2004 } 2005 2006 SDValue Mask, VL; 2007 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2008 2009 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2010 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 2011 2012 if (!VT.isFixedLengthVector()) 2013 return Gather; 2014 2015 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2016 } 2017 2018 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2019 const RISCVSubtarget &Subtarget) { 2020 MVT VT = Op.getSimpleValueType(); 2021 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2022 2023 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2024 2025 SDLoc DL(Op); 2026 SDValue Mask, VL; 2027 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2028 2029 MVT XLenVT = Subtarget.getXLenVT(); 2030 unsigned NumElts = Op.getNumOperands(); 2031 2032 if (VT.getVectorElementType() == MVT::i1) { 2033 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2034 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2035 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2036 } 2037 2038 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2039 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2040 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2041 } 2042 2043 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2044 // scalar integer chunks whose bit-width depends on the number of mask 2045 // bits and XLEN. 2046 // First, determine the most appropriate scalar integer type to use. This 2047 // is at most XLenVT, but may be shrunk to a smaller vector element type 2048 // according to the size of the final vector - use i8 chunks rather than 2049 // XLenVT if we're producing a v8i1. This results in more consistent 2050 // codegen across RV32 and RV64. 2051 unsigned NumViaIntegerBits = 2052 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2053 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2054 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2055 // If we have to use more than one INSERT_VECTOR_ELT then this 2056 // optimization is likely to increase code size; avoid peforming it in 2057 // such a case. We can use a load from a constant pool in this case. 2058 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2059 return SDValue(); 2060 // Now we can create our integer vector type. Note that it may be larger 2061 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2062 MVT IntegerViaVecVT = 2063 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2064 divideCeil(NumElts, NumViaIntegerBits)); 2065 2066 uint64_t Bits = 0; 2067 unsigned BitPos = 0, IntegerEltIdx = 0; 2068 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2069 2070 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2071 // Once we accumulate enough bits to fill our scalar type, insert into 2072 // our vector and clear our accumulated data. 2073 if (I != 0 && I % NumViaIntegerBits == 0) { 2074 if (NumViaIntegerBits <= 32) 2075 Bits = SignExtend64<32>(Bits); 2076 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2077 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2078 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2079 Bits = 0; 2080 BitPos = 0; 2081 IntegerEltIdx++; 2082 } 2083 SDValue V = Op.getOperand(I); 2084 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2085 Bits |= ((uint64_t)BitValue << BitPos); 2086 } 2087 2088 // Insert the (remaining) scalar value into position in our integer 2089 // vector type. 2090 if (NumViaIntegerBits <= 32) 2091 Bits = SignExtend64<32>(Bits); 2092 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2093 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2094 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2095 2096 if (NumElts < NumViaIntegerBits) { 2097 // If we're producing a smaller vector than our minimum legal integer 2098 // type, bitcast to the equivalent (known-legal) mask type, and extract 2099 // our final mask. 2100 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2101 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2102 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2103 DAG.getConstant(0, DL, XLenVT)); 2104 } else { 2105 // Else we must have produced an integer type with the same size as the 2106 // mask type; bitcast for the final result. 2107 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2108 Vec = DAG.getBitcast(VT, Vec); 2109 } 2110 2111 return Vec; 2112 } 2113 2114 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2115 // vector type, we have a legal equivalently-sized i8 type, so we can use 2116 // that. 2117 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2118 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2119 2120 SDValue WideVec; 2121 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2122 // For a splat, perform a scalar truncate before creating the wider 2123 // vector. 2124 assert(Splat.getValueType() == XLenVT && 2125 "Unexpected type for i1 splat value"); 2126 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2127 DAG.getConstant(1, DL, XLenVT)); 2128 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2129 } else { 2130 SmallVector<SDValue, 8> Ops(Op->op_values()); 2131 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2132 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2133 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2134 } 2135 2136 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2137 } 2138 2139 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2140 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2141 return Gather; 2142 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2143 : RISCVISD::VMV_V_X_VL; 2144 Splat = 2145 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2146 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2147 } 2148 2149 // Try and match index sequences, which we can lower to the vid instruction 2150 // with optional modifications. An all-undef vector is matched by 2151 // getSplatValue, above. 2152 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2153 int64_t StepNumerator = SimpleVID->StepNumerator; 2154 unsigned StepDenominator = SimpleVID->StepDenominator; 2155 int64_t Addend = SimpleVID->Addend; 2156 2157 assert(StepNumerator != 0 && "Invalid step"); 2158 bool Negate = false; 2159 int64_t SplatStepVal = StepNumerator; 2160 unsigned StepOpcode = ISD::MUL; 2161 if (StepNumerator != 1) { 2162 if (isPowerOf2_64(std::abs(StepNumerator))) { 2163 Negate = StepNumerator < 0; 2164 StepOpcode = ISD::SHL; 2165 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2166 } 2167 } 2168 2169 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2170 // threshold since it's the immediate value many RVV instructions accept. 2171 // There is no vmul.vi instruction so ensure multiply constant can fit in 2172 // a single addi instruction. 2173 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2174 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2175 isPowerOf2_32(StepDenominator) && 2176 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2177 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2178 // Convert right out of the scalable type so we can use standard ISD 2179 // nodes for the rest of the computation. If we used scalable types with 2180 // these, we'd lose the fixed-length vector info and generate worse 2181 // vsetvli code. 2182 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2183 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2184 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2185 SDValue SplatStep = DAG.getSplatBuildVector( 2186 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2187 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2188 } 2189 if (StepDenominator != 1) { 2190 SDValue SplatStep = DAG.getSplatBuildVector( 2191 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2192 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2193 } 2194 if (Addend != 0 || Negate) { 2195 SDValue SplatAddend = DAG.getSplatBuildVector( 2196 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2197 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2198 } 2199 return VID; 2200 } 2201 } 2202 2203 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2204 // when re-interpreted as a vector with a larger element type. For example, 2205 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2206 // could be instead splat as 2207 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2208 // TODO: This optimization could also work on non-constant splats, but it 2209 // would require bit-manipulation instructions to construct the splat value. 2210 SmallVector<SDValue> Sequence; 2211 unsigned EltBitSize = VT.getScalarSizeInBits(); 2212 const auto *BV = cast<BuildVectorSDNode>(Op); 2213 if (VT.isInteger() && EltBitSize < 64 && 2214 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2215 BV->getRepeatedSequence(Sequence) && 2216 (Sequence.size() * EltBitSize) <= 64) { 2217 unsigned SeqLen = Sequence.size(); 2218 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2219 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2220 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2221 ViaIntVT == MVT::i64) && 2222 "Unexpected sequence type"); 2223 2224 unsigned EltIdx = 0; 2225 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2226 uint64_t SplatValue = 0; 2227 // Construct the amalgamated value which can be splatted as this larger 2228 // vector type. 2229 for (const auto &SeqV : Sequence) { 2230 if (!SeqV.isUndef()) 2231 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2232 << (EltIdx * EltBitSize)); 2233 EltIdx++; 2234 } 2235 2236 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2237 // achieve better constant materializion. 2238 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2239 SplatValue = SignExtend64<32>(SplatValue); 2240 2241 // Since we can't introduce illegal i64 types at this stage, we can only 2242 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2243 // way we can use RVV instructions to splat. 2244 assert((ViaIntVT.bitsLE(XLenVT) || 2245 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2246 "Unexpected bitcast sequence"); 2247 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2248 SDValue ViaVL = 2249 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2250 MVT ViaContainerVT = 2251 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2252 SDValue Splat = 2253 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2254 DAG.getUNDEF(ViaContainerVT), 2255 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2256 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2257 return DAG.getBitcast(VT, Splat); 2258 } 2259 } 2260 2261 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2262 // which constitute a large proportion of the elements. In such cases we can 2263 // splat a vector with the dominant element and make up the shortfall with 2264 // INSERT_VECTOR_ELTs. 2265 // Note that this includes vectors of 2 elements by association. The 2266 // upper-most element is the "dominant" one, allowing us to use a splat to 2267 // "insert" the upper element, and an insert of the lower element at position 2268 // 0, which improves codegen. 2269 SDValue DominantValue; 2270 unsigned MostCommonCount = 0; 2271 DenseMap<SDValue, unsigned> ValueCounts; 2272 unsigned NumUndefElts = 2273 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2274 2275 // Track the number of scalar loads we know we'd be inserting, estimated as 2276 // any non-zero floating-point constant. Other kinds of element are either 2277 // already in registers or are materialized on demand. The threshold at which 2278 // a vector load is more desirable than several scalar materializion and 2279 // vector-insertion instructions is not known. 2280 unsigned NumScalarLoads = 0; 2281 2282 for (SDValue V : Op->op_values()) { 2283 if (V.isUndef()) 2284 continue; 2285 2286 ValueCounts.insert(std::make_pair(V, 0)); 2287 unsigned &Count = ValueCounts[V]; 2288 2289 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2290 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2291 2292 // Is this value dominant? In case of a tie, prefer the highest element as 2293 // it's cheaper to insert near the beginning of a vector than it is at the 2294 // end. 2295 if (++Count >= MostCommonCount) { 2296 DominantValue = V; 2297 MostCommonCount = Count; 2298 } 2299 } 2300 2301 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2302 unsigned NumDefElts = NumElts - NumUndefElts; 2303 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2304 2305 // Don't perform this optimization when optimizing for size, since 2306 // materializing elements and inserting them tends to cause code bloat. 2307 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2308 ((MostCommonCount > DominantValueCountThreshold) || 2309 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2310 // Start by splatting the most common element. 2311 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2312 2313 DenseSet<SDValue> Processed{DominantValue}; 2314 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2315 for (const auto &OpIdx : enumerate(Op->ops())) { 2316 const SDValue &V = OpIdx.value(); 2317 if (V.isUndef() || !Processed.insert(V).second) 2318 continue; 2319 if (ValueCounts[V] == 1) { 2320 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2321 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2322 } else { 2323 // Blend in all instances of this value using a VSELECT, using a 2324 // mask where each bit signals whether that element is the one 2325 // we're after. 2326 SmallVector<SDValue> Ops; 2327 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2328 return DAG.getConstant(V == V1, DL, XLenVT); 2329 }); 2330 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2331 DAG.getBuildVector(SelMaskTy, DL, Ops), 2332 DAG.getSplatBuildVector(VT, DL, V), Vec); 2333 } 2334 } 2335 2336 return Vec; 2337 } 2338 2339 return SDValue(); 2340 } 2341 2342 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2343 SDValue Lo, SDValue Hi, SDValue VL, 2344 SelectionDAG &DAG) { 2345 if (!Passthru) 2346 Passthru = DAG.getUNDEF(VT); 2347 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2348 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2349 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2350 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2351 // node in order to try and match RVV vector/scalar instructions. 2352 if ((LoC >> 31) == HiC) 2353 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2354 2355 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2356 // vmv.v.x whose EEW = 32 to lower it. 2357 auto *Const = dyn_cast<ConstantSDNode>(VL); 2358 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2359 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2360 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2361 // access the subtarget here now. 2362 auto InterVec = DAG.getNode( 2363 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2364 DAG.getRegister(RISCV::X0, MVT::i32)); 2365 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2366 } 2367 } 2368 2369 // Fall back to a stack store and stride x0 vector load. 2370 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2371 Hi, VL); 2372 } 2373 2374 // Called by type legalization to handle splat of i64 on RV32. 2375 // FIXME: We can optimize this when the type has sign or zero bits in one 2376 // of the halves. 2377 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2378 SDValue Scalar, SDValue VL, 2379 SelectionDAG &DAG) { 2380 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2381 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2382 DAG.getConstant(0, DL, MVT::i32)); 2383 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2384 DAG.getConstant(1, DL, MVT::i32)); 2385 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2386 } 2387 2388 // This function lowers a splat of a scalar operand Splat with the vector 2389 // length VL. It ensures the final sequence is type legal, which is useful when 2390 // lowering a splat after type legalization. 2391 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2392 MVT VT, SDLoc DL, SelectionDAG &DAG, 2393 const RISCVSubtarget &Subtarget) { 2394 bool HasPassthru = Passthru && !Passthru.isUndef(); 2395 if (!HasPassthru && !Passthru) 2396 Passthru = DAG.getUNDEF(VT); 2397 if (VT.isFloatingPoint()) { 2398 // If VL is 1, we could use vfmv.s.f. 2399 if (isOneConstant(VL)) 2400 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2401 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2402 } 2403 2404 MVT XLenVT = Subtarget.getXLenVT(); 2405 2406 // Simplest case is that the operand needs to be promoted to XLenVT. 2407 if (Scalar.getValueType().bitsLE(XLenVT)) { 2408 // If the operand is a constant, sign extend to increase our chances 2409 // of being able to use a .vi instruction. ANY_EXTEND would become a 2410 // a zero extend and the simm5 check in isel would fail. 2411 // FIXME: Should we ignore the upper bits in isel instead? 2412 unsigned ExtOpc = 2413 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2414 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2415 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2416 // If VL is 1 and the scalar value won't benefit from immediate, we could 2417 // use vmv.s.x. 2418 if (isOneConstant(VL) && 2419 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2420 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2421 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2422 } 2423 2424 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2425 "Unexpected scalar for splat lowering!"); 2426 2427 if (isOneConstant(VL) && isNullConstant(Scalar)) 2428 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2429 DAG.getConstant(0, DL, XLenVT), VL); 2430 2431 // Otherwise use the more complicated splatting algorithm. 2432 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2433 } 2434 2435 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2436 const RISCVSubtarget &Subtarget) { 2437 // We need to be able to widen elements to the next larger integer type. 2438 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2439 return false; 2440 2441 int Size = Mask.size(); 2442 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2443 2444 int Srcs[] = {-1, -1}; 2445 for (int i = 0; i != Size; ++i) { 2446 // Ignore undef elements. 2447 if (Mask[i] < 0) 2448 continue; 2449 2450 // Is this an even or odd element. 2451 int Pol = i % 2; 2452 2453 // Ensure we consistently use the same source for this element polarity. 2454 int Src = Mask[i] / Size; 2455 if (Srcs[Pol] < 0) 2456 Srcs[Pol] = Src; 2457 if (Srcs[Pol] != Src) 2458 return false; 2459 2460 // Make sure the element within the source is appropriate for this element 2461 // in the destination. 2462 int Elt = Mask[i] % Size; 2463 if (Elt != i / 2) 2464 return false; 2465 } 2466 2467 // We need to find a source for each polarity and they can't be the same. 2468 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2469 return false; 2470 2471 // Swap the sources if the second source was in the even polarity. 2472 SwapSources = Srcs[0] > Srcs[1]; 2473 2474 return true; 2475 } 2476 2477 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2478 /// and then extract the original number of elements from the rotated result. 2479 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2480 /// returned rotation amount is for a rotate right, where elements move from 2481 /// higher elements to lower elements. \p LoSrc indicates the first source 2482 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2483 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2484 /// 0 or 1 if a rotation is found. 2485 /// 2486 /// NOTE: We talk about rotate to the right which matches how bit shift and 2487 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2488 /// and the table below write vectors with the lowest elements on the left. 2489 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2490 int Size = Mask.size(); 2491 2492 // We need to detect various ways of spelling a rotation: 2493 // [11, 12, 13, 14, 15, 0, 1, 2] 2494 // [-1, 12, 13, 14, -1, -1, 1, -1] 2495 // [-1, -1, -1, -1, -1, -1, 1, 2] 2496 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2497 // [-1, 4, 5, 6, -1, -1, 9, -1] 2498 // [-1, 4, 5, 6, -1, -1, -1, -1] 2499 int Rotation = 0; 2500 LoSrc = -1; 2501 HiSrc = -1; 2502 for (int i = 0; i != Size; ++i) { 2503 int M = Mask[i]; 2504 if (M < 0) 2505 continue; 2506 2507 // Determine where a rotate vector would have started. 2508 int StartIdx = i - (M % Size); 2509 // The identity rotation isn't interesting, stop. 2510 if (StartIdx == 0) 2511 return -1; 2512 2513 // If we found the tail of a vector the rotation must be the missing 2514 // front. If we found the head of a vector, it must be how much of the 2515 // head. 2516 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2517 2518 if (Rotation == 0) 2519 Rotation = CandidateRotation; 2520 else if (Rotation != CandidateRotation) 2521 // The rotations don't match, so we can't match this mask. 2522 return -1; 2523 2524 // Compute which value this mask is pointing at. 2525 int MaskSrc = M < Size ? 0 : 1; 2526 2527 // Compute which of the two target values this index should be assigned to. 2528 // This reflects whether the high elements are remaining or the low elemnts 2529 // are remaining. 2530 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2531 2532 // Either set up this value if we've not encountered it before, or check 2533 // that it remains consistent. 2534 if (TargetSrc < 0) 2535 TargetSrc = MaskSrc; 2536 else if (TargetSrc != MaskSrc) 2537 // This may be a rotation, but it pulls from the inputs in some 2538 // unsupported interleaving. 2539 return -1; 2540 } 2541 2542 // Check that we successfully analyzed the mask, and normalize the results. 2543 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2544 assert((LoSrc >= 0 || HiSrc >= 0) && 2545 "Failed to find a rotated input vector!"); 2546 2547 return Rotation; 2548 } 2549 2550 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2551 const RISCVSubtarget &Subtarget) { 2552 SDValue V1 = Op.getOperand(0); 2553 SDValue V2 = Op.getOperand(1); 2554 SDLoc DL(Op); 2555 MVT XLenVT = Subtarget.getXLenVT(); 2556 MVT VT = Op.getSimpleValueType(); 2557 unsigned NumElts = VT.getVectorNumElements(); 2558 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2559 2560 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2561 2562 SDValue TrueMask, VL; 2563 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2564 2565 if (SVN->isSplat()) { 2566 const int Lane = SVN->getSplatIndex(); 2567 if (Lane >= 0) { 2568 MVT SVT = VT.getVectorElementType(); 2569 2570 // Turn splatted vector load into a strided load with an X0 stride. 2571 SDValue V = V1; 2572 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2573 // with undef. 2574 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2575 int Offset = Lane; 2576 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2577 int OpElements = 2578 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2579 V = V.getOperand(Offset / OpElements); 2580 Offset %= OpElements; 2581 } 2582 2583 // We need to ensure the load isn't atomic or volatile. 2584 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2585 auto *Ld = cast<LoadSDNode>(V); 2586 Offset *= SVT.getStoreSize(); 2587 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2588 TypeSize::Fixed(Offset), DL); 2589 2590 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2591 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2592 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2593 SDValue IntID = 2594 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2595 SDValue Ops[] = {Ld->getChain(), 2596 IntID, 2597 DAG.getUNDEF(ContainerVT), 2598 NewAddr, 2599 DAG.getRegister(RISCV::X0, XLenVT), 2600 VL}; 2601 SDValue NewLoad = DAG.getMemIntrinsicNode( 2602 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2603 DAG.getMachineFunction().getMachineMemOperand( 2604 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2605 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2606 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2607 } 2608 2609 // Otherwise use a scalar load and splat. This will give the best 2610 // opportunity to fold a splat into the operation. ISel can turn it into 2611 // the x0 strided load if we aren't able to fold away the select. 2612 if (SVT.isFloatingPoint()) 2613 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2614 Ld->getPointerInfo().getWithOffset(Offset), 2615 Ld->getOriginalAlign(), 2616 Ld->getMemOperand()->getFlags()); 2617 else 2618 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2619 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2620 Ld->getOriginalAlign(), 2621 Ld->getMemOperand()->getFlags()); 2622 DAG.makeEquivalentMemoryOrdering(Ld, V); 2623 2624 unsigned Opc = 2625 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2626 SDValue Splat = 2627 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2628 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2629 } 2630 2631 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2632 assert(Lane < (int)NumElts && "Unexpected lane!"); 2633 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2634 V1, DAG.getConstant(Lane, DL, XLenVT), 2635 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2636 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2637 } 2638 } 2639 2640 ArrayRef<int> Mask = SVN->getMask(); 2641 2642 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2643 // be undef which can be handled with a single SLIDEDOWN/UP. 2644 int LoSrc, HiSrc; 2645 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2646 if (Rotation > 0) { 2647 SDValue LoV, HiV; 2648 if (LoSrc >= 0) { 2649 LoV = LoSrc == 0 ? V1 : V2; 2650 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2651 } 2652 if (HiSrc >= 0) { 2653 HiV = HiSrc == 0 ? V1 : V2; 2654 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2655 } 2656 2657 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2658 // to slide LoV up by (NumElts - Rotation). 2659 unsigned InvRotate = NumElts - Rotation; 2660 2661 SDValue Res = DAG.getUNDEF(ContainerVT); 2662 if (HiV) { 2663 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2664 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2665 // causes multiple vsetvlis in some test cases such as lowering 2666 // reduce.mul 2667 SDValue DownVL = VL; 2668 if (LoV) 2669 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2670 Res = 2671 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2672 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2673 } 2674 if (LoV) 2675 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2676 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2677 2678 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2679 } 2680 2681 // Detect an interleave shuffle and lower to 2682 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2683 bool SwapSources; 2684 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2685 // Swap sources if needed. 2686 if (SwapSources) 2687 std::swap(V1, V2); 2688 2689 // Extract the lower half of the vectors. 2690 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2691 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2692 DAG.getConstant(0, DL, XLenVT)); 2693 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2694 DAG.getConstant(0, DL, XLenVT)); 2695 2696 // Double the element width and halve the number of elements in an int type. 2697 unsigned EltBits = VT.getScalarSizeInBits(); 2698 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2699 MVT WideIntVT = 2700 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2701 // Convert this to a scalable vector. We need to base this on the 2702 // destination size to ensure there's always a type with a smaller LMUL. 2703 MVT WideIntContainerVT = 2704 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2705 2706 // Convert sources to scalable vectors with the same element count as the 2707 // larger type. 2708 MVT HalfContainerVT = MVT::getVectorVT( 2709 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2710 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2711 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2712 2713 // Cast sources to integer. 2714 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2715 MVT IntHalfVT = 2716 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2717 V1 = DAG.getBitcast(IntHalfVT, V1); 2718 V2 = DAG.getBitcast(IntHalfVT, V2); 2719 2720 // Freeze V2 since we use it twice and we need to be sure that the add and 2721 // multiply see the same value. 2722 V2 = DAG.getFreeze(V2); 2723 2724 // Recreate TrueMask using the widened type's element count. 2725 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2726 2727 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2728 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2729 V2, TrueMask, VL); 2730 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2731 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2732 DAG.getUNDEF(IntHalfVT), 2733 DAG.getAllOnesConstant(DL, XLenVT)); 2734 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2735 V2, Multiplier, TrueMask, VL); 2736 // Add the new copies to our previous addition giving us 2^eltbits copies of 2737 // V2. This is equivalent to shifting V2 left by eltbits. This should 2738 // combine with the vwmulu.vv above to form vwmaccu.vv. 2739 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2740 TrueMask, VL); 2741 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2742 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2743 // vector VT. 2744 ContainerVT = 2745 MVT::getVectorVT(VT.getVectorElementType(), 2746 WideIntContainerVT.getVectorElementCount() * 2); 2747 Add = DAG.getBitcast(ContainerVT, Add); 2748 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2749 } 2750 2751 // Detect shuffles which can be re-expressed as vector selects; these are 2752 // shuffles in which each element in the destination is taken from an element 2753 // at the corresponding index in either source vectors. 2754 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2755 int MaskIndex = MaskIdx.value(); 2756 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2757 }); 2758 2759 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2760 2761 SmallVector<SDValue> MaskVals; 2762 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2763 // merged with a second vrgather. 2764 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2765 2766 // By default we preserve the original operand order, and use a mask to 2767 // select LHS as true and RHS as false. However, since RVV vector selects may 2768 // feature splats but only on the LHS, we may choose to invert our mask and 2769 // instead select between RHS and LHS. 2770 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2771 bool InvertMask = IsSelect == SwapOps; 2772 2773 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2774 // half. 2775 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2776 2777 // Now construct the mask that will be used by the vselect or blended 2778 // vrgather operation. For vrgathers, construct the appropriate indices into 2779 // each vector. 2780 for (int MaskIndex : Mask) { 2781 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2782 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2783 if (!IsSelect) { 2784 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2785 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2786 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2787 : DAG.getUNDEF(XLenVT)); 2788 GatherIndicesRHS.push_back( 2789 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2790 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2791 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2792 ++LHSIndexCounts[MaskIndex]; 2793 if (!IsLHSOrUndefIndex) 2794 ++RHSIndexCounts[MaskIndex - NumElts]; 2795 } 2796 } 2797 2798 if (SwapOps) { 2799 std::swap(V1, V2); 2800 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2801 } 2802 2803 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2804 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2805 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2806 2807 if (IsSelect) 2808 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2809 2810 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2811 // On such a large vector we're unable to use i8 as the index type. 2812 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2813 // may involve vector splitting if we're already at LMUL=8, or our 2814 // user-supplied maximum fixed-length LMUL. 2815 return SDValue(); 2816 } 2817 2818 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2819 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2820 MVT IndexVT = VT.changeTypeToInteger(); 2821 // Since we can't introduce illegal index types at this stage, use i16 and 2822 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2823 // than XLenVT. 2824 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2825 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2826 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2827 } 2828 2829 MVT IndexContainerVT = 2830 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2831 2832 SDValue Gather; 2833 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2834 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2835 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2836 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2837 Subtarget); 2838 } else { 2839 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2840 // If only one index is used, we can use a "splat" vrgather. 2841 // TODO: We can splat the most-common index and fix-up any stragglers, if 2842 // that's beneficial. 2843 if (LHSIndexCounts.size() == 1) { 2844 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2845 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2846 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2847 DAG.getUNDEF(ContainerVT), VL); 2848 } else { 2849 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2850 LHSIndices = 2851 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2852 2853 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2854 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2855 } 2856 } 2857 2858 // If a second vector operand is used by this shuffle, blend it in with an 2859 // additional vrgather. 2860 if (!V2.isUndef()) { 2861 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2862 2863 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2864 SelectMask = 2865 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2866 2867 // If only one index is used, we can use a "splat" vrgather. 2868 // TODO: We can splat the most-common index and fix-up any stragglers, if 2869 // that's beneficial. 2870 if (RHSIndexCounts.size() == 1) { 2871 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2872 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2873 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2874 Gather, VL); 2875 } else { 2876 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2877 RHSIndices = 2878 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2879 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2880 SelectMask, Gather, VL); 2881 } 2882 } 2883 2884 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2885 } 2886 2887 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2888 // Support splats for any type. These should type legalize well. 2889 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2890 return true; 2891 2892 // Only support legal VTs for other shuffles for now. 2893 if (!isTypeLegal(VT)) 2894 return false; 2895 2896 MVT SVT = VT.getSimpleVT(); 2897 2898 bool SwapSources; 2899 int LoSrc, HiSrc; 2900 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2901 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2902 } 2903 2904 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2905 // the exponent. 2906 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2907 MVT VT = Op.getSimpleValueType(); 2908 unsigned EltSize = VT.getScalarSizeInBits(); 2909 SDValue Src = Op.getOperand(0); 2910 SDLoc DL(Op); 2911 2912 // We need a FP type that can represent the value. 2913 // TODO: Use f16 for i8 when possible? 2914 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2915 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2916 2917 // Legal types should have been checked in the RISCVTargetLowering 2918 // constructor. 2919 // TODO: Splitting may make sense in some cases. 2920 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2921 "Expected legal float type!"); 2922 2923 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2924 // The trailing zero count is equal to log2 of this single bit value. 2925 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2926 SDValue Neg = 2927 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2928 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2929 } 2930 2931 // We have a legal FP type, convert to it. 2932 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2933 // Bitcast to integer and shift the exponent to the LSB. 2934 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2935 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2936 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2937 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2938 DAG.getConstant(ShiftAmt, DL, IntVT)); 2939 // Truncate back to original type to allow vnsrl. 2940 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2941 // The exponent contains log2 of the value in biased form. 2942 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2943 2944 // For trailing zeros, we just need to subtract the bias. 2945 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2946 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2947 DAG.getConstant(ExponentBias, DL, VT)); 2948 2949 // For leading zeros, we need to remove the bias and convert from log2 to 2950 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2951 unsigned Adjust = ExponentBias + (EltSize - 1); 2952 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2953 } 2954 2955 // While RVV has alignment restrictions, we should always be able to load as a 2956 // legal equivalently-sized byte-typed vector instead. This method is 2957 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2958 // the load is already correctly-aligned, it returns SDValue(). 2959 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2960 SelectionDAG &DAG) const { 2961 auto *Load = cast<LoadSDNode>(Op); 2962 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2963 2964 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2965 Load->getMemoryVT(), 2966 *Load->getMemOperand())) 2967 return SDValue(); 2968 2969 SDLoc DL(Op); 2970 MVT VT = Op.getSimpleValueType(); 2971 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2972 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2973 "Unexpected unaligned RVV load type"); 2974 MVT NewVT = 2975 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2976 assert(NewVT.isValid() && 2977 "Expecting equally-sized RVV vector types to be legal"); 2978 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2979 Load->getPointerInfo(), Load->getOriginalAlign(), 2980 Load->getMemOperand()->getFlags()); 2981 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2982 } 2983 2984 // While RVV has alignment restrictions, we should always be able to store as a 2985 // legal equivalently-sized byte-typed vector instead. This method is 2986 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2987 // returns SDValue() if the store is already correctly aligned. 2988 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2989 SelectionDAG &DAG) const { 2990 auto *Store = cast<StoreSDNode>(Op); 2991 assert(Store && Store->getValue().getValueType().isVector() && 2992 "Expected vector store"); 2993 2994 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2995 Store->getMemoryVT(), 2996 *Store->getMemOperand())) 2997 return SDValue(); 2998 2999 SDLoc DL(Op); 3000 SDValue StoredVal = Store->getValue(); 3001 MVT VT = StoredVal.getSimpleValueType(); 3002 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3003 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3004 "Unexpected unaligned RVV store type"); 3005 MVT NewVT = 3006 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3007 assert(NewVT.isValid() && 3008 "Expecting equally-sized RVV vector types to be legal"); 3009 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3010 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3011 Store->getPointerInfo(), Store->getOriginalAlign(), 3012 Store->getMemOperand()->getFlags()); 3013 } 3014 3015 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 3016 const RISCVSubtarget &Subtarget) { 3017 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 3018 3019 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 3020 3021 // All simm32 constants should be handled by isel. 3022 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 3023 // this check redundant, but small immediates are common so this check 3024 // should have better compile time. 3025 if (isInt<32>(Imm)) 3026 return Op; 3027 3028 // We only need to cost the immediate, if constant pool lowering is enabled. 3029 if (!Subtarget.useConstantPoolForLargeInts()) 3030 return Op; 3031 3032 RISCVMatInt::InstSeq Seq = 3033 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3034 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3035 return Op; 3036 3037 // Expand to a constant pool using the default expansion code. 3038 return SDValue(); 3039 } 3040 3041 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3042 SelectionDAG &DAG) const { 3043 switch (Op.getOpcode()) { 3044 default: 3045 report_fatal_error("unimplemented operand"); 3046 case ISD::GlobalAddress: 3047 return lowerGlobalAddress(Op, DAG); 3048 case ISD::BlockAddress: 3049 return lowerBlockAddress(Op, DAG); 3050 case ISD::ConstantPool: 3051 return lowerConstantPool(Op, DAG); 3052 case ISD::JumpTable: 3053 return lowerJumpTable(Op, DAG); 3054 case ISD::GlobalTLSAddress: 3055 return lowerGlobalTLSAddress(Op, DAG); 3056 case ISD::Constant: 3057 return lowerConstant(Op, DAG, Subtarget); 3058 case ISD::SELECT: 3059 return lowerSELECT(Op, DAG); 3060 case ISD::BRCOND: 3061 return lowerBRCOND(Op, DAG); 3062 case ISD::VASTART: 3063 return lowerVASTART(Op, DAG); 3064 case ISD::FRAMEADDR: 3065 return lowerFRAMEADDR(Op, DAG); 3066 case ISD::RETURNADDR: 3067 return lowerRETURNADDR(Op, DAG); 3068 case ISD::SHL_PARTS: 3069 return lowerShiftLeftParts(Op, DAG); 3070 case ISD::SRA_PARTS: 3071 return lowerShiftRightParts(Op, DAG, true); 3072 case ISD::SRL_PARTS: 3073 return lowerShiftRightParts(Op, DAG, false); 3074 case ISD::BITCAST: { 3075 SDLoc DL(Op); 3076 EVT VT = Op.getValueType(); 3077 SDValue Op0 = Op.getOperand(0); 3078 EVT Op0VT = Op0.getValueType(); 3079 MVT XLenVT = Subtarget.getXLenVT(); 3080 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3081 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3082 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3083 return FPConv; 3084 } 3085 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3086 Subtarget.hasStdExtF()) { 3087 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3088 SDValue FPConv = 3089 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3090 return FPConv; 3091 } 3092 3093 // Consider other scalar<->scalar casts as legal if the types are legal. 3094 // Otherwise expand them. 3095 if (!VT.isVector() && !Op0VT.isVector()) { 3096 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3097 return Op; 3098 return SDValue(); 3099 } 3100 3101 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3102 "Unexpected types"); 3103 3104 if (VT.isFixedLengthVector()) { 3105 // We can handle fixed length vector bitcasts with a simple replacement 3106 // in isel. 3107 if (Op0VT.isFixedLengthVector()) 3108 return Op; 3109 // When bitcasting from scalar to fixed-length vector, insert the scalar 3110 // into a one-element vector of the result type, and perform a vector 3111 // bitcast. 3112 if (!Op0VT.isVector()) { 3113 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3114 if (!isTypeLegal(BVT)) 3115 return SDValue(); 3116 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3117 DAG.getUNDEF(BVT), Op0, 3118 DAG.getConstant(0, DL, XLenVT))); 3119 } 3120 return SDValue(); 3121 } 3122 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3123 // thus: bitcast the vector to a one-element vector type whose element type 3124 // is the same as the result type, and extract the first element. 3125 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3126 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3127 if (!isTypeLegal(BVT)) 3128 return SDValue(); 3129 SDValue BVec = DAG.getBitcast(BVT, Op0); 3130 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3131 DAG.getConstant(0, DL, XLenVT)); 3132 } 3133 return SDValue(); 3134 } 3135 case ISD::INTRINSIC_WO_CHAIN: 3136 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3137 case ISD::INTRINSIC_W_CHAIN: 3138 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3139 case ISD::INTRINSIC_VOID: 3140 return LowerINTRINSIC_VOID(Op, DAG); 3141 case ISD::BSWAP: 3142 case ISD::BITREVERSE: { 3143 MVT VT = Op.getSimpleValueType(); 3144 SDLoc DL(Op); 3145 if (Subtarget.hasStdExtZbp()) { 3146 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3147 // Start with the maximum immediate value which is the bitwidth - 1. 3148 unsigned Imm = VT.getSizeInBits() - 1; 3149 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3150 if (Op.getOpcode() == ISD::BSWAP) 3151 Imm &= ~0x7U; 3152 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3153 DAG.getConstant(Imm, DL, VT)); 3154 } 3155 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3156 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3157 // Expand bitreverse to a bswap(rev8) followed by brev8. 3158 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3159 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3160 // as brev8 by an isel pattern. 3161 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3162 DAG.getConstant(7, DL, VT)); 3163 } 3164 case ISD::FSHL: 3165 case ISD::FSHR: { 3166 MVT VT = Op.getSimpleValueType(); 3167 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3168 SDLoc DL(Op); 3169 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3170 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3171 // accidentally setting the extra bit. 3172 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3173 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3174 DAG.getConstant(ShAmtWidth, DL, VT)); 3175 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3176 // instruction use different orders. fshl will return its first operand for 3177 // shift of zero, fshr will return its second operand. fsl and fsr both 3178 // return rs1 so the ISD nodes need to have different operand orders. 3179 // Shift amount is in rs2. 3180 SDValue Op0 = Op.getOperand(0); 3181 SDValue Op1 = Op.getOperand(1); 3182 unsigned Opc = RISCVISD::FSL; 3183 if (Op.getOpcode() == ISD::FSHR) { 3184 std::swap(Op0, Op1); 3185 Opc = RISCVISD::FSR; 3186 } 3187 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3188 } 3189 case ISD::TRUNCATE: 3190 // Only custom-lower vector truncates 3191 if (!Op.getSimpleValueType().isVector()) 3192 return Op; 3193 return lowerVectorTruncLike(Op, DAG); 3194 case ISD::ANY_EXTEND: 3195 case ISD::ZERO_EXTEND: 3196 if (Op.getOperand(0).getValueType().isVector() && 3197 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3198 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3199 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3200 case ISD::SIGN_EXTEND: 3201 if (Op.getOperand(0).getValueType().isVector() && 3202 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3203 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3204 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3205 case ISD::SPLAT_VECTOR_PARTS: 3206 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3207 case ISD::INSERT_VECTOR_ELT: 3208 return lowerINSERT_VECTOR_ELT(Op, DAG); 3209 case ISD::EXTRACT_VECTOR_ELT: 3210 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3211 case ISD::VSCALE: { 3212 MVT VT = Op.getSimpleValueType(); 3213 SDLoc DL(Op); 3214 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3215 // We define our scalable vector types for lmul=1 to use a 64 bit known 3216 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3217 // vscale as VLENB / 8. 3218 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3219 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3220 report_fatal_error("Support for VLEN==32 is incomplete."); 3221 // We assume VLENB is a multiple of 8. We manually choose the best shift 3222 // here because SimplifyDemandedBits isn't always able to simplify it. 3223 uint64_t Val = Op.getConstantOperandVal(0); 3224 if (isPowerOf2_64(Val)) { 3225 uint64_t Log2 = Log2_64(Val); 3226 if (Log2 < 3) 3227 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3228 DAG.getConstant(3 - Log2, DL, VT)); 3229 if (Log2 > 3) 3230 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3231 DAG.getConstant(Log2 - 3, DL, VT)); 3232 return VLENB; 3233 } 3234 // If the multiplier is a multiple of 8, scale it down to avoid needing 3235 // to shift the VLENB value. 3236 if ((Val % 8) == 0) 3237 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3238 DAG.getConstant(Val / 8, DL, VT)); 3239 3240 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3241 DAG.getConstant(3, DL, VT)); 3242 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3243 } 3244 case ISD::FPOWI: { 3245 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3246 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3247 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3248 Op.getOperand(1).getValueType() == MVT::i32) { 3249 SDLoc DL(Op); 3250 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3251 SDValue Powi = 3252 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3253 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3254 DAG.getIntPtrConstant(0, DL)); 3255 } 3256 return SDValue(); 3257 } 3258 case ISD::FP_EXTEND: 3259 case ISD::FP_ROUND: 3260 if (!Op.getValueType().isVector()) 3261 return Op; 3262 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3263 case ISD::FP_TO_SINT: 3264 case ISD::FP_TO_UINT: 3265 case ISD::SINT_TO_FP: 3266 case ISD::UINT_TO_FP: { 3267 // RVV can only do fp<->int conversions to types half/double the size as 3268 // the source. We custom-lower any conversions that do two hops into 3269 // sequences. 3270 MVT VT = Op.getSimpleValueType(); 3271 if (!VT.isVector()) 3272 return Op; 3273 SDLoc DL(Op); 3274 SDValue Src = Op.getOperand(0); 3275 MVT EltVT = VT.getVectorElementType(); 3276 MVT SrcVT = Src.getSimpleValueType(); 3277 MVT SrcEltVT = SrcVT.getVectorElementType(); 3278 unsigned EltSize = EltVT.getSizeInBits(); 3279 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3280 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3281 "Unexpected vector element types"); 3282 3283 bool IsInt2FP = SrcEltVT.isInteger(); 3284 // Widening conversions 3285 if (EltSize > (2 * SrcEltSize)) { 3286 if (IsInt2FP) { 3287 // Do a regular integer sign/zero extension then convert to float. 3288 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3289 VT.getVectorElementCount()); 3290 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3291 ? ISD::ZERO_EXTEND 3292 : ISD::SIGN_EXTEND; 3293 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3294 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3295 } 3296 // FP2Int 3297 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3298 // Do one doubling fp_extend then complete the operation by converting 3299 // to int. 3300 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3301 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3302 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3303 } 3304 3305 // Narrowing conversions 3306 if (SrcEltSize > (2 * EltSize)) { 3307 if (IsInt2FP) { 3308 // One narrowing int_to_fp, then an fp_round. 3309 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3310 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3311 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3312 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3313 } 3314 // FP2Int 3315 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3316 // representable by the integer, the result is poison. 3317 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3318 VT.getVectorElementCount()); 3319 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3320 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3321 } 3322 3323 // Scalable vectors can exit here. Patterns will handle equally-sized 3324 // conversions halving/doubling ones. 3325 if (!VT.isFixedLengthVector()) 3326 return Op; 3327 3328 // For fixed-length vectors we lower to a custom "VL" node. 3329 unsigned RVVOpc = 0; 3330 switch (Op.getOpcode()) { 3331 default: 3332 llvm_unreachable("Impossible opcode"); 3333 case ISD::FP_TO_SINT: 3334 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3335 break; 3336 case ISD::FP_TO_UINT: 3337 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3338 break; 3339 case ISD::SINT_TO_FP: 3340 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3341 break; 3342 case ISD::UINT_TO_FP: 3343 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3344 break; 3345 } 3346 3347 MVT ContainerVT, SrcContainerVT; 3348 // Derive the reference container type from the larger vector type. 3349 if (SrcEltSize > EltSize) { 3350 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3351 ContainerVT = 3352 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3353 } else { 3354 ContainerVT = getContainerForFixedLengthVector(VT); 3355 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3356 } 3357 3358 SDValue Mask, VL; 3359 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3360 3361 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3362 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3363 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3364 } 3365 case ISD::FP_TO_SINT_SAT: 3366 case ISD::FP_TO_UINT_SAT: 3367 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3368 case ISD::FTRUNC: 3369 case ISD::FCEIL: 3370 case ISD::FFLOOR: 3371 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3372 case ISD::FROUND: 3373 return lowerFROUND(Op, DAG); 3374 case ISD::VECREDUCE_ADD: 3375 case ISD::VECREDUCE_UMAX: 3376 case ISD::VECREDUCE_SMAX: 3377 case ISD::VECREDUCE_UMIN: 3378 case ISD::VECREDUCE_SMIN: 3379 return lowerVECREDUCE(Op, DAG); 3380 case ISD::VECREDUCE_AND: 3381 case ISD::VECREDUCE_OR: 3382 case ISD::VECREDUCE_XOR: 3383 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3384 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3385 return lowerVECREDUCE(Op, DAG); 3386 case ISD::VECREDUCE_FADD: 3387 case ISD::VECREDUCE_SEQ_FADD: 3388 case ISD::VECREDUCE_FMIN: 3389 case ISD::VECREDUCE_FMAX: 3390 return lowerFPVECREDUCE(Op, DAG); 3391 case ISD::VP_REDUCE_ADD: 3392 case ISD::VP_REDUCE_UMAX: 3393 case ISD::VP_REDUCE_SMAX: 3394 case ISD::VP_REDUCE_UMIN: 3395 case ISD::VP_REDUCE_SMIN: 3396 case ISD::VP_REDUCE_FADD: 3397 case ISD::VP_REDUCE_SEQ_FADD: 3398 case ISD::VP_REDUCE_FMIN: 3399 case ISD::VP_REDUCE_FMAX: 3400 return lowerVPREDUCE(Op, DAG); 3401 case ISD::VP_REDUCE_AND: 3402 case ISD::VP_REDUCE_OR: 3403 case ISD::VP_REDUCE_XOR: 3404 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3405 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3406 return lowerVPREDUCE(Op, DAG); 3407 case ISD::INSERT_SUBVECTOR: 3408 return lowerINSERT_SUBVECTOR(Op, DAG); 3409 case ISD::EXTRACT_SUBVECTOR: 3410 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3411 case ISD::STEP_VECTOR: 3412 return lowerSTEP_VECTOR(Op, DAG); 3413 case ISD::VECTOR_REVERSE: 3414 return lowerVECTOR_REVERSE(Op, DAG); 3415 case ISD::VECTOR_SPLICE: 3416 return lowerVECTOR_SPLICE(Op, DAG); 3417 case ISD::BUILD_VECTOR: 3418 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3419 case ISD::SPLAT_VECTOR: 3420 if (Op.getValueType().getVectorElementType() == MVT::i1) 3421 return lowerVectorMaskSplat(Op, DAG); 3422 return SDValue(); 3423 case ISD::VECTOR_SHUFFLE: 3424 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3425 case ISD::CONCAT_VECTORS: { 3426 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3427 // better than going through the stack, as the default expansion does. 3428 SDLoc DL(Op); 3429 MVT VT = Op.getSimpleValueType(); 3430 unsigned NumOpElts = 3431 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3432 SDValue Vec = DAG.getUNDEF(VT); 3433 for (const auto &OpIdx : enumerate(Op->ops())) { 3434 SDValue SubVec = OpIdx.value(); 3435 // Don't insert undef subvectors. 3436 if (SubVec.isUndef()) 3437 continue; 3438 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3439 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3440 } 3441 return Vec; 3442 } 3443 case ISD::LOAD: 3444 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3445 return V; 3446 if (Op.getValueType().isFixedLengthVector()) 3447 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3448 return Op; 3449 case ISD::STORE: 3450 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3451 return V; 3452 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3453 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3454 return Op; 3455 case ISD::MLOAD: 3456 case ISD::VP_LOAD: 3457 return lowerMaskedLoad(Op, DAG); 3458 case ISD::MSTORE: 3459 case ISD::VP_STORE: 3460 return lowerMaskedStore(Op, DAG); 3461 case ISD::SETCC: 3462 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3463 case ISD::ADD: 3464 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3465 case ISD::SUB: 3466 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3467 case ISD::MUL: 3468 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3469 case ISD::MULHS: 3470 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3471 case ISD::MULHU: 3472 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3473 case ISD::AND: 3474 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3475 RISCVISD::AND_VL); 3476 case ISD::OR: 3477 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3478 RISCVISD::OR_VL); 3479 case ISD::XOR: 3480 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3481 RISCVISD::XOR_VL); 3482 case ISD::SDIV: 3483 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3484 case ISD::SREM: 3485 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3486 case ISD::UDIV: 3487 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3488 case ISD::UREM: 3489 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3490 case ISD::SHL: 3491 case ISD::SRA: 3492 case ISD::SRL: 3493 if (Op.getSimpleValueType().isFixedLengthVector()) 3494 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3495 // This can be called for an i32 shift amount that needs to be promoted. 3496 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3497 "Unexpected custom legalisation"); 3498 return SDValue(); 3499 case ISD::SADDSAT: 3500 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3501 case ISD::UADDSAT: 3502 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3503 case ISD::SSUBSAT: 3504 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3505 case ISD::USUBSAT: 3506 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3507 case ISD::FADD: 3508 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3509 case ISD::FSUB: 3510 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3511 case ISD::FMUL: 3512 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3513 case ISD::FDIV: 3514 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3515 case ISD::FNEG: 3516 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3517 case ISD::FABS: 3518 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3519 case ISD::FSQRT: 3520 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3521 case ISD::FMA: 3522 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3523 case ISD::SMIN: 3524 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3525 case ISD::SMAX: 3526 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3527 case ISD::UMIN: 3528 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3529 case ISD::UMAX: 3530 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3531 case ISD::FMINNUM: 3532 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3533 case ISD::FMAXNUM: 3534 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3535 case ISD::ABS: 3536 return lowerABS(Op, DAG); 3537 case ISD::CTLZ_ZERO_UNDEF: 3538 case ISD::CTTZ_ZERO_UNDEF: 3539 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3540 case ISD::VSELECT: 3541 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3542 case ISD::FCOPYSIGN: 3543 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3544 case ISD::MGATHER: 3545 case ISD::VP_GATHER: 3546 return lowerMaskedGather(Op, DAG); 3547 case ISD::MSCATTER: 3548 case ISD::VP_SCATTER: 3549 return lowerMaskedScatter(Op, DAG); 3550 case ISD::FLT_ROUNDS_: 3551 return lowerGET_ROUNDING(Op, DAG); 3552 case ISD::SET_ROUNDING: 3553 return lowerSET_ROUNDING(Op, DAG); 3554 case ISD::EH_DWARF_CFA: 3555 return lowerEH_DWARF_CFA(Op, DAG); 3556 case ISD::VP_SELECT: 3557 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3558 case ISD::VP_MERGE: 3559 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3560 case ISD::VP_ADD: 3561 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3562 case ISD::VP_SUB: 3563 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3564 case ISD::VP_MUL: 3565 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3566 case ISD::VP_SDIV: 3567 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3568 case ISD::VP_UDIV: 3569 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3570 case ISD::VP_SREM: 3571 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3572 case ISD::VP_UREM: 3573 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3574 case ISD::VP_AND: 3575 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3576 case ISD::VP_OR: 3577 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3578 case ISD::VP_XOR: 3579 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3580 case ISD::VP_ASHR: 3581 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3582 case ISD::VP_LSHR: 3583 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3584 case ISD::VP_SHL: 3585 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3586 case ISD::VP_FADD: 3587 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3588 case ISD::VP_FSUB: 3589 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3590 case ISD::VP_FMUL: 3591 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3592 case ISD::VP_FDIV: 3593 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3594 case ISD::VP_FNEG: 3595 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3596 case ISD::VP_FMA: 3597 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3598 case ISD::VP_SIGN_EXTEND: 3599 case ISD::VP_ZERO_EXTEND: 3600 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3601 return lowerVPExtMaskOp(Op, DAG); 3602 return lowerVPOp(Op, DAG, 3603 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3604 ? RISCVISD::VSEXT_VL 3605 : RISCVISD::VZEXT_VL); 3606 case ISD::VP_TRUNCATE: 3607 return lowerVectorTruncLike(Op, DAG); 3608 case ISD::VP_FP_EXTEND: 3609 case ISD::VP_FP_ROUND: 3610 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3611 case ISD::VP_FPTOSI: 3612 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3613 case ISD::VP_FPTOUI: 3614 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3615 case ISD::VP_SITOFP: 3616 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3617 case ISD::VP_UITOFP: 3618 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3619 case ISD::VP_SETCC: 3620 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3621 return lowerVPSetCCMaskOp(Op, DAG); 3622 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3623 } 3624 } 3625 3626 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3627 SelectionDAG &DAG, unsigned Flags) { 3628 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3629 } 3630 3631 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3632 SelectionDAG &DAG, unsigned Flags) { 3633 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3634 Flags); 3635 } 3636 3637 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3638 SelectionDAG &DAG, unsigned Flags) { 3639 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3640 N->getOffset(), Flags); 3641 } 3642 3643 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3644 SelectionDAG &DAG, unsigned Flags) { 3645 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3646 } 3647 3648 template <class NodeTy> 3649 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3650 bool IsLocal) const { 3651 SDLoc DL(N); 3652 EVT Ty = getPointerTy(DAG.getDataLayout()); 3653 3654 if (isPositionIndependent()) { 3655 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3656 if (IsLocal) 3657 // Use PC-relative addressing to access the symbol. This generates the 3658 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3659 // %pcrel_lo(auipc)). 3660 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3661 3662 // Use PC-relative addressing to access the GOT for this symbol, then load 3663 // the address from the GOT. This generates the pattern (PseudoLA sym), 3664 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3665 MachineFunction &MF = DAG.getMachineFunction(); 3666 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3667 MachinePointerInfo::getGOT(MF), 3668 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3669 MachineMemOperand::MOInvariant, 3670 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3671 SDValue Load = 3672 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3673 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3674 return Load; 3675 } 3676 3677 switch (getTargetMachine().getCodeModel()) { 3678 default: 3679 report_fatal_error("Unsupported code model for lowering"); 3680 case CodeModel::Small: { 3681 // Generate a sequence for accessing addresses within the first 2 GiB of 3682 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3683 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3684 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3685 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3686 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3687 } 3688 case CodeModel::Medium: { 3689 // Generate a sequence for accessing addresses within any 2GiB range within 3690 // the address space. This generates the pattern (PseudoLLA sym), which 3691 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3692 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3693 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3694 } 3695 } 3696 } 3697 3698 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3699 SelectionDAG &DAG) const { 3700 SDLoc DL(Op); 3701 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3702 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3703 3704 const GlobalValue *GV = N->getGlobal(); 3705 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3706 return getAddr(N, DAG, IsLocal); 3707 } 3708 3709 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3710 SelectionDAG &DAG) const { 3711 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3712 3713 return getAddr(N, DAG); 3714 } 3715 3716 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3717 SelectionDAG &DAG) const { 3718 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3719 3720 return getAddr(N, DAG); 3721 } 3722 3723 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3724 SelectionDAG &DAG) const { 3725 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3726 3727 return getAddr(N, DAG); 3728 } 3729 3730 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3731 SelectionDAG &DAG, 3732 bool UseGOT) const { 3733 SDLoc DL(N); 3734 EVT Ty = getPointerTy(DAG.getDataLayout()); 3735 const GlobalValue *GV = N->getGlobal(); 3736 MVT XLenVT = Subtarget.getXLenVT(); 3737 3738 if (UseGOT) { 3739 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3740 // load the address from the GOT and add the thread pointer. This generates 3741 // the pattern (PseudoLA_TLS_IE sym), which expands to 3742 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3743 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3744 MachineFunction &MF = DAG.getMachineFunction(); 3745 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3746 MachinePointerInfo::getGOT(MF), 3747 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3748 MachineMemOperand::MOInvariant, 3749 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3750 SDValue Load = DAG.getMemIntrinsicNode( 3751 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3752 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3753 3754 // Add the thread pointer. 3755 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3756 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3757 } 3758 3759 // Generate a sequence for accessing the address relative to the thread 3760 // pointer, with the appropriate adjustment for the thread pointer offset. 3761 // This generates the pattern 3762 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3763 SDValue AddrHi = 3764 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3765 SDValue AddrAdd = 3766 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3767 SDValue AddrLo = 3768 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3769 3770 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3771 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3772 SDValue MNAdd = 3773 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3774 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3775 } 3776 3777 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3778 SelectionDAG &DAG) const { 3779 SDLoc DL(N); 3780 EVT Ty = getPointerTy(DAG.getDataLayout()); 3781 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3782 const GlobalValue *GV = N->getGlobal(); 3783 3784 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3785 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3786 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3787 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3788 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3789 3790 // Prepare argument list to generate call. 3791 ArgListTy Args; 3792 ArgListEntry Entry; 3793 Entry.Node = Load; 3794 Entry.Ty = CallTy; 3795 Args.push_back(Entry); 3796 3797 // Setup call to __tls_get_addr. 3798 TargetLowering::CallLoweringInfo CLI(DAG); 3799 CLI.setDebugLoc(DL) 3800 .setChain(DAG.getEntryNode()) 3801 .setLibCallee(CallingConv::C, CallTy, 3802 DAG.getExternalSymbol("__tls_get_addr", Ty), 3803 std::move(Args)); 3804 3805 return LowerCallTo(CLI).first; 3806 } 3807 3808 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3809 SelectionDAG &DAG) const { 3810 SDLoc DL(Op); 3811 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3812 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3813 3814 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3815 3816 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3817 CallingConv::GHC) 3818 report_fatal_error("In GHC calling convention TLS is not supported"); 3819 3820 SDValue Addr; 3821 switch (Model) { 3822 case TLSModel::LocalExec: 3823 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3824 break; 3825 case TLSModel::InitialExec: 3826 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3827 break; 3828 case TLSModel::LocalDynamic: 3829 case TLSModel::GeneralDynamic: 3830 Addr = getDynamicTLSAddr(N, DAG); 3831 break; 3832 } 3833 3834 return Addr; 3835 } 3836 3837 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3838 SDValue CondV = Op.getOperand(0); 3839 SDValue TrueV = Op.getOperand(1); 3840 SDValue FalseV = Op.getOperand(2); 3841 SDLoc DL(Op); 3842 MVT VT = Op.getSimpleValueType(); 3843 MVT XLenVT = Subtarget.getXLenVT(); 3844 3845 // Lower vector SELECTs to VSELECTs by splatting the condition. 3846 if (VT.isVector()) { 3847 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3848 SDValue CondSplat = VT.isScalableVector() 3849 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3850 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3851 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3852 } 3853 3854 // If the result type is XLenVT and CondV is the output of a SETCC node 3855 // which also operated on XLenVT inputs, then merge the SETCC node into the 3856 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3857 // compare+branch instructions. i.e.: 3858 // (select (setcc lhs, rhs, cc), truev, falsev) 3859 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3860 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3861 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3862 SDValue LHS = CondV.getOperand(0); 3863 SDValue RHS = CondV.getOperand(1); 3864 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3865 ISD::CondCode CCVal = CC->get(); 3866 3867 // Special case for a select of 2 constants that have a diffence of 1. 3868 // Normally this is done by DAGCombine, but if the select is introduced by 3869 // type legalization or op legalization, we miss it. Restricting to SETLT 3870 // case for now because that is what signed saturating add/sub need. 3871 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3872 // but we would probably want to swap the true/false values if the condition 3873 // is SETGE/SETLE to avoid an XORI. 3874 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3875 CCVal == ISD::SETLT) { 3876 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3877 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3878 if (TrueVal - 1 == FalseVal) 3879 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3880 if (TrueVal + 1 == FalseVal) 3881 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3882 } 3883 3884 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3885 3886 SDValue TargetCC = DAG.getCondCode(CCVal); 3887 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3888 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3889 } 3890 3891 // Otherwise: 3892 // (select condv, truev, falsev) 3893 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3894 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3895 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3896 3897 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3898 3899 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3900 } 3901 3902 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3903 SDValue CondV = Op.getOperand(1); 3904 SDLoc DL(Op); 3905 MVT XLenVT = Subtarget.getXLenVT(); 3906 3907 if (CondV.getOpcode() == ISD::SETCC && 3908 CondV.getOperand(0).getValueType() == XLenVT) { 3909 SDValue LHS = CondV.getOperand(0); 3910 SDValue RHS = CondV.getOperand(1); 3911 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3912 3913 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3914 3915 SDValue TargetCC = DAG.getCondCode(CCVal); 3916 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3917 LHS, RHS, TargetCC, Op.getOperand(2)); 3918 } 3919 3920 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3921 CondV, DAG.getConstant(0, DL, XLenVT), 3922 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3923 } 3924 3925 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3926 MachineFunction &MF = DAG.getMachineFunction(); 3927 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3928 3929 SDLoc DL(Op); 3930 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3931 getPointerTy(MF.getDataLayout())); 3932 3933 // vastart just stores the address of the VarArgsFrameIndex slot into the 3934 // memory location argument. 3935 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3936 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3937 MachinePointerInfo(SV)); 3938 } 3939 3940 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3941 SelectionDAG &DAG) const { 3942 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3943 MachineFunction &MF = DAG.getMachineFunction(); 3944 MachineFrameInfo &MFI = MF.getFrameInfo(); 3945 MFI.setFrameAddressIsTaken(true); 3946 Register FrameReg = RI.getFrameRegister(MF); 3947 int XLenInBytes = Subtarget.getXLen() / 8; 3948 3949 EVT VT = Op.getValueType(); 3950 SDLoc DL(Op); 3951 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3952 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3953 while (Depth--) { 3954 int Offset = -(XLenInBytes * 2); 3955 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3956 DAG.getIntPtrConstant(Offset, DL)); 3957 FrameAddr = 3958 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3959 } 3960 return FrameAddr; 3961 } 3962 3963 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3964 SelectionDAG &DAG) const { 3965 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3966 MachineFunction &MF = DAG.getMachineFunction(); 3967 MachineFrameInfo &MFI = MF.getFrameInfo(); 3968 MFI.setReturnAddressIsTaken(true); 3969 MVT XLenVT = Subtarget.getXLenVT(); 3970 int XLenInBytes = Subtarget.getXLen() / 8; 3971 3972 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3973 return SDValue(); 3974 3975 EVT VT = Op.getValueType(); 3976 SDLoc DL(Op); 3977 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3978 if (Depth) { 3979 int Off = -XLenInBytes; 3980 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3981 SDValue Offset = DAG.getConstant(Off, DL, VT); 3982 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3983 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3984 MachinePointerInfo()); 3985 } 3986 3987 // Return the value of the return address register, marking it an implicit 3988 // live-in. 3989 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3990 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3991 } 3992 3993 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3994 SelectionDAG &DAG) const { 3995 SDLoc DL(Op); 3996 SDValue Lo = Op.getOperand(0); 3997 SDValue Hi = Op.getOperand(1); 3998 SDValue Shamt = Op.getOperand(2); 3999 EVT VT = Lo.getValueType(); 4000 4001 // if Shamt-XLEN < 0: // Shamt < XLEN 4002 // Lo = Lo << Shamt 4003 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4004 // else: 4005 // Lo = 0 4006 // Hi = Lo << (Shamt-XLEN) 4007 4008 SDValue Zero = DAG.getConstant(0, DL, VT); 4009 SDValue One = DAG.getConstant(1, DL, VT); 4010 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4011 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4012 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4013 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4014 4015 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4016 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4017 SDValue ShiftRightLo = 4018 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4019 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4020 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4021 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4022 4023 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4024 4025 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4026 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4027 4028 SDValue Parts[2] = {Lo, Hi}; 4029 return DAG.getMergeValues(Parts, DL); 4030 } 4031 4032 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4033 bool IsSRA) const { 4034 SDLoc DL(Op); 4035 SDValue Lo = Op.getOperand(0); 4036 SDValue Hi = Op.getOperand(1); 4037 SDValue Shamt = Op.getOperand(2); 4038 EVT VT = Lo.getValueType(); 4039 4040 // SRA expansion: 4041 // if Shamt-XLEN < 0: // Shamt < XLEN 4042 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4043 // Hi = Hi >>s Shamt 4044 // else: 4045 // Lo = Hi >>s (Shamt-XLEN); 4046 // Hi = Hi >>s (XLEN-1) 4047 // 4048 // SRL expansion: 4049 // if Shamt-XLEN < 0: // Shamt < XLEN 4050 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4051 // Hi = Hi >>u Shamt 4052 // else: 4053 // Lo = Hi >>u (Shamt-XLEN); 4054 // Hi = 0; 4055 4056 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4057 4058 SDValue Zero = DAG.getConstant(0, DL, VT); 4059 SDValue One = DAG.getConstant(1, DL, VT); 4060 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4061 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4062 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4063 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4064 4065 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4066 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4067 SDValue ShiftLeftHi = 4068 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4069 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4070 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4071 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4072 SDValue HiFalse = 4073 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4074 4075 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4076 4077 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4078 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4079 4080 SDValue Parts[2] = {Lo, Hi}; 4081 return DAG.getMergeValues(Parts, DL); 4082 } 4083 4084 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4085 // legal equivalently-sized i8 type, so we can use that as a go-between. 4086 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4087 SelectionDAG &DAG) const { 4088 SDLoc DL(Op); 4089 MVT VT = Op.getSimpleValueType(); 4090 SDValue SplatVal = Op.getOperand(0); 4091 // All-zeros or all-ones splats are handled specially. 4092 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4093 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4094 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4095 } 4096 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4097 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4098 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4099 } 4100 MVT XLenVT = Subtarget.getXLenVT(); 4101 assert(SplatVal.getValueType() == XLenVT && 4102 "Unexpected type for i1 splat value"); 4103 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4104 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4105 DAG.getConstant(1, DL, XLenVT)); 4106 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4107 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4108 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4109 } 4110 4111 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4112 // illegal (currently only vXi64 RV32). 4113 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4114 // them to VMV_V_X_VL. 4115 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4116 SelectionDAG &DAG) const { 4117 SDLoc DL(Op); 4118 MVT VecVT = Op.getSimpleValueType(); 4119 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4120 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4121 4122 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4123 SDValue Lo = Op.getOperand(0); 4124 SDValue Hi = Op.getOperand(1); 4125 4126 if (VecVT.isFixedLengthVector()) { 4127 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4128 SDLoc DL(Op); 4129 SDValue Mask, VL; 4130 std::tie(Mask, VL) = 4131 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4132 4133 SDValue Res = 4134 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4135 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4136 } 4137 4138 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4139 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4140 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4141 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4142 // node in order to try and match RVV vector/scalar instructions. 4143 if ((LoC >> 31) == HiC) 4144 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4145 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4146 } 4147 4148 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4149 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4150 isa<ConstantSDNode>(Hi.getOperand(1)) && 4151 Hi.getConstantOperandVal(1) == 31) 4152 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4153 DAG.getRegister(RISCV::X0, MVT::i32)); 4154 4155 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4156 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4157 DAG.getUNDEF(VecVT), Lo, Hi, 4158 DAG.getRegister(RISCV::X0, MVT::i32)); 4159 } 4160 4161 // Custom-lower extensions from mask vectors by using a vselect either with 1 4162 // for zero/any-extension or -1 for sign-extension: 4163 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4164 // Note that any-extension is lowered identically to zero-extension. 4165 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4166 int64_t ExtTrueVal) const { 4167 SDLoc DL(Op); 4168 MVT VecVT = Op.getSimpleValueType(); 4169 SDValue Src = Op.getOperand(0); 4170 // Only custom-lower extensions from mask types 4171 assert(Src.getValueType().isVector() && 4172 Src.getValueType().getVectorElementType() == MVT::i1); 4173 4174 if (VecVT.isScalableVector()) { 4175 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4176 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4177 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4178 } 4179 4180 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4181 MVT I1ContainerVT = 4182 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4183 4184 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4185 4186 SDValue Mask, VL; 4187 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4188 4189 MVT XLenVT = Subtarget.getXLenVT(); 4190 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4191 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4192 4193 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4194 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4195 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4196 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4197 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4198 SplatTrueVal, SplatZero, VL); 4199 4200 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4201 } 4202 4203 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4204 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4205 MVT ExtVT = Op.getSimpleValueType(); 4206 // Only custom-lower extensions from fixed-length vector types. 4207 if (!ExtVT.isFixedLengthVector()) 4208 return Op; 4209 MVT VT = Op.getOperand(0).getSimpleValueType(); 4210 // Grab the canonical container type for the extended type. Infer the smaller 4211 // type from that to ensure the same number of vector elements, as we know 4212 // the LMUL will be sufficient to hold the smaller type. 4213 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4214 // Get the extended container type manually to ensure the same number of 4215 // vector elements between source and dest. 4216 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4217 ContainerExtVT.getVectorElementCount()); 4218 4219 SDValue Op1 = 4220 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4221 4222 SDLoc DL(Op); 4223 SDValue Mask, VL; 4224 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4225 4226 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4227 4228 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4229 } 4230 4231 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4232 // setcc operation: 4233 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4234 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4235 SelectionDAG &DAG) const { 4236 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4237 SDLoc DL(Op); 4238 EVT MaskVT = Op.getValueType(); 4239 // Only expect to custom-lower truncations to mask types 4240 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4241 "Unexpected type for vector mask lowering"); 4242 SDValue Src = Op.getOperand(0); 4243 MVT VecVT = Src.getSimpleValueType(); 4244 SDValue Mask, VL; 4245 if (IsVPTrunc) { 4246 Mask = Op.getOperand(1); 4247 VL = Op.getOperand(2); 4248 } 4249 // If this is a fixed vector, we need to convert it to a scalable vector. 4250 MVT ContainerVT = VecVT; 4251 4252 if (VecVT.isFixedLengthVector()) { 4253 ContainerVT = getContainerForFixedLengthVector(VecVT); 4254 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4255 if (IsVPTrunc) { 4256 MVT MaskContainerVT = 4257 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4258 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4259 } 4260 } 4261 4262 if (!IsVPTrunc) { 4263 std::tie(Mask, VL) = 4264 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4265 } 4266 4267 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4268 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4269 4270 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4271 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4272 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4273 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4274 4275 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4276 SDValue Trunc = 4277 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4278 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4279 DAG.getCondCode(ISD::SETNE), Mask, VL); 4280 if (MaskVT.isFixedLengthVector()) 4281 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4282 return Trunc; 4283 } 4284 4285 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4286 SelectionDAG &DAG) const { 4287 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4288 SDLoc DL(Op); 4289 4290 MVT VT = Op.getSimpleValueType(); 4291 // Only custom-lower vector truncates 4292 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4293 4294 // Truncates to mask types are handled differently 4295 if (VT.getVectorElementType() == MVT::i1) 4296 return lowerVectorMaskTruncLike(Op, DAG); 4297 4298 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4299 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4300 // truncate by one power of two at a time. 4301 MVT DstEltVT = VT.getVectorElementType(); 4302 4303 SDValue Src = Op.getOperand(0); 4304 MVT SrcVT = Src.getSimpleValueType(); 4305 MVT SrcEltVT = SrcVT.getVectorElementType(); 4306 4307 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4308 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4309 "Unexpected vector truncate lowering"); 4310 4311 MVT ContainerVT = SrcVT; 4312 SDValue Mask, VL; 4313 if (IsVPTrunc) { 4314 Mask = Op.getOperand(1); 4315 VL = Op.getOperand(2); 4316 } 4317 if (SrcVT.isFixedLengthVector()) { 4318 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4319 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4320 if (IsVPTrunc) { 4321 MVT MaskVT = getMaskTypeFor(ContainerVT); 4322 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4323 } 4324 } 4325 4326 SDValue Result = Src; 4327 if (!IsVPTrunc) { 4328 std::tie(Mask, VL) = 4329 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4330 } 4331 4332 LLVMContext &Context = *DAG.getContext(); 4333 const ElementCount Count = ContainerVT.getVectorElementCount(); 4334 do { 4335 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4336 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4337 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4338 Mask, VL); 4339 } while (SrcEltVT != DstEltVT); 4340 4341 if (SrcVT.isFixedLengthVector()) 4342 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4343 4344 return Result; 4345 } 4346 4347 SDValue 4348 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4349 SelectionDAG &DAG) const { 4350 bool IsVP = 4351 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4352 bool IsExtend = 4353 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4354 // RVV can only do truncate fp to types half the size as the source. We 4355 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4356 // conversion instruction. 4357 SDLoc DL(Op); 4358 MVT VT = Op.getSimpleValueType(); 4359 4360 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4361 4362 SDValue Src = Op.getOperand(0); 4363 MVT SrcVT = Src.getSimpleValueType(); 4364 4365 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4366 SrcVT.getVectorElementType() != MVT::f16); 4367 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4368 SrcVT.getVectorElementType() != MVT::f64); 4369 4370 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4371 4372 // Prepare any fixed-length vector operands. 4373 MVT ContainerVT = VT; 4374 SDValue Mask, VL; 4375 if (IsVP) { 4376 Mask = Op.getOperand(1); 4377 VL = Op.getOperand(2); 4378 } 4379 if (VT.isFixedLengthVector()) { 4380 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4381 ContainerVT = 4382 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4383 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4384 if (IsVP) { 4385 MVT MaskVT = getMaskTypeFor(ContainerVT); 4386 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4387 } 4388 } 4389 4390 if (!IsVP) 4391 std::tie(Mask, VL) = 4392 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4393 4394 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4395 4396 if (IsDirectConv) { 4397 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4398 if (VT.isFixedLengthVector()) 4399 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4400 return Src; 4401 } 4402 4403 unsigned InterConvOpc = 4404 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4405 4406 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4407 SDValue IntermediateConv = 4408 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4409 SDValue Result = 4410 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4411 if (VT.isFixedLengthVector()) 4412 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4413 return Result; 4414 } 4415 4416 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4417 // first position of a vector, and that vector is slid up to the insert index. 4418 // By limiting the active vector length to index+1 and merging with the 4419 // original vector (with an undisturbed tail policy for elements >= VL), we 4420 // achieve the desired result of leaving all elements untouched except the one 4421 // at VL-1, which is replaced with the desired value. 4422 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4423 SelectionDAG &DAG) const { 4424 SDLoc DL(Op); 4425 MVT VecVT = Op.getSimpleValueType(); 4426 SDValue Vec = Op.getOperand(0); 4427 SDValue Val = Op.getOperand(1); 4428 SDValue Idx = Op.getOperand(2); 4429 4430 if (VecVT.getVectorElementType() == MVT::i1) { 4431 // FIXME: For now we just promote to an i8 vector and insert into that, 4432 // but this is probably not optimal. 4433 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4434 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4435 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4436 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4437 } 4438 4439 MVT ContainerVT = VecVT; 4440 // If the operand is a fixed-length vector, convert to a scalable one. 4441 if (VecVT.isFixedLengthVector()) { 4442 ContainerVT = getContainerForFixedLengthVector(VecVT); 4443 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4444 } 4445 4446 MVT XLenVT = Subtarget.getXLenVT(); 4447 4448 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4449 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4450 // Even i64-element vectors on RV32 can be lowered without scalar 4451 // legalization if the most-significant 32 bits of the value are not affected 4452 // by the sign-extension of the lower 32 bits. 4453 // TODO: We could also catch sign extensions of a 32-bit value. 4454 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4455 const auto *CVal = cast<ConstantSDNode>(Val); 4456 if (isInt<32>(CVal->getSExtValue())) { 4457 IsLegalInsert = true; 4458 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4459 } 4460 } 4461 4462 SDValue Mask, VL; 4463 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4464 4465 SDValue ValInVec; 4466 4467 if (IsLegalInsert) { 4468 unsigned Opc = 4469 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4470 if (isNullConstant(Idx)) { 4471 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4472 if (!VecVT.isFixedLengthVector()) 4473 return Vec; 4474 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4475 } 4476 ValInVec = 4477 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4478 } else { 4479 // On RV32, i64-element vectors must be specially handled to place the 4480 // value at element 0, by using two vslide1up instructions in sequence on 4481 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4482 // this. 4483 SDValue One = DAG.getConstant(1, DL, XLenVT); 4484 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4485 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4486 MVT I32ContainerVT = 4487 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4488 SDValue I32Mask = 4489 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4490 // Limit the active VL to two. 4491 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4492 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4493 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4494 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4495 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4496 // First slide in the hi value, then the lo in underneath it. 4497 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4498 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4499 I32Mask, InsertI64VL); 4500 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4501 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4502 I32Mask, InsertI64VL); 4503 // Bitcast back to the right container type. 4504 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4505 } 4506 4507 // Now that the value is in a vector, slide it into position. 4508 SDValue InsertVL = 4509 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4510 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4511 ValInVec, Idx, Mask, InsertVL); 4512 if (!VecVT.isFixedLengthVector()) 4513 return Slideup; 4514 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4515 } 4516 4517 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4518 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4519 // types this is done using VMV_X_S to allow us to glean information about the 4520 // sign bits of the result. 4521 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4522 SelectionDAG &DAG) const { 4523 SDLoc DL(Op); 4524 SDValue Idx = Op.getOperand(1); 4525 SDValue Vec = Op.getOperand(0); 4526 EVT EltVT = Op.getValueType(); 4527 MVT VecVT = Vec.getSimpleValueType(); 4528 MVT XLenVT = Subtarget.getXLenVT(); 4529 4530 if (VecVT.getVectorElementType() == MVT::i1) { 4531 if (VecVT.isFixedLengthVector()) { 4532 unsigned NumElts = VecVT.getVectorNumElements(); 4533 if (NumElts >= 8) { 4534 MVT WideEltVT; 4535 unsigned WidenVecLen; 4536 SDValue ExtractElementIdx; 4537 SDValue ExtractBitIdx; 4538 unsigned MaxEEW = Subtarget.getELEN(); 4539 MVT LargestEltVT = MVT::getIntegerVT( 4540 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4541 if (NumElts <= LargestEltVT.getSizeInBits()) { 4542 assert(isPowerOf2_32(NumElts) && 4543 "the number of elements should be power of 2"); 4544 WideEltVT = MVT::getIntegerVT(NumElts); 4545 WidenVecLen = 1; 4546 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4547 ExtractBitIdx = Idx; 4548 } else { 4549 WideEltVT = LargestEltVT; 4550 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4551 // extract element index = index / element width 4552 ExtractElementIdx = DAG.getNode( 4553 ISD::SRL, DL, XLenVT, Idx, 4554 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4555 // mask bit index = index % element width 4556 ExtractBitIdx = DAG.getNode( 4557 ISD::AND, DL, XLenVT, Idx, 4558 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4559 } 4560 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4561 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4562 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4563 Vec, ExtractElementIdx); 4564 // Extract the bit from GPR. 4565 SDValue ShiftRight = 4566 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4567 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4568 DAG.getConstant(1, DL, XLenVT)); 4569 } 4570 } 4571 // Otherwise, promote to an i8 vector and extract from that. 4572 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4573 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4574 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4575 } 4576 4577 // If this is a fixed vector, we need to convert it to a scalable vector. 4578 MVT ContainerVT = VecVT; 4579 if (VecVT.isFixedLengthVector()) { 4580 ContainerVT = getContainerForFixedLengthVector(VecVT); 4581 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4582 } 4583 4584 // If the index is 0, the vector is already in the right position. 4585 if (!isNullConstant(Idx)) { 4586 // Use a VL of 1 to avoid processing more elements than we need. 4587 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4588 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4589 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4590 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4591 } 4592 4593 if (!EltVT.isInteger()) { 4594 // Floating-point extracts are handled in TableGen. 4595 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4596 DAG.getConstant(0, DL, XLenVT)); 4597 } 4598 4599 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4600 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4601 } 4602 4603 // Some RVV intrinsics may claim that they want an integer operand to be 4604 // promoted or expanded. 4605 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4606 const RISCVSubtarget &Subtarget) { 4607 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4608 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4609 "Unexpected opcode"); 4610 4611 if (!Subtarget.hasVInstructions()) 4612 return SDValue(); 4613 4614 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4615 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4616 SDLoc DL(Op); 4617 4618 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4619 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4620 if (!II || !II->hasScalarOperand()) 4621 return SDValue(); 4622 4623 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4624 assert(SplatOp < Op.getNumOperands()); 4625 4626 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4627 SDValue &ScalarOp = Operands[SplatOp]; 4628 MVT OpVT = ScalarOp.getSimpleValueType(); 4629 MVT XLenVT = Subtarget.getXLenVT(); 4630 4631 // If this isn't a scalar, or its type is XLenVT we're done. 4632 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4633 return SDValue(); 4634 4635 // Simplest case is that the operand needs to be promoted to XLenVT. 4636 if (OpVT.bitsLT(XLenVT)) { 4637 // If the operand is a constant, sign extend to increase our chances 4638 // of being able to use a .vi instruction. ANY_EXTEND would become a 4639 // a zero extend and the simm5 check in isel would fail. 4640 // FIXME: Should we ignore the upper bits in isel instead? 4641 unsigned ExtOpc = 4642 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4643 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4644 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4645 } 4646 4647 // Use the previous operand to get the vXi64 VT. The result might be a mask 4648 // VT for compares. Using the previous operand assumes that the previous 4649 // operand will never have a smaller element size than a scalar operand and 4650 // that a widening operation never uses SEW=64. 4651 // NOTE: If this fails the below assert, we can probably just find the 4652 // element count from any operand or result and use it to construct the VT. 4653 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4654 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4655 4656 // The more complex case is when the scalar is larger than XLenVT. 4657 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4658 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4659 4660 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4661 // instruction to sign-extend since SEW>XLEN. 4662 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4663 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4664 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4665 } 4666 4667 switch (IntNo) { 4668 case Intrinsic::riscv_vslide1up: 4669 case Intrinsic::riscv_vslide1down: 4670 case Intrinsic::riscv_vslide1up_mask: 4671 case Intrinsic::riscv_vslide1down_mask: { 4672 // We need to special case these when the scalar is larger than XLen. 4673 unsigned NumOps = Op.getNumOperands(); 4674 bool IsMasked = NumOps == 7; 4675 4676 // Convert the vector source to the equivalent nxvXi32 vector. 4677 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4678 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4679 4680 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4681 DAG.getConstant(0, DL, XLenVT)); 4682 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4683 DAG.getConstant(1, DL, XLenVT)); 4684 4685 // Double the VL since we halved SEW. 4686 SDValue AVL = getVLOperand(Op); 4687 SDValue I32VL; 4688 4689 // Optimize for constant AVL 4690 if (isa<ConstantSDNode>(AVL)) { 4691 unsigned EltSize = VT.getScalarSizeInBits(); 4692 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4693 4694 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4695 unsigned MaxVLMAX = 4696 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4697 4698 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4699 unsigned MinVLMAX = 4700 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4701 4702 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4703 if (AVLInt <= MinVLMAX) { 4704 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4705 } else if (AVLInt >= 2 * MaxVLMAX) { 4706 // Just set vl to VLMAX in this situation 4707 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4708 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4709 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4710 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4711 SDValue SETVLMAX = DAG.getTargetConstant( 4712 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4713 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4714 LMUL); 4715 } else { 4716 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4717 // is related to the hardware implementation. 4718 // So let the following code handle 4719 } 4720 } 4721 if (!I32VL) { 4722 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4723 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4724 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4725 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4726 SDValue SETVL = 4727 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4728 // Using vsetvli instruction to get actually used length which related to 4729 // the hardware implementation 4730 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4731 SEW, LMUL); 4732 I32VL = 4733 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4734 } 4735 4736 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4737 4738 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4739 // instructions. 4740 SDValue Passthru; 4741 if (IsMasked) 4742 Passthru = DAG.getUNDEF(I32VT); 4743 else 4744 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4745 4746 if (IntNo == Intrinsic::riscv_vslide1up || 4747 IntNo == Intrinsic::riscv_vslide1up_mask) { 4748 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4749 ScalarHi, I32Mask, I32VL); 4750 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4751 ScalarLo, I32Mask, I32VL); 4752 } else { 4753 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4754 ScalarLo, I32Mask, I32VL); 4755 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4756 ScalarHi, I32Mask, I32VL); 4757 } 4758 4759 // Convert back to nxvXi64. 4760 Vec = DAG.getBitcast(VT, Vec); 4761 4762 if (!IsMasked) 4763 return Vec; 4764 // Apply mask after the operation. 4765 SDValue Mask = Operands[NumOps - 3]; 4766 SDValue MaskedOff = Operands[1]; 4767 // Assume Policy operand is the last operand. 4768 uint64_t Policy = 4769 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4770 // We don't need to select maskedoff if it's undef. 4771 if (MaskedOff.isUndef()) 4772 return Vec; 4773 // TAMU 4774 if (Policy == RISCVII::TAIL_AGNOSTIC) 4775 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4776 AVL); 4777 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4778 // It's fine because vmerge does not care mask policy. 4779 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4780 AVL); 4781 } 4782 } 4783 4784 // We need to convert the scalar to a splat vector. 4785 SDValue VL = getVLOperand(Op); 4786 assert(VL.getValueType() == XLenVT); 4787 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4788 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4789 } 4790 4791 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4792 SelectionDAG &DAG) const { 4793 unsigned IntNo = Op.getConstantOperandVal(0); 4794 SDLoc DL(Op); 4795 MVT XLenVT = Subtarget.getXLenVT(); 4796 4797 switch (IntNo) { 4798 default: 4799 break; // Don't custom lower most intrinsics. 4800 case Intrinsic::thread_pointer: { 4801 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4802 return DAG.getRegister(RISCV::X4, PtrVT); 4803 } 4804 case Intrinsic::riscv_orc_b: 4805 case Intrinsic::riscv_brev8: { 4806 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4807 unsigned Opc = 4808 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4809 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4810 DAG.getConstant(7, DL, XLenVT)); 4811 } 4812 case Intrinsic::riscv_grev: 4813 case Intrinsic::riscv_gorc: { 4814 unsigned Opc = 4815 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4816 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4817 } 4818 case Intrinsic::riscv_zip: 4819 case Intrinsic::riscv_unzip: { 4820 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4821 // For i32 the immediate is 15. For i64 the immediate is 31. 4822 unsigned Opc = 4823 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4824 unsigned BitWidth = Op.getValueSizeInBits(); 4825 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4826 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4827 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4828 } 4829 case Intrinsic::riscv_shfl: 4830 case Intrinsic::riscv_unshfl: { 4831 unsigned Opc = 4832 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4833 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4834 } 4835 case Intrinsic::riscv_bcompress: 4836 case Intrinsic::riscv_bdecompress: { 4837 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4838 : RISCVISD::BDECOMPRESS; 4839 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4840 } 4841 case Intrinsic::riscv_bfp: 4842 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4843 Op.getOperand(2)); 4844 case Intrinsic::riscv_fsl: 4845 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4846 Op.getOperand(2), Op.getOperand(3)); 4847 case Intrinsic::riscv_fsr: 4848 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4849 Op.getOperand(2), Op.getOperand(3)); 4850 case Intrinsic::riscv_vmv_x_s: 4851 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4852 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4853 Op.getOperand(1)); 4854 case Intrinsic::riscv_vmv_v_x: 4855 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4856 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4857 Subtarget); 4858 case Intrinsic::riscv_vfmv_v_f: 4859 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4860 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4861 case Intrinsic::riscv_vmv_s_x: { 4862 SDValue Scalar = Op.getOperand(2); 4863 4864 if (Scalar.getValueType().bitsLE(XLenVT)) { 4865 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4866 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4867 Op.getOperand(1), Scalar, Op.getOperand(3)); 4868 } 4869 4870 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4871 4872 // This is an i64 value that lives in two scalar registers. We have to 4873 // insert this in a convoluted way. First we build vXi64 splat containing 4874 // the two values that we assemble using some bit math. Next we'll use 4875 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4876 // to merge element 0 from our splat into the source vector. 4877 // FIXME: This is probably not the best way to do this, but it is 4878 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4879 // point. 4880 // sw lo, (a0) 4881 // sw hi, 4(a0) 4882 // vlse vX, (a0) 4883 // 4884 // vid.v vVid 4885 // vmseq.vx mMask, vVid, 0 4886 // vmerge.vvm vDest, vSrc, vVal, mMask 4887 MVT VT = Op.getSimpleValueType(); 4888 SDValue Vec = Op.getOperand(1); 4889 SDValue VL = getVLOperand(Op); 4890 4891 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4892 if (Op.getOperand(1).isUndef()) 4893 return SplattedVal; 4894 SDValue SplattedIdx = 4895 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4896 DAG.getConstant(0, DL, MVT::i32), VL); 4897 4898 MVT MaskVT = getMaskTypeFor(VT); 4899 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4900 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4901 SDValue SelectCond = 4902 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4903 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4904 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4905 Vec, VL); 4906 } 4907 } 4908 4909 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4910 } 4911 4912 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4913 SelectionDAG &DAG) const { 4914 unsigned IntNo = Op.getConstantOperandVal(1); 4915 switch (IntNo) { 4916 default: 4917 break; 4918 case Intrinsic::riscv_masked_strided_load: { 4919 SDLoc DL(Op); 4920 MVT XLenVT = Subtarget.getXLenVT(); 4921 4922 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4923 // the selection of the masked intrinsics doesn't do this for us. 4924 SDValue Mask = Op.getOperand(5); 4925 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4926 4927 MVT VT = Op->getSimpleValueType(0); 4928 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4929 4930 SDValue PassThru = Op.getOperand(2); 4931 if (!IsUnmasked) { 4932 MVT MaskVT = getMaskTypeFor(ContainerVT); 4933 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4934 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4935 } 4936 4937 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4938 4939 SDValue IntID = DAG.getTargetConstant( 4940 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4941 XLenVT); 4942 4943 auto *Load = cast<MemIntrinsicSDNode>(Op); 4944 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4945 if (IsUnmasked) 4946 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4947 else 4948 Ops.push_back(PassThru); 4949 Ops.push_back(Op.getOperand(3)); // Ptr 4950 Ops.push_back(Op.getOperand(4)); // Stride 4951 if (!IsUnmasked) 4952 Ops.push_back(Mask); 4953 Ops.push_back(VL); 4954 if (!IsUnmasked) { 4955 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4956 Ops.push_back(Policy); 4957 } 4958 4959 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4960 SDValue Result = 4961 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4962 Load->getMemoryVT(), Load->getMemOperand()); 4963 SDValue Chain = Result.getValue(1); 4964 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4965 return DAG.getMergeValues({Result, Chain}, DL); 4966 } 4967 case Intrinsic::riscv_seg2_load: 4968 case Intrinsic::riscv_seg3_load: 4969 case Intrinsic::riscv_seg4_load: 4970 case Intrinsic::riscv_seg5_load: 4971 case Intrinsic::riscv_seg6_load: 4972 case Intrinsic::riscv_seg7_load: 4973 case Intrinsic::riscv_seg8_load: { 4974 SDLoc DL(Op); 4975 static const Intrinsic::ID VlsegInts[7] = { 4976 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4977 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4978 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4979 Intrinsic::riscv_vlseg8}; 4980 unsigned NF = Op->getNumValues() - 1; 4981 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4982 MVT XLenVT = Subtarget.getXLenVT(); 4983 MVT VT = Op->getSimpleValueType(0); 4984 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4985 4986 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4987 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4988 auto *Load = cast<MemIntrinsicSDNode>(Op); 4989 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4990 ContainerVTs.push_back(MVT::Other); 4991 SDVTList VTs = DAG.getVTList(ContainerVTs); 4992 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4993 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4994 Ops.push_back(Op.getOperand(2)); 4995 Ops.push_back(VL); 4996 SDValue Result = 4997 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4998 Load->getMemoryVT(), Load->getMemOperand()); 4999 SmallVector<SDValue, 9> Results; 5000 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5001 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5002 DAG, Subtarget)); 5003 Results.push_back(Result.getValue(NF)); 5004 return DAG.getMergeValues(Results, DL); 5005 } 5006 } 5007 5008 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5009 } 5010 5011 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5012 SelectionDAG &DAG) const { 5013 unsigned IntNo = Op.getConstantOperandVal(1); 5014 switch (IntNo) { 5015 default: 5016 break; 5017 case Intrinsic::riscv_masked_strided_store: { 5018 SDLoc DL(Op); 5019 MVT XLenVT = Subtarget.getXLenVT(); 5020 5021 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5022 // the selection of the masked intrinsics doesn't do this for us. 5023 SDValue Mask = Op.getOperand(5); 5024 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5025 5026 SDValue Val = Op.getOperand(2); 5027 MVT VT = Val.getSimpleValueType(); 5028 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5029 5030 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5031 if (!IsUnmasked) { 5032 MVT MaskVT = getMaskTypeFor(ContainerVT); 5033 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5034 } 5035 5036 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5037 5038 SDValue IntID = DAG.getTargetConstant( 5039 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5040 XLenVT); 5041 5042 auto *Store = cast<MemIntrinsicSDNode>(Op); 5043 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5044 Ops.push_back(Val); 5045 Ops.push_back(Op.getOperand(3)); // Ptr 5046 Ops.push_back(Op.getOperand(4)); // Stride 5047 if (!IsUnmasked) 5048 Ops.push_back(Mask); 5049 Ops.push_back(VL); 5050 5051 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5052 Ops, Store->getMemoryVT(), 5053 Store->getMemOperand()); 5054 } 5055 } 5056 5057 return SDValue(); 5058 } 5059 5060 static MVT getLMUL1VT(MVT VT) { 5061 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5062 "Unexpected vector MVT"); 5063 return MVT::getScalableVectorVT( 5064 VT.getVectorElementType(), 5065 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5066 } 5067 5068 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5069 switch (ISDOpcode) { 5070 default: 5071 llvm_unreachable("Unhandled reduction"); 5072 case ISD::VECREDUCE_ADD: 5073 return RISCVISD::VECREDUCE_ADD_VL; 5074 case ISD::VECREDUCE_UMAX: 5075 return RISCVISD::VECREDUCE_UMAX_VL; 5076 case ISD::VECREDUCE_SMAX: 5077 return RISCVISD::VECREDUCE_SMAX_VL; 5078 case ISD::VECREDUCE_UMIN: 5079 return RISCVISD::VECREDUCE_UMIN_VL; 5080 case ISD::VECREDUCE_SMIN: 5081 return RISCVISD::VECREDUCE_SMIN_VL; 5082 case ISD::VECREDUCE_AND: 5083 return RISCVISD::VECREDUCE_AND_VL; 5084 case ISD::VECREDUCE_OR: 5085 return RISCVISD::VECREDUCE_OR_VL; 5086 case ISD::VECREDUCE_XOR: 5087 return RISCVISD::VECREDUCE_XOR_VL; 5088 } 5089 } 5090 5091 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5092 SelectionDAG &DAG, 5093 bool IsVP) const { 5094 SDLoc DL(Op); 5095 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5096 MVT VecVT = Vec.getSimpleValueType(); 5097 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5098 Op.getOpcode() == ISD::VECREDUCE_OR || 5099 Op.getOpcode() == ISD::VECREDUCE_XOR || 5100 Op.getOpcode() == ISD::VP_REDUCE_AND || 5101 Op.getOpcode() == ISD::VP_REDUCE_OR || 5102 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5103 "Unexpected reduction lowering"); 5104 5105 MVT XLenVT = Subtarget.getXLenVT(); 5106 assert(Op.getValueType() == XLenVT && 5107 "Expected reduction output to be legalized to XLenVT"); 5108 5109 MVT ContainerVT = VecVT; 5110 if (VecVT.isFixedLengthVector()) { 5111 ContainerVT = getContainerForFixedLengthVector(VecVT); 5112 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5113 } 5114 5115 SDValue Mask, VL; 5116 if (IsVP) { 5117 Mask = Op.getOperand(2); 5118 VL = Op.getOperand(3); 5119 } else { 5120 std::tie(Mask, VL) = 5121 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5122 } 5123 5124 unsigned BaseOpc; 5125 ISD::CondCode CC; 5126 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5127 5128 switch (Op.getOpcode()) { 5129 default: 5130 llvm_unreachable("Unhandled reduction"); 5131 case ISD::VECREDUCE_AND: 5132 case ISD::VP_REDUCE_AND: { 5133 // vcpop ~x == 0 5134 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5135 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5136 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5137 CC = ISD::SETEQ; 5138 BaseOpc = ISD::AND; 5139 break; 5140 } 5141 case ISD::VECREDUCE_OR: 5142 case ISD::VP_REDUCE_OR: 5143 // vcpop x != 0 5144 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5145 CC = ISD::SETNE; 5146 BaseOpc = ISD::OR; 5147 break; 5148 case ISD::VECREDUCE_XOR: 5149 case ISD::VP_REDUCE_XOR: { 5150 // ((vcpop x) & 1) != 0 5151 SDValue One = DAG.getConstant(1, DL, XLenVT); 5152 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5153 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5154 CC = ISD::SETNE; 5155 BaseOpc = ISD::XOR; 5156 break; 5157 } 5158 } 5159 5160 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5161 5162 if (!IsVP) 5163 return SetCC; 5164 5165 // Now include the start value in the operation. 5166 // Note that we must return the start value when no elements are operated 5167 // upon. The vcpop instructions we've emitted in each case above will return 5168 // 0 for an inactive vector, and so we've already received the neutral value: 5169 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5170 // can simply include the start value. 5171 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5172 } 5173 5174 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5175 SelectionDAG &DAG) const { 5176 SDLoc DL(Op); 5177 SDValue Vec = Op.getOperand(0); 5178 EVT VecEVT = Vec.getValueType(); 5179 5180 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5181 5182 // Due to ordering in legalize types we may have a vector type that needs to 5183 // be split. Do that manually so we can get down to a legal type. 5184 while (getTypeAction(*DAG.getContext(), VecEVT) == 5185 TargetLowering::TypeSplitVector) { 5186 SDValue Lo, Hi; 5187 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5188 VecEVT = Lo.getValueType(); 5189 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5190 } 5191 5192 // TODO: The type may need to be widened rather than split. Or widened before 5193 // it can be split. 5194 if (!isTypeLegal(VecEVT)) 5195 return SDValue(); 5196 5197 MVT VecVT = VecEVT.getSimpleVT(); 5198 MVT VecEltVT = VecVT.getVectorElementType(); 5199 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5200 5201 MVT ContainerVT = VecVT; 5202 if (VecVT.isFixedLengthVector()) { 5203 ContainerVT = getContainerForFixedLengthVector(VecVT); 5204 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5205 } 5206 5207 MVT M1VT = getLMUL1VT(ContainerVT); 5208 MVT XLenVT = Subtarget.getXLenVT(); 5209 5210 SDValue Mask, VL; 5211 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5212 5213 SDValue NeutralElem = 5214 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5215 SDValue IdentitySplat = 5216 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5217 M1VT, DL, DAG, Subtarget); 5218 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5219 IdentitySplat, Mask, VL); 5220 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5221 DAG.getConstant(0, DL, XLenVT)); 5222 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5223 } 5224 5225 // Given a reduction op, this function returns the matching reduction opcode, 5226 // the vector SDValue and the scalar SDValue required to lower this to a 5227 // RISCVISD node. 5228 static std::tuple<unsigned, SDValue, SDValue> 5229 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5230 SDLoc DL(Op); 5231 auto Flags = Op->getFlags(); 5232 unsigned Opcode = Op.getOpcode(); 5233 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5234 switch (Opcode) { 5235 default: 5236 llvm_unreachable("Unhandled reduction"); 5237 case ISD::VECREDUCE_FADD: { 5238 // Use positive zero if we can. It is cheaper to materialize. 5239 SDValue Zero = 5240 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5241 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5242 } 5243 case ISD::VECREDUCE_SEQ_FADD: 5244 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5245 Op.getOperand(0)); 5246 case ISD::VECREDUCE_FMIN: 5247 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5248 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5249 case ISD::VECREDUCE_FMAX: 5250 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5251 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5252 } 5253 } 5254 5255 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5256 SelectionDAG &DAG) const { 5257 SDLoc DL(Op); 5258 MVT VecEltVT = Op.getSimpleValueType(); 5259 5260 unsigned RVVOpcode; 5261 SDValue VectorVal, ScalarVal; 5262 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5263 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5264 MVT VecVT = VectorVal.getSimpleValueType(); 5265 5266 MVT ContainerVT = VecVT; 5267 if (VecVT.isFixedLengthVector()) { 5268 ContainerVT = getContainerForFixedLengthVector(VecVT); 5269 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5270 } 5271 5272 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5273 MVT XLenVT = Subtarget.getXLenVT(); 5274 5275 SDValue Mask, VL; 5276 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5277 5278 SDValue ScalarSplat = 5279 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5280 M1VT, DL, DAG, Subtarget); 5281 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5282 VectorVal, ScalarSplat, Mask, VL); 5283 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5284 DAG.getConstant(0, DL, XLenVT)); 5285 } 5286 5287 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5288 switch (ISDOpcode) { 5289 default: 5290 llvm_unreachable("Unhandled reduction"); 5291 case ISD::VP_REDUCE_ADD: 5292 return RISCVISD::VECREDUCE_ADD_VL; 5293 case ISD::VP_REDUCE_UMAX: 5294 return RISCVISD::VECREDUCE_UMAX_VL; 5295 case ISD::VP_REDUCE_SMAX: 5296 return RISCVISD::VECREDUCE_SMAX_VL; 5297 case ISD::VP_REDUCE_UMIN: 5298 return RISCVISD::VECREDUCE_UMIN_VL; 5299 case ISD::VP_REDUCE_SMIN: 5300 return RISCVISD::VECREDUCE_SMIN_VL; 5301 case ISD::VP_REDUCE_AND: 5302 return RISCVISD::VECREDUCE_AND_VL; 5303 case ISD::VP_REDUCE_OR: 5304 return RISCVISD::VECREDUCE_OR_VL; 5305 case ISD::VP_REDUCE_XOR: 5306 return RISCVISD::VECREDUCE_XOR_VL; 5307 case ISD::VP_REDUCE_FADD: 5308 return RISCVISD::VECREDUCE_FADD_VL; 5309 case ISD::VP_REDUCE_SEQ_FADD: 5310 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5311 case ISD::VP_REDUCE_FMAX: 5312 return RISCVISD::VECREDUCE_FMAX_VL; 5313 case ISD::VP_REDUCE_FMIN: 5314 return RISCVISD::VECREDUCE_FMIN_VL; 5315 } 5316 } 5317 5318 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5319 SelectionDAG &DAG) const { 5320 SDLoc DL(Op); 5321 SDValue Vec = Op.getOperand(1); 5322 EVT VecEVT = Vec.getValueType(); 5323 5324 // TODO: The type may need to be widened rather than split. Or widened before 5325 // it can be split. 5326 if (!isTypeLegal(VecEVT)) 5327 return SDValue(); 5328 5329 MVT VecVT = VecEVT.getSimpleVT(); 5330 MVT VecEltVT = VecVT.getVectorElementType(); 5331 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5332 5333 MVT ContainerVT = VecVT; 5334 if (VecVT.isFixedLengthVector()) { 5335 ContainerVT = getContainerForFixedLengthVector(VecVT); 5336 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5337 } 5338 5339 SDValue VL = Op.getOperand(3); 5340 SDValue Mask = Op.getOperand(2); 5341 5342 MVT M1VT = getLMUL1VT(ContainerVT); 5343 MVT XLenVT = Subtarget.getXLenVT(); 5344 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5345 5346 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5347 DAG.getConstant(1, DL, XLenVT), M1VT, 5348 DL, DAG, Subtarget); 5349 SDValue Reduction = 5350 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5351 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5352 DAG.getConstant(0, DL, XLenVT)); 5353 if (!VecVT.isInteger()) 5354 return Elt0; 5355 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5356 } 5357 5358 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5359 SelectionDAG &DAG) const { 5360 SDValue Vec = Op.getOperand(0); 5361 SDValue SubVec = Op.getOperand(1); 5362 MVT VecVT = Vec.getSimpleValueType(); 5363 MVT SubVecVT = SubVec.getSimpleValueType(); 5364 5365 SDLoc DL(Op); 5366 MVT XLenVT = Subtarget.getXLenVT(); 5367 unsigned OrigIdx = Op.getConstantOperandVal(2); 5368 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5369 5370 // We don't have the ability to slide mask vectors up indexed by their i1 5371 // elements; the smallest we can do is i8. Often we are able to bitcast to 5372 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5373 // into a scalable one, we might not necessarily have enough scalable 5374 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5375 if (SubVecVT.getVectorElementType() == MVT::i1 && 5376 (OrigIdx != 0 || !Vec.isUndef())) { 5377 if (VecVT.getVectorMinNumElements() >= 8 && 5378 SubVecVT.getVectorMinNumElements() >= 8) { 5379 assert(OrigIdx % 8 == 0 && "Invalid index"); 5380 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5381 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5382 "Unexpected mask vector lowering"); 5383 OrigIdx /= 8; 5384 SubVecVT = 5385 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5386 SubVecVT.isScalableVector()); 5387 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5388 VecVT.isScalableVector()); 5389 Vec = DAG.getBitcast(VecVT, Vec); 5390 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5391 } else { 5392 // We can't slide this mask vector up indexed by its i1 elements. 5393 // This poses a problem when we wish to insert a scalable vector which 5394 // can't be re-expressed as a larger type. Just choose the slow path and 5395 // extend to a larger type, then truncate back down. 5396 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5397 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5398 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5399 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5400 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5401 Op.getOperand(2)); 5402 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5403 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5404 } 5405 } 5406 5407 // If the subvector vector is a fixed-length type, we cannot use subregister 5408 // manipulation to simplify the codegen; we don't know which register of a 5409 // LMUL group contains the specific subvector as we only know the minimum 5410 // register size. Therefore we must slide the vector group up the full 5411 // amount. 5412 if (SubVecVT.isFixedLengthVector()) { 5413 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5414 return Op; 5415 MVT ContainerVT = VecVT; 5416 if (VecVT.isFixedLengthVector()) { 5417 ContainerVT = getContainerForFixedLengthVector(VecVT); 5418 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5419 } 5420 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5421 DAG.getUNDEF(ContainerVT), SubVec, 5422 DAG.getConstant(0, DL, XLenVT)); 5423 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5424 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5425 return DAG.getBitcast(Op.getValueType(), SubVec); 5426 } 5427 SDValue Mask = 5428 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5429 // Set the vector length to only the number of elements we care about. Note 5430 // that for slideup this includes the offset. 5431 SDValue VL = 5432 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5433 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5434 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5435 SubVec, SlideupAmt, Mask, VL); 5436 if (VecVT.isFixedLengthVector()) 5437 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5438 return DAG.getBitcast(Op.getValueType(), Slideup); 5439 } 5440 5441 unsigned SubRegIdx, RemIdx; 5442 std::tie(SubRegIdx, RemIdx) = 5443 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5444 VecVT, SubVecVT, OrigIdx, TRI); 5445 5446 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5447 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5448 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5449 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5450 5451 // 1. If the Idx has been completely eliminated and this subvector's size is 5452 // a vector register or a multiple thereof, or the surrounding elements are 5453 // undef, then this is a subvector insert which naturally aligns to a vector 5454 // register. These can easily be handled using subregister manipulation. 5455 // 2. If the subvector is smaller than a vector register, then the insertion 5456 // must preserve the undisturbed elements of the register. We do this by 5457 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5458 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5459 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5460 // LMUL=1 type back into the larger vector (resolving to another subregister 5461 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5462 // to avoid allocating a large register group to hold our subvector. 5463 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5464 return Op; 5465 5466 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5467 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5468 // (in our case undisturbed). This means we can set up a subvector insertion 5469 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5470 // size of the subvector. 5471 MVT InterSubVT = VecVT; 5472 SDValue AlignedExtract = Vec; 5473 unsigned AlignedIdx = OrigIdx - RemIdx; 5474 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5475 InterSubVT = getLMUL1VT(VecVT); 5476 // Extract a subvector equal to the nearest full vector register type. This 5477 // should resolve to a EXTRACT_SUBREG instruction. 5478 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5479 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5480 } 5481 5482 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5483 // For scalable vectors this must be further multiplied by vscale. 5484 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5485 5486 SDValue Mask, VL; 5487 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5488 5489 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5490 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5491 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5492 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5493 5494 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5495 DAG.getUNDEF(InterSubVT), SubVec, 5496 DAG.getConstant(0, DL, XLenVT)); 5497 5498 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5499 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5500 5501 // If required, insert this subvector back into the correct vector register. 5502 // This should resolve to an INSERT_SUBREG instruction. 5503 if (VecVT.bitsGT(InterSubVT)) 5504 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5505 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5506 5507 // We might have bitcast from a mask type: cast back to the original type if 5508 // required. 5509 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5510 } 5511 5512 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5513 SelectionDAG &DAG) const { 5514 SDValue Vec = Op.getOperand(0); 5515 MVT SubVecVT = Op.getSimpleValueType(); 5516 MVT VecVT = Vec.getSimpleValueType(); 5517 5518 SDLoc DL(Op); 5519 MVT XLenVT = Subtarget.getXLenVT(); 5520 unsigned OrigIdx = Op.getConstantOperandVal(1); 5521 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5522 5523 // We don't have the ability to slide mask vectors down indexed by their i1 5524 // elements; the smallest we can do is i8. Often we are able to bitcast to 5525 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5526 // from a scalable one, we might not necessarily have enough scalable 5527 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5528 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5529 if (VecVT.getVectorMinNumElements() >= 8 && 5530 SubVecVT.getVectorMinNumElements() >= 8) { 5531 assert(OrigIdx % 8 == 0 && "Invalid index"); 5532 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5533 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5534 "Unexpected mask vector lowering"); 5535 OrigIdx /= 8; 5536 SubVecVT = 5537 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5538 SubVecVT.isScalableVector()); 5539 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5540 VecVT.isScalableVector()); 5541 Vec = DAG.getBitcast(VecVT, Vec); 5542 } else { 5543 // We can't slide this mask vector down, indexed by its i1 elements. 5544 // This poses a problem when we wish to extract a scalable vector which 5545 // can't be re-expressed as a larger type. Just choose the slow path and 5546 // extend to a larger type, then truncate back down. 5547 // TODO: We could probably improve this when extracting certain fixed 5548 // from fixed, where we can extract as i8 and shift the correct element 5549 // right to reach the desired subvector? 5550 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5551 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5552 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5553 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5554 Op.getOperand(1)); 5555 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5556 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5557 } 5558 } 5559 5560 // If the subvector vector is a fixed-length type, we cannot use subregister 5561 // manipulation to simplify the codegen; we don't know which register of a 5562 // LMUL group contains the specific subvector as we only know the minimum 5563 // register size. Therefore we must slide the vector group down the full 5564 // amount. 5565 if (SubVecVT.isFixedLengthVector()) { 5566 // With an index of 0 this is a cast-like subvector, which can be performed 5567 // with subregister operations. 5568 if (OrigIdx == 0) 5569 return Op; 5570 MVT ContainerVT = VecVT; 5571 if (VecVT.isFixedLengthVector()) { 5572 ContainerVT = getContainerForFixedLengthVector(VecVT); 5573 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5574 } 5575 SDValue Mask = 5576 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5577 // Set the vector length to only the number of elements we care about. This 5578 // avoids sliding down elements we're going to discard straight away. 5579 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5580 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5581 SDValue Slidedown = 5582 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5583 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5584 // Now we can use a cast-like subvector extract to get the result. 5585 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5586 DAG.getConstant(0, DL, XLenVT)); 5587 return DAG.getBitcast(Op.getValueType(), Slidedown); 5588 } 5589 5590 unsigned SubRegIdx, RemIdx; 5591 std::tie(SubRegIdx, RemIdx) = 5592 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5593 VecVT, SubVecVT, OrigIdx, TRI); 5594 5595 // If the Idx has been completely eliminated then this is a subvector extract 5596 // which naturally aligns to a vector register. These can easily be handled 5597 // using subregister manipulation. 5598 if (RemIdx == 0) 5599 return Op; 5600 5601 // Else we must shift our vector register directly to extract the subvector. 5602 // Do this using VSLIDEDOWN. 5603 5604 // If the vector type is an LMUL-group type, extract a subvector equal to the 5605 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5606 // instruction. 5607 MVT InterSubVT = VecVT; 5608 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5609 InterSubVT = getLMUL1VT(VecVT); 5610 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5611 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5612 } 5613 5614 // Slide this vector register down by the desired number of elements in order 5615 // to place the desired subvector starting at element 0. 5616 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5617 // For scalable vectors this must be further multiplied by vscale. 5618 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5619 5620 SDValue Mask, VL; 5621 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5622 SDValue Slidedown = 5623 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5624 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5625 5626 // Now the vector is in the right position, extract our final subvector. This 5627 // should resolve to a COPY. 5628 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5629 DAG.getConstant(0, DL, XLenVT)); 5630 5631 // We might have bitcast from a mask type: cast back to the original type if 5632 // required. 5633 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5634 } 5635 5636 // Lower step_vector to the vid instruction. Any non-identity step value must 5637 // be accounted for my manual expansion. 5638 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5639 SelectionDAG &DAG) const { 5640 SDLoc DL(Op); 5641 MVT VT = Op.getSimpleValueType(); 5642 MVT XLenVT = Subtarget.getXLenVT(); 5643 SDValue Mask, VL; 5644 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5645 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5646 uint64_t StepValImm = Op.getConstantOperandVal(0); 5647 if (StepValImm != 1) { 5648 if (isPowerOf2_64(StepValImm)) { 5649 SDValue StepVal = 5650 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5651 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5652 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5653 } else { 5654 SDValue StepVal = lowerScalarSplat( 5655 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5656 VL, VT, DL, DAG, Subtarget); 5657 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5658 } 5659 } 5660 return StepVec; 5661 } 5662 5663 // Implement vector_reverse using vrgather.vv with indices determined by 5664 // subtracting the id of each element from (VLMAX-1). This will convert 5665 // the indices like so: 5666 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5667 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5668 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5669 SelectionDAG &DAG) const { 5670 SDLoc DL(Op); 5671 MVT VecVT = Op.getSimpleValueType(); 5672 if (VecVT.getVectorElementType() == MVT::i1) { 5673 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5674 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5675 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5676 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5677 } 5678 unsigned EltSize = VecVT.getScalarSizeInBits(); 5679 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5680 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5681 unsigned MaxVLMAX = 5682 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5683 5684 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5685 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5686 5687 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5688 // to use vrgatherei16.vv. 5689 // TODO: It's also possible to use vrgatherei16.vv for other types to 5690 // decrease register width for the index calculation. 5691 if (MaxVLMAX > 256 && EltSize == 8) { 5692 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5693 // Reverse each half, then reassemble them in reverse order. 5694 // NOTE: It's also possible that after splitting that VLMAX no longer 5695 // requires vrgatherei16.vv. 5696 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5697 SDValue Lo, Hi; 5698 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5699 EVT LoVT, HiVT; 5700 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5701 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5702 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5703 // Reassemble the low and high pieces reversed. 5704 // FIXME: This is a CONCAT_VECTORS. 5705 SDValue Res = 5706 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5707 DAG.getIntPtrConstant(0, DL)); 5708 return DAG.getNode( 5709 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5710 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5711 } 5712 5713 // Just promote the int type to i16 which will double the LMUL. 5714 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5715 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5716 } 5717 5718 MVT XLenVT = Subtarget.getXLenVT(); 5719 SDValue Mask, VL; 5720 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5721 5722 // Calculate VLMAX-1 for the desired SEW. 5723 unsigned MinElts = VecVT.getVectorMinNumElements(); 5724 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5725 DAG.getConstant(MinElts, DL, XLenVT)); 5726 SDValue VLMinus1 = 5727 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5728 5729 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5730 bool IsRV32E64 = 5731 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5732 SDValue SplatVL; 5733 if (!IsRV32E64) 5734 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5735 else 5736 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5737 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5738 5739 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5740 SDValue Indices = 5741 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5742 5743 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5744 DAG.getUNDEF(VecVT), VL); 5745 } 5746 5747 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5748 SelectionDAG &DAG) const { 5749 SDLoc DL(Op); 5750 SDValue V1 = Op.getOperand(0); 5751 SDValue V2 = Op.getOperand(1); 5752 MVT XLenVT = Subtarget.getXLenVT(); 5753 MVT VecVT = Op.getSimpleValueType(); 5754 5755 unsigned MinElts = VecVT.getVectorMinNumElements(); 5756 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5757 DAG.getConstant(MinElts, DL, XLenVT)); 5758 5759 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5760 SDValue DownOffset, UpOffset; 5761 if (ImmValue >= 0) { 5762 // The operand is a TargetConstant, we need to rebuild it as a regular 5763 // constant. 5764 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5765 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5766 } else { 5767 // The operand is a TargetConstant, we need to rebuild it as a regular 5768 // constant rather than negating the original operand. 5769 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5770 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5771 } 5772 5773 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5774 5775 SDValue SlideDown = 5776 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5777 DownOffset, TrueMask, UpOffset); 5778 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5779 TrueMask, 5780 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5781 } 5782 5783 SDValue 5784 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5785 SelectionDAG &DAG) const { 5786 SDLoc DL(Op); 5787 auto *Load = cast<LoadSDNode>(Op); 5788 5789 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5790 Load->getMemoryVT(), 5791 *Load->getMemOperand()) && 5792 "Expecting a correctly-aligned load"); 5793 5794 MVT VT = Op.getSimpleValueType(); 5795 MVT XLenVT = Subtarget.getXLenVT(); 5796 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5797 5798 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5799 5800 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5801 SDValue IntID = DAG.getTargetConstant( 5802 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5803 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5804 if (!IsMaskOp) 5805 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5806 Ops.push_back(Load->getBasePtr()); 5807 Ops.push_back(VL); 5808 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5809 SDValue NewLoad = 5810 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5811 Load->getMemoryVT(), Load->getMemOperand()); 5812 5813 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5814 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5815 } 5816 5817 SDValue 5818 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5819 SelectionDAG &DAG) const { 5820 SDLoc DL(Op); 5821 auto *Store = cast<StoreSDNode>(Op); 5822 5823 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5824 Store->getMemoryVT(), 5825 *Store->getMemOperand()) && 5826 "Expecting a correctly-aligned store"); 5827 5828 SDValue StoreVal = Store->getValue(); 5829 MVT VT = StoreVal.getSimpleValueType(); 5830 MVT XLenVT = Subtarget.getXLenVT(); 5831 5832 // If the size less than a byte, we need to pad with zeros to make a byte. 5833 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5834 VT = MVT::v8i1; 5835 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5836 DAG.getConstant(0, DL, VT), StoreVal, 5837 DAG.getIntPtrConstant(0, DL)); 5838 } 5839 5840 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5841 5842 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5843 5844 SDValue NewValue = 5845 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5846 5847 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5848 SDValue IntID = DAG.getTargetConstant( 5849 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5850 return DAG.getMemIntrinsicNode( 5851 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5852 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5853 Store->getMemoryVT(), Store->getMemOperand()); 5854 } 5855 5856 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5857 SelectionDAG &DAG) const { 5858 SDLoc DL(Op); 5859 MVT VT = Op.getSimpleValueType(); 5860 5861 const auto *MemSD = cast<MemSDNode>(Op); 5862 EVT MemVT = MemSD->getMemoryVT(); 5863 MachineMemOperand *MMO = MemSD->getMemOperand(); 5864 SDValue Chain = MemSD->getChain(); 5865 SDValue BasePtr = MemSD->getBasePtr(); 5866 5867 SDValue Mask, PassThru, VL; 5868 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5869 Mask = VPLoad->getMask(); 5870 PassThru = DAG.getUNDEF(VT); 5871 VL = VPLoad->getVectorLength(); 5872 } else { 5873 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5874 Mask = MLoad->getMask(); 5875 PassThru = MLoad->getPassThru(); 5876 } 5877 5878 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5879 5880 MVT XLenVT = Subtarget.getXLenVT(); 5881 5882 MVT ContainerVT = VT; 5883 if (VT.isFixedLengthVector()) { 5884 ContainerVT = getContainerForFixedLengthVector(VT); 5885 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5886 if (!IsUnmasked) { 5887 MVT MaskVT = getMaskTypeFor(ContainerVT); 5888 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5889 } 5890 } 5891 5892 if (!VL) 5893 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5894 5895 unsigned IntID = 5896 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5897 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5898 if (IsUnmasked) 5899 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5900 else 5901 Ops.push_back(PassThru); 5902 Ops.push_back(BasePtr); 5903 if (!IsUnmasked) 5904 Ops.push_back(Mask); 5905 Ops.push_back(VL); 5906 if (!IsUnmasked) 5907 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5908 5909 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5910 5911 SDValue Result = 5912 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5913 Chain = Result.getValue(1); 5914 5915 if (VT.isFixedLengthVector()) 5916 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5917 5918 return DAG.getMergeValues({Result, Chain}, DL); 5919 } 5920 5921 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5922 SelectionDAG &DAG) const { 5923 SDLoc DL(Op); 5924 5925 const auto *MemSD = cast<MemSDNode>(Op); 5926 EVT MemVT = MemSD->getMemoryVT(); 5927 MachineMemOperand *MMO = MemSD->getMemOperand(); 5928 SDValue Chain = MemSD->getChain(); 5929 SDValue BasePtr = MemSD->getBasePtr(); 5930 SDValue Val, Mask, VL; 5931 5932 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5933 Val = VPStore->getValue(); 5934 Mask = VPStore->getMask(); 5935 VL = VPStore->getVectorLength(); 5936 } else { 5937 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5938 Val = MStore->getValue(); 5939 Mask = MStore->getMask(); 5940 } 5941 5942 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5943 5944 MVT VT = Val.getSimpleValueType(); 5945 MVT XLenVT = Subtarget.getXLenVT(); 5946 5947 MVT ContainerVT = VT; 5948 if (VT.isFixedLengthVector()) { 5949 ContainerVT = getContainerForFixedLengthVector(VT); 5950 5951 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5952 if (!IsUnmasked) { 5953 MVT MaskVT = getMaskTypeFor(ContainerVT); 5954 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5955 } 5956 } 5957 5958 if (!VL) 5959 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5960 5961 unsigned IntID = 5962 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5963 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5964 Ops.push_back(Val); 5965 Ops.push_back(BasePtr); 5966 if (!IsUnmasked) 5967 Ops.push_back(Mask); 5968 Ops.push_back(VL); 5969 5970 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5971 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5972 } 5973 5974 SDValue 5975 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5976 SelectionDAG &DAG) const { 5977 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5978 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5979 5980 MVT VT = Op.getSimpleValueType(); 5981 5982 SDValue Op1 = 5983 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5984 SDValue Op2 = 5985 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5986 5987 SDLoc DL(Op); 5988 SDValue VL = 5989 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5990 5991 MVT MaskVT = getMaskTypeFor(ContainerVT); 5992 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5993 5994 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5995 Op.getOperand(2), Mask, VL); 5996 5997 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5998 } 5999 6000 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6001 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6002 MVT VT = Op.getSimpleValueType(); 6003 6004 if (VT.getVectorElementType() == MVT::i1) 6005 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 6006 6007 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 6008 } 6009 6010 SDValue 6011 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6012 SelectionDAG &DAG) const { 6013 unsigned Opc; 6014 switch (Op.getOpcode()) { 6015 default: llvm_unreachable("Unexpected opcode!"); 6016 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6017 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6018 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6019 } 6020 6021 return lowerToScalableOp(Op, DAG, Opc); 6022 } 6023 6024 // Lower vector ABS to smax(X, sub(0, X)). 6025 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6026 SDLoc DL(Op); 6027 MVT VT = Op.getSimpleValueType(); 6028 SDValue X = Op.getOperand(0); 6029 6030 assert(VT.isFixedLengthVector() && "Unexpected type"); 6031 6032 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6033 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6034 6035 SDValue Mask, VL; 6036 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6037 6038 SDValue SplatZero = DAG.getNode( 6039 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6040 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6041 SDValue NegX = 6042 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6043 SDValue Max = 6044 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6045 6046 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6047 } 6048 6049 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6050 SDValue Op, SelectionDAG &DAG) const { 6051 SDLoc DL(Op); 6052 MVT VT = Op.getSimpleValueType(); 6053 SDValue Mag = Op.getOperand(0); 6054 SDValue Sign = Op.getOperand(1); 6055 assert(Mag.getValueType() == Sign.getValueType() && 6056 "Can only handle COPYSIGN with matching types."); 6057 6058 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6059 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6060 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6061 6062 SDValue Mask, VL; 6063 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6064 6065 SDValue CopySign = 6066 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6067 6068 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6069 } 6070 6071 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6072 SDValue Op, SelectionDAG &DAG) const { 6073 MVT VT = Op.getSimpleValueType(); 6074 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6075 6076 MVT I1ContainerVT = 6077 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6078 6079 SDValue CC = 6080 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6081 SDValue Op1 = 6082 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6083 SDValue Op2 = 6084 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6085 6086 SDLoc DL(Op); 6087 SDValue Mask, VL; 6088 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6089 6090 SDValue Select = 6091 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6092 6093 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6094 } 6095 6096 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6097 unsigned NewOpc, 6098 bool HasMask) const { 6099 MVT VT = Op.getSimpleValueType(); 6100 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6101 6102 // Create list of operands by converting existing ones to scalable types. 6103 SmallVector<SDValue, 6> Ops; 6104 for (const SDValue &V : Op->op_values()) { 6105 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6106 6107 // Pass through non-vector operands. 6108 if (!V.getValueType().isVector()) { 6109 Ops.push_back(V); 6110 continue; 6111 } 6112 6113 // "cast" fixed length vector to a scalable vector. 6114 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6115 "Only fixed length vectors are supported!"); 6116 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6117 } 6118 6119 SDLoc DL(Op); 6120 SDValue Mask, VL; 6121 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6122 if (HasMask) 6123 Ops.push_back(Mask); 6124 Ops.push_back(VL); 6125 6126 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6127 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6128 } 6129 6130 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6131 // * Operands of each node are assumed to be in the same order. 6132 // * The EVL operand is promoted from i32 to i64 on RV64. 6133 // * Fixed-length vectors are converted to their scalable-vector container 6134 // types. 6135 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6136 unsigned RISCVISDOpc) const { 6137 SDLoc DL(Op); 6138 MVT VT = Op.getSimpleValueType(); 6139 SmallVector<SDValue, 4> Ops; 6140 6141 for (const auto &OpIdx : enumerate(Op->ops())) { 6142 SDValue V = OpIdx.value(); 6143 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6144 // Pass through operands which aren't fixed-length vectors. 6145 if (!V.getValueType().isFixedLengthVector()) { 6146 Ops.push_back(V); 6147 continue; 6148 } 6149 // "cast" fixed length vector to a scalable vector. 6150 MVT OpVT = V.getSimpleValueType(); 6151 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6152 assert(useRVVForFixedLengthVectorVT(OpVT) && 6153 "Only fixed length vectors are supported!"); 6154 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6155 } 6156 6157 if (!VT.isFixedLengthVector()) 6158 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6159 6160 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6161 6162 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6163 6164 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6165 } 6166 6167 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6168 SelectionDAG &DAG) const { 6169 SDLoc DL(Op); 6170 MVT VT = Op.getSimpleValueType(); 6171 6172 SDValue Src = Op.getOperand(0); 6173 // NOTE: Mask is dropped. 6174 SDValue VL = Op.getOperand(2); 6175 6176 MVT ContainerVT = VT; 6177 if (VT.isFixedLengthVector()) { 6178 ContainerVT = getContainerForFixedLengthVector(VT); 6179 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6180 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6181 } 6182 6183 MVT XLenVT = Subtarget.getXLenVT(); 6184 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6185 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6186 DAG.getUNDEF(ContainerVT), Zero, VL); 6187 6188 SDValue SplatValue = DAG.getConstant( 6189 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6190 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6191 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6192 6193 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6194 Splat, ZeroSplat, VL); 6195 if (!VT.isFixedLengthVector()) 6196 return Result; 6197 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6198 } 6199 6200 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6201 SelectionDAG &DAG) const { 6202 SDLoc DL(Op); 6203 MVT VT = Op.getSimpleValueType(); 6204 6205 SDValue Op1 = Op.getOperand(0); 6206 SDValue Op2 = Op.getOperand(1); 6207 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6208 // NOTE: Mask is dropped. 6209 SDValue VL = Op.getOperand(4); 6210 6211 MVT ContainerVT = VT; 6212 if (VT.isFixedLengthVector()) { 6213 ContainerVT = getContainerForFixedLengthVector(VT); 6214 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6215 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6216 } 6217 6218 SDValue Result; 6219 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6220 6221 switch (Condition) { 6222 default: 6223 break; 6224 // X != Y --> (X^Y) 6225 case ISD::SETNE: 6226 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6227 break; 6228 // X == Y --> ~(X^Y) 6229 case ISD::SETEQ: { 6230 SDValue Temp = 6231 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6232 Result = 6233 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6234 break; 6235 } 6236 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6237 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6238 case ISD::SETGT: 6239 case ISD::SETULT: { 6240 SDValue Temp = 6241 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6242 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6243 break; 6244 } 6245 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6246 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6247 case ISD::SETLT: 6248 case ISD::SETUGT: { 6249 SDValue Temp = 6250 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6251 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6252 break; 6253 } 6254 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6255 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6256 case ISD::SETGE: 6257 case ISD::SETULE: { 6258 SDValue Temp = 6259 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6260 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6261 break; 6262 } 6263 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6264 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6265 case ISD::SETLE: 6266 case ISD::SETUGE: { 6267 SDValue Temp = 6268 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6269 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6270 break; 6271 } 6272 } 6273 6274 if (!VT.isFixedLengthVector()) 6275 return Result; 6276 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6277 } 6278 6279 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6280 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6281 unsigned RISCVISDOpc) const { 6282 SDLoc DL(Op); 6283 6284 SDValue Src = Op.getOperand(0); 6285 SDValue Mask = Op.getOperand(1); 6286 SDValue VL = Op.getOperand(2); 6287 6288 MVT DstVT = Op.getSimpleValueType(); 6289 MVT SrcVT = Src.getSimpleValueType(); 6290 if (DstVT.isFixedLengthVector()) { 6291 DstVT = getContainerForFixedLengthVector(DstVT); 6292 SrcVT = getContainerForFixedLengthVector(SrcVT); 6293 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6294 MVT MaskVT = getMaskTypeFor(DstVT); 6295 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6296 } 6297 6298 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6299 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6300 ? RISCVISD::VSEXT_VL 6301 : RISCVISD::VZEXT_VL; 6302 6303 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6304 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6305 6306 SDValue Result; 6307 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6308 if (SrcVT.isInteger()) { 6309 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6310 6311 // Do we need to do any pre-widening before converting? 6312 if (SrcEltSize == 1) { 6313 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6314 MVT XLenVT = Subtarget.getXLenVT(); 6315 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6316 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6317 DAG.getUNDEF(IntVT), Zero, VL); 6318 SDValue One = DAG.getConstant( 6319 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6320 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6321 DAG.getUNDEF(IntVT), One, VL); 6322 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6323 ZeroSplat, VL); 6324 } else if (DstEltSize > (2 * SrcEltSize)) { 6325 // Widen before converting. 6326 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6327 DstVT.getVectorElementCount()); 6328 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6329 } 6330 6331 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6332 } else { 6333 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6334 "Wrong input/output vector types"); 6335 6336 // Convert f16 to f32 then convert f32 to i64. 6337 if (DstEltSize > (2 * SrcEltSize)) { 6338 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6339 MVT InterimFVT = 6340 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6341 Src = 6342 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6343 } 6344 6345 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6346 } 6347 } else { // Narrowing + Conversion 6348 if (SrcVT.isInteger()) { 6349 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6350 // First do a narrowing convert to an FP type half the size, then round 6351 // the FP type to a small FP type if needed. 6352 6353 MVT InterimFVT = DstVT; 6354 if (SrcEltSize > (2 * DstEltSize)) { 6355 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6356 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6357 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6358 } 6359 6360 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6361 6362 if (InterimFVT != DstVT) { 6363 Src = Result; 6364 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6365 } 6366 } else { 6367 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6368 "Wrong input/output vector types"); 6369 // First do a narrowing conversion to an integer half the size, then 6370 // truncate if needed. 6371 6372 if (DstEltSize == 1) { 6373 // First convert to the same size integer, then convert to mask using 6374 // setcc. 6375 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6376 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6377 DstVT.getVectorElementCount()); 6378 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6379 6380 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6381 // otherwise the conversion was undefined. 6382 MVT XLenVT = Subtarget.getXLenVT(); 6383 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6384 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6385 DAG.getUNDEF(InterimIVT), SplatZero); 6386 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6387 DAG.getCondCode(ISD::SETNE), Mask, VL); 6388 } else { 6389 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6390 DstVT.getVectorElementCount()); 6391 6392 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6393 6394 while (InterimIVT != DstVT) { 6395 SrcEltSize /= 2; 6396 Src = Result; 6397 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6398 DstVT.getVectorElementCount()); 6399 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6400 Src, Mask, VL); 6401 } 6402 } 6403 } 6404 } 6405 6406 MVT VT = Op.getSimpleValueType(); 6407 if (!VT.isFixedLengthVector()) 6408 return Result; 6409 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6410 } 6411 6412 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6413 unsigned MaskOpc, 6414 unsigned VecOpc) const { 6415 MVT VT = Op.getSimpleValueType(); 6416 if (VT.getVectorElementType() != MVT::i1) 6417 return lowerVPOp(Op, DAG, VecOpc); 6418 6419 // It is safe to drop mask parameter as masked-off elements are undef. 6420 SDValue Op1 = Op->getOperand(0); 6421 SDValue Op2 = Op->getOperand(1); 6422 SDValue VL = Op->getOperand(3); 6423 6424 MVT ContainerVT = VT; 6425 const bool IsFixed = VT.isFixedLengthVector(); 6426 if (IsFixed) { 6427 ContainerVT = getContainerForFixedLengthVector(VT); 6428 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6429 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6430 } 6431 6432 SDLoc DL(Op); 6433 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6434 if (!IsFixed) 6435 return Val; 6436 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6437 } 6438 6439 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6440 // matched to a RVV indexed load. The RVV indexed load instructions only 6441 // support the "unsigned unscaled" addressing mode; indices are implicitly 6442 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6443 // signed or scaled indexing is extended to the XLEN value type and scaled 6444 // accordingly. 6445 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6446 SelectionDAG &DAG) const { 6447 SDLoc DL(Op); 6448 MVT VT = Op.getSimpleValueType(); 6449 6450 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6451 EVT MemVT = MemSD->getMemoryVT(); 6452 MachineMemOperand *MMO = MemSD->getMemOperand(); 6453 SDValue Chain = MemSD->getChain(); 6454 SDValue BasePtr = MemSD->getBasePtr(); 6455 6456 ISD::LoadExtType LoadExtType; 6457 SDValue Index, Mask, PassThru, VL; 6458 6459 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6460 Index = VPGN->getIndex(); 6461 Mask = VPGN->getMask(); 6462 PassThru = DAG.getUNDEF(VT); 6463 VL = VPGN->getVectorLength(); 6464 // VP doesn't support extending loads. 6465 LoadExtType = ISD::NON_EXTLOAD; 6466 } else { 6467 // Else it must be a MGATHER. 6468 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6469 Index = MGN->getIndex(); 6470 Mask = MGN->getMask(); 6471 PassThru = MGN->getPassThru(); 6472 LoadExtType = MGN->getExtensionType(); 6473 } 6474 6475 MVT IndexVT = Index.getSimpleValueType(); 6476 MVT XLenVT = Subtarget.getXLenVT(); 6477 6478 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6479 "Unexpected VTs!"); 6480 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6481 // Targets have to explicitly opt-in for extending vector loads. 6482 assert(LoadExtType == ISD::NON_EXTLOAD && 6483 "Unexpected extending MGATHER/VP_GATHER"); 6484 (void)LoadExtType; 6485 6486 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6487 // the selection of the masked intrinsics doesn't do this for us. 6488 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6489 6490 MVT ContainerVT = VT; 6491 if (VT.isFixedLengthVector()) { 6492 ContainerVT = getContainerForFixedLengthVector(VT); 6493 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6494 ContainerVT.getVectorElementCount()); 6495 6496 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6497 6498 if (!IsUnmasked) { 6499 MVT MaskVT = getMaskTypeFor(ContainerVT); 6500 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6501 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6502 } 6503 } 6504 6505 if (!VL) 6506 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6507 6508 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6509 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6510 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6511 VL); 6512 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6513 TrueMask, VL); 6514 } 6515 6516 unsigned IntID = 6517 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6518 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6519 if (IsUnmasked) 6520 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6521 else 6522 Ops.push_back(PassThru); 6523 Ops.push_back(BasePtr); 6524 Ops.push_back(Index); 6525 if (!IsUnmasked) 6526 Ops.push_back(Mask); 6527 Ops.push_back(VL); 6528 if (!IsUnmasked) 6529 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6530 6531 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6532 SDValue Result = 6533 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6534 Chain = Result.getValue(1); 6535 6536 if (VT.isFixedLengthVector()) 6537 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6538 6539 return DAG.getMergeValues({Result, Chain}, DL); 6540 } 6541 6542 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6543 // matched to a RVV indexed store. The RVV indexed store instructions only 6544 // support the "unsigned unscaled" addressing mode; indices are implicitly 6545 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6546 // signed or scaled indexing is extended to the XLEN value type and scaled 6547 // accordingly. 6548 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6549 SelectionDAG &DAG) const { 6550 SDLoc DL(Op); 6551 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6552 EVT MemVT = MemSD->getMemoryVT(); 6553 MachineMemOperand *MMO = MemSD->getMemOperand(); 6554 SDValue Chain = MemSD->getChain(); 6555 SDValue BasePtr = MemSD->getBasePtr(); 6556 6557 bool IsTruncatingStore = false; 6558 SDValue Index, Mask, Val, VL; 6559 6560 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6561 Index = VPSN->getIndex(); 6562 Mask = VPSN->getMask(); 6563 Val = VPSN->getValue(); 6564 VL = VPSN->getVectorLength(); 6565 // VP doesn't support truncating stores. 6566 IsTruncatingStore = false; 6567 } else { 6568 // Else it must be a MSCATTER. 6569 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6570 Index = MSN->getIndex(); 6571 Mask = MSN->getMask(); 6572 Val = MSN->getValue(); 6573 IsTruncatingStore = MSN->isTruncatingStore(); 6574 } 6575 6576 MVT VT = Val.getSimpleValueType(); 6577 MVT IndexVT = Index.getSimpleValueType(); 6578 MVT XLenVT = Subtarget.getXLenVT(); 6579 6580 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6581 "Unexpected VTs!"); 6582 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6583 // Targets have to explicitly opt-in for extending vector loads and 6584 // truncating vector stores. 6585 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6586 (void)IsTruncatingStore; 6587 6588 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6589 // the selection of the masked intrinsics doesn't do this for us. 6590 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6591 6592 MVT ContainerVT = VT; 6593 if (VT.isFixedLengthVector()) { 6594 ContainerVT = getContainerForFixedLengthVector(VT); 6595 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6596 ContainerVT.getVectorElementCount()); 6597 6598 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6599 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6600 6601 if (!IsUnmasked) { 6602 MVT MaskVT = getMaskTypeFor(ContainerVT); 6603 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6604 } 6605 } 6606 6607 if (!VL) 6608 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6609 6610 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6611 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6612 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6613 VL); 6614 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6615 TrueMask, VL); 6616 } 6617 6618 unsigned IntID = 6619 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6620 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6621 Ops.push_back(Val); 6622 Ops.push_back(BasePtr); 6623 Ops.push_back(Index); 6624 if (!IsUnmasked) 6625 Ops.push_back(Mask); 6626 Ops.push_back(VL); 6627 6628 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6629 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6630 } 6631 6632 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6633 SelectionDAG &DAG) const { 6634 const MVT XLenVT = Subtarget.getXLenVT(); 6635 SDLoc DL(Op); 6636 SDValue Chain = Op->getOperand(0); 6637 SDValue SysRegNo = DAG.getTargetConstant( 6638 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6639 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6640 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6641 6642 // Encoding used for rounding mode in RISCV differs from that used in 6643 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6644 // table, which consists of a sequence of 4-bit fields, each representing 6645 // corresponding FLT_ROUNDS mode. 6646 static const int Table = 6647 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6648 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6649 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6650 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6651 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6652 6653 SDValue Shift = 6654 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6655 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6656 DAG.getConstant(Table, DL, XLenVT), Shift); 6657 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6658 DAG.getConstant(7, DL, XLenVT)); 6659 6660 return DAG.getMergeValues({Masked, Chain}, DL); 6661 } 6662 6663 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6664 SelectionDAG &DAG) const { 6665 const MVT XLenVT = Subtarget.getXLenVT(); 6666 SDLoc DL(Op); 6667 SDValue Chain = Op->getOperand(0); 6668 SDValue RMValue = Op->getOperand(1); 6669 SDValue SysRegNo = DAG.getTargetConstant( 6670 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6671 6672 // Encoding used for rounding mode in RISCV differs from that used in 6673 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6674 // a table, which consists of a sequence of 4-bit fields, each representing 6675 // corresponding RISCV mode. 6676 static const unsigned Table = 6677 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6678 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6679 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6680 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6681 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6682 6683 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6684 DAG.getConstant(2, DL, XLenVT)); 6685 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6686 DAG.getConstant(Table, DL, XLenVT), Shift); 6687 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6688 DAG.getConstant(0x7, DL, XLenVT)); 6689 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6690 RMValue); 6691 } 6692 6693 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6694 SelectionDAG &DAG) const { 6695 MachineFunction &MF = DAG.getMachineFunction(); 6696 6697 bool isRISCV64 = Subtarget.is64Bit(); 6698 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6699 6700 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6701 return DAG.getFrameIndex(FI, PtrVT); 6702 } 6703 6704 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6705 switch (IntNo) { 6706 default: 6707 llvm_unreachable("Unexpected Intrinsic"); 6708 case Intrinsic::riscv_bcompress: 6709 return RISCVISD::BCOMPRESSW; 6710 case Intrinsic::riscv_bdecompress: 6711 return RISCVISD::BDECOMPRESSW; 6712 case Intrinsic::riscv_bfp: 6713 return RISCVISD::BFPW; 6714 case Intrinsic::riscv_fsl: 6715 return RISCVISD::FSLW; 6716 case Intrinsic::riscv_fsr: 6717 return RISCVISD::FSRW; 6718 } 6719 } 6720 6721 // Converts the given intrinsic to a i64 operation with any extension. 6722 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6723 unsigned IntNo) { 6724 SDLoc DL(N); 6725 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6726 // Deal with the Instruction Operands 6727 SmallVector<SDValue, 3> NewOps; 6728 for (SDValue Op : drop_begin(N->ops())) 6729 // Promote the operand to i64 type 6730 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6731 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6732 // ReplaceNodeResults requires we maintain the same type for the return value. 6733 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6734 } 6735 6736 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6737 // form of the given Opcode. 6738 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6739 switch (Opcode) { 6740 default: 6741 llvm_unreachable("Unexpected opcode"); 6742 case ISD::SHL: 6743 return RISCVISD::SLLW; 6744 case ISD::SRA: 6745 return RISCVISD::SRAW; 6746 case ISD::SRL: 6747 return RISCVISD::SRLW; 6748 case ISD::SDIV: 6749 return RISCVISD::DIVW; 6750 case ISD::UDIV: 6751 return RISCVISD::DIVUW; 6752 case ISD::UREM: 6753 return RISCVISD::REMUW; 6754 case ISD::ROTL: 6755 return RISCVISD::ROLW; 6756 case ISD::ROTR: 6757 return RISCVISD::RORW; 6758 } 6759 } 6760 6761 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6762 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6763 // otherwise be promoted to i64, making it difficult to select the 6764 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6765 // type i8/i16/i32 is lost. 6766 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6767 unsigned ExtOpc = ISD::ANY_EXTEND) { 6768 SDLoc DL(N); 6769 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6770 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6771 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6772 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6773 // ReplaceNodeResults requires we maintain the same type for the return value. 6774 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6775 } 6776 6777 // Converts the given 32-bit operation to a i64 operation with signed extension 6778 // semantic to reduce the signed extension instructions. 6779 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6780 SDLoc DL(N); 6781 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6782 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6783 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6784 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6785 DAG.getValueType(MVT::i32)); 6786 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6787 } 6788 6789 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6790 SmallVectorImpl<SDValue> &Results, 6791 SelectionDAG &DAG) const { 6792 SDLoc DL(N); 6793 switch (N->getOpcode()) { 6794 default: 6795 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6796 case ISD::STRICT_FP_TO_SINT: 6797 case ISD::STRICT_FP_TO_UINT: 6798 case ISD::FP_TO_SINT: 6799 case ISD::FP_TO_UINT: { 6800 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6801 "Unexpected custom legalisation"); 6802 bool IsStrict = N->isStrictFPOpcode(); 6803 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6804 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6805 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6806 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6807 TargetLowering::TypeSoftenFloat) { 6808 if (!isTypeLegal(Op0.getValueType())) 6809 return; 6810 if (IsStrict) { 6811 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6812 : RISCVISD::STRICT_FCVT_WU_RV64; 6813 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6814 SDValue Res = DAG.getNode( 6815 Opc, DL, VTs, N->getOperand(0), Op0, 6816 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6817 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6818 Results.push_back(Res.getValue(1)); 6819 return; 6820 } 6821 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6822 SDValue Res = 6823 DAG.getNode(Opc, DL, MVT::i64, Op0, 6824 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6825 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6826 return; 6827 } 6828 // If the FP type needs to be softened, emit a library call using the 'si' 6829 // version. If we left it to default legalization we'd end up with 'di'. If 6830 // the FP type doesn't need to be softened just let generic type 6831 // legalization promote the result type. 6832 RTLIB::Libcall LC; 6833 if (IsSigned) 6834 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6835 else 6836 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6837 MakeLibCallOptions CallOptions; 6838 EVT OpVT = Op0.getValueType(); 6839 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6840 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6841 SDValue Result; 6842 std::tie(Result, Chain) = 6843 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6844 Results.push_back(Result); 6845 if (IsStrict) 6846 Results.push_back(Chain); 6847 break; 6848 } 6849 case ISD::READCYCLECOUNTER: { 6850 assert(!Subtarget.is64Bit() && 6851 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6852 6853 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6854 SDValue RCW = 6855 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6856 6857 Results.push_back( 6858 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6859 Results.push_back(RCW.getValue(2)); 6860 break; 6861 } 6862 case ISD::MUL: { 6863 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6864 unsigned XLen = Subtarget.getXLen(); 6865 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6866 if (Size > XLen) { 6867 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6868 SDValue LHS = N->getOperand(0); 6869 SDValue RHS = N->getOperand(1); 6870 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6871 6872 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6873 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6874 // We need exactly one side to be unsigned. 6875 if (LHSIsU == RHSIsU) 6876 return; 6877 6878 auto MakeMULPair = [&](SDValue S, SDValue U) { 6879 MVT XLenVT = Subtarget.getXLenVT(); 6880 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6881 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6882 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6883 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6884 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6885 }; 6886 6887 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6888 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6889 6890 // The other operand should be signed, but still prefer MULH when 6891 // possible. 6892 if (RHSIsU && LHSIsS && !RHSIsS) 6893 Results.push_back(MakeMULPair(LHS, RHS)); 6894 else if (LHSIsU && RHSIsS && !LHSIsS) 6895 Results.push_back(MakeMULPair(RHS, LHS)); 6896 6897 return; 6898 } 6899 LLVM_FALLTHROUGH; 6900 } 6901 case ISD::ADD: 6902 case ISD::SUB: 6903 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6904 "Unexpected custom legalisation"); 6905 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6906 break; 6907 case ISD::SHL: 6908 case ISD::SRA: 6909 case ISD::SRL: 6910 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6911 "Unexpected custom legalisation"); 6912 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6913 // If we can use a BSET instruction, allow default promotion to apply. 6914 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6915 isOneConstant(N->getOperand(0))) 6916 break; 6917 Results.push_back(customLegalizeToWOp(N, DAG)); 6918 break; 6919 } 6920 6921 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6922 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6923 // shift amount. 6924 if (N->getOpcode() == ISD::SHL) { 6925 SDLoc DL(N); 6926 SDValue NewOp0 = 6927 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6928 SDValue NewOp1 = 6929 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6930 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6931 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6932 DAG.getValueType(MVT::i32)); 6933 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6934 } 6935 6936 break; 6937 case ISD::ROTL: 6938 case ISD::ROTR: 6939 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6940 "Unexpected custom legalisation"); 6941 Results.push_back(customLegalizeToWOp(N, DAG)); 6942 break; 6943 case ISD::CTTZ: 6944 case ISD::CTTZ_ZERO_UNDEF: 6945 case ISD::CTLZ: 6946 case ISD::CTLZ_ZERO_UNDEF: { 6947 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6948 "Unexpected custom legalisation"); 6949 6950 SDValue NewOp0 = 6951 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6952 bool IsCTZ = 6953 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6954 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6955 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6956 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6957 return; 6958 } 6959 case ISD::SDIV: 6960 case ISD::UDIV: 6961 case ISD::UREM: { 6962 MVT VT = N->getSimpleValueType(0); 6963 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6964 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6965 "Unexpected custom legalisation"); 6966 // Don't promote division/remainder by constant since we should expand those 6967 // to multiply by magic constant. 6968 // FIXME: What if the expansion is disabled for minsize. 6969 if (N->getOperand(1).getOpcode() == ISD::Constant) 6970 return; 6971 6972 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6973 // the upper 32 bits. For other types we need to sign or zero extend 6974 // based on the opcode. 6975 unsigned ExtOpc = ISD::ANY_EXTEND; 6976 if (VT != MVT::i32) 6977 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6978 : ISD::ZERO_EXTEND; 6979 6980 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6981 break; 6982 } 6983 case ISD::UADDO: 6984 case ISD::USUBO: { 6985 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6986 "Unexpected custom legalisation"); 6987 bool IsAdd = N->getOpcode() == ISD::UADDO; 6988 // Create an ADDW or SUBW. 6989 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6990 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6991 SDValue Res = 6992 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6993 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6994 DAG.getValueType(MVT::i32)); 6995 6996 SDValue Overflow; 6997 if (IsAdd && isOneConstant(RHS)) { 6998 // Special case uaddo X, 1 overflowed if the addition result is 0. 6999 // The general case (X + C) < C is not necessarily beneficial. Although we 7000 // reduce the live range of X, we may introduce the materialization of 7001 // constant C, especially when the setcc result is used by branch. We have 7002 // no compare with constant and branch instructions. 7003 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 7004 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 7005 } else { 7006 // Sign extend the LHS and perform an unsigned compare with the ADDW 7007 // result. Since the inputs are sign extended from i32, this is equivalent 7008 // to comparing the lower 32 bits. 7009 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7010 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 7011 IsAdd ? ISD::SETULT : ISD::SETUGT); 7012 } 7013 7014 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7015 Results.push_back(Overflow); 7016 return; 7017 } 7018 case ISD::UADDSAT: 7019 case ISD::USUBSAT: { 7020 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7021 "Unexpected custom legalisation"); 7022 if (Subtarget.hasStdExtZbb()) { 7023 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7024 // sign extend allows overflow of the lower 32 bits to be detected on 7025 // the promoted size. 7026 SDValue LHS = 7027 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7028 SDValue RHS = 7029 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7030 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7031 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7032 return; 7033 } 7034 7035 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7036 // promotion for UADDO/USUBO. 7037 Results.push_back(expandAddSubSat(N, DAG)); 7038 return; 7039 } 7040 case ISD::ABS: { 7041 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7042 "Unexpected custom legalisation"); 7043 7044 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7045 7046 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7047 7048 // Freeze the source so we can increase it's use count. 7049 Src = DAG.getFreeze(Src); 7050 7051 // Copy sign bit to all bits using the sraiw pattern. 7052 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7053 DAG.getValueType(MVT::i32)); 7054 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7055 DAG.getConstant(31, DL, MVT::i64)); 7056 7057 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7058 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7059 7060 // NOTE: The result is only required to be anyextended, but sext is 7061 // consistent with type legalization of sub. 7062 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7063 DAG.getValueType(MVT::i32)); 7064 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7065 return; 7066 } 7067 case ISD::BITCAST: { 7068 EVT VT = N->getValueType(0); 7069 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7070 SDValue Op0 = N->getOperand(0); 7071 EVT Op0VT = Op0.getValueType(); 7072 MVT XLenVT = Subtarget.getXLenVT(); 7073 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7074 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7075 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7076 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7077 Subtarget.hasStdExtF()) { 7078 SDValue FPConv = 7079 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7080 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7081 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7082 isTypeLegal(Op0VT)) { 7083 // Custom-legalize bitcasts from fixed-length vector types to illegal 7084 // scalar types in order to improve codegen. Bitcast the vector to a 7085 // one-element vector type whose element type is the same as the result 7086 // type, and extract the first element. 7087 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7088 if (isTypeLegal(BVT)) { 7089 SDValue BVec = DAG.getBitcast(BVT, Op0); 7090 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7091 DAG.getConstant(0, DL, XLenVT))); 7092 } 7093 } 7094 break; 7095 } 7096 case RISCVISD::GREV: 7097 case RISCVISD::GORC: 7098 case RISCVISD::SHFL: { 7099 MVT VT = N->getSimpleValueType(0); 7100 MVT XLenVT = Subtarget.getXLenVT(); 7101 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7102 "Unexpected custom legalisation"); 7103 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7104 assert((Subtarget.hasStdExtZbp() || 7105 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7106 N->getConstantOperandVal(1) == 7)) && 7107 "Unexpected extension"); 7108 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7109 SDValue NewOp1 = 7110 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7111 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7112 // ReplaceNodeResults requires we maintain the same type for the return 7113 // value. 7114 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7115 break; 7116 } 7117 case ISD::BSWAP: 7118 case ISD::BITREVERSE: { 7119 MVT VT = N->getSimpleValueType(0); 7120 MVT XLenVT = Subtarget.getXLenVT(); 7121 assert((VT == MVT::i8 || VT == MVT::i16 || 7122 (VT == MVT::i32 && Subtarget.is64Bit())) && 7123 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7124 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7125 unsigned Imm = VT.getSizeInBits() - 1; 7126 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7127 if (N->getOpcode() == ISD::BSWAP) 7128 Imm &= ~0x7U; 7129 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7130 DAG.getConstant(Imm, DL, XLenVT)); 7131 // ReplaceNodeResults requires we maintain the same type for the return 7132 // value. 7133 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7134 break; 7135 } 7136 case ISD::FSHL: 7137 case ISD::FSHR: { 7138 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7139 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7140 SDValue NewOp0 = 7141 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7142 SDValue NewOp1 = 7143 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7144 SDValue NewShAmt = 7145 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7146 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7147 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7148 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7149 DAG.getConstant(0x1f, DL, MVT::i64)); 7150 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7151 // instruction use different orders. fshl will return its first operand for 7152 // shift of zero, fshr will return its second operand. fsl and fsr both 7153 // return rs1 so the ISD nodes need to have different operand orders. 7154 // Shift amount is in rs2. 7155 unsigned Opc = RISCVISD::FSLW; 7156 if (N->getOpcode() == ISD::FSHR) { 7157 std::swap(NewOp0, NewOp1); 7158 Opc = RISCVISD::FSRW; 7159 } 7160 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7161 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7162 break; 7163 } 7164 case ISD::EXTRACT_VECTOR_ELT: { 7165 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7166 // type is illegal (currently only vXi64 RV32). 7167 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7168 // transferred to the destination register. We issue two of these from the 7169 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7170 // first element. 7171 SDValue Vec = N->getOperand(0); 7172 SDValue Idx = N->getOperand(1); 7173 7174 // The vector type hasn't been legalized yet so we can't issue target 7175 // specific nodes if it needs legalization. 7176 // FIXME: We would manually legalize if it's important. 7177 if (!isTypeLegal(Vec.getValueType())) 7178 return; 7179 7180 MVT VecVT = Vec.getSimpleValueType(); 7181 7182 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7183 VecVT.getVectorElementType() == MVT::i64 && 7184 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7185 7186 // If this is a fixed vector, we need to convert it to a scalable vector. 7187 MVT ContainerVT = VecVT; 7188 if (VecVT.isFixedLengthVector()) { 7189 ContainerVT = getContainerForFixedLengthVector(VecVT); 7190 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7191 } 7192 7193 MVT XLenVT = Subtarget.getXLenVT(); 7194 7195 // Use a VL of 1 to avoid processing more elements than we need. 7196 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7197 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7198 7199 // Unless the index is known to be 0, we must slide the vector down to get 7200 // the desired element into index 0. 7201 if (!isNullConstant(Idx)) { 7202 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7203 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7204 } 7205 7206 // Extract the lower XLEN bits of the correct vector element. 7207 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7208 7209 // To extract the upper XLEN bits of the vector element, shift the first 7210 // element right by 32 bits and re-extract the lower XLEN bits. 7211 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7212 DAG.getUNDEF(ContainerVT), 7213 DAG.getConstant(32, DL, XLenVT), VL); 7214 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7215 ThirtyTwoV, Mask, VL); 7216 7217 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7218 7219 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7220 break; 7221 } 7222 case ISD::INTRINSIC_WO_CHAIN: { 7223 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7224 switch (IntNo) { 7225 default: 7226 llvm_unreachable( 7227 "Don't know how to custom type legalize this intrinsic!"); 7228 case Intrinsic::riscv_grev: 7229 case Intrinsic::riscv_gorc: { 7230 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7231 "Unexpected custom legalisation"); 7232 SDValue NewOp1 = 7233 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7234 SDValue NewOp2 = 7235 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7236 unsigned Opc = 7237 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7238 // If the control is a constant, promote the node by clearing any extra 7239 // bits bits in the control. isel will form greviw/gorciw if the result is 7240 // sign extended. 7241 if (isa<ConstantSDNode>(NewOp2)) { 7242 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7243 DAG.getConstant(0x1f, DL, MVT::i64)); 7244 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7245 } 7246 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7247 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7248 break; 7249 } 7250 case Intrinsic::riscv_bcompress: 7251 case Intrinsic::riscv_bdecompress: 7252 case Intrinsic::riscv_bfp: 7253 case Intrinsic::riscv_fsl: 7254 case Intrinsic::riscv_fsr: { 7255 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7256 "Unexpected custom legalisation"); 7257 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7258 break; 7259 } 7260 case Intrinsic::riscv_orc_b: { 7261 // Lower to the GORCI encoding for orc.b with the operand extended. 7262 SDValue NewOp = 7263 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7264 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7265 DAG.getConstant(7, DL, MVT::i64)); 7266 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7267 return; 7268 } 7269 case Intrinsic::riscv_shfl: 7270 case Intrinsic::riscv_unshfl: { 7271 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7272 "Unexpected custom legalisation"); 7273 SDValue NewOp1 = 7274 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7275 SDValue NewOp2 = 7276 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7277 unsigned Opc = 7278 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7279 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7280 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7281 // will be shuffled the same way as the lower 32 bit half, but the two 7282 // halves won't cross. 7283 if (isa<ConstantSDNode>(NewOp2)) { 7284 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7285 DAG.getConstant(0xf, DL, MVT::i64)); 7286 Opc = 7287 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7288 } 7289 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7290 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7291 break; 7292 } 7293 case Intrinsic::riscv_vmv_x_s: { 7294 EVT VT = N->getValueType(0); 7295 MVT XLenVT = Subtarget.getXLenVT(); 7296 if (VT.bitsLT(XLenVT)) { 7297 // Simple case just extract using vmv.x.s and truncate. 7298 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7299 Subtarget.getXLenVT(), N->getOperand(1)); 7300 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7301 return; 7302 } 7303 7304 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7305 "Unexpected custom legalization"); 7306 7307 // We need to do the move in two steps. 7308 SDValue Vec = N->getOperand(1); 7309 MVT VecVT = Vec.getSimpleValueType(); 7310 7311 // First extract the lower XLEN bits of the element. 7312 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7313 7314 // To extract the upper XLEN bits of the vector element, shift the first 7315 // element right by 32 bits and re-extract the lower XLEN bits. 7316 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7317 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7318 7319 SDValue ThirtyTwoV = 7320 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7321 DAG.getConstant(32, DL, XLenVT), VL); 7322 SDValue LShr32 = 7323 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7324 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7325 7326 Results.push_back( 7327 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7328 break; 7329 } 7330 } 7331 break; 7332 } 7333 case ISD::VECREDUCE_ADD: 7334 case ISD::VECREDUCE_AND: 7335 case ISD::VECREDUCE_OR: 7336 case ISD::VECREDUCE_XOR: 7337 case ISD::VECREDUCE_SMAX: 7338 case ISD::VECREDUCE_UMAX: 7339 case ISD::VECREDUCE_SMIN: 7340 case ISD::VECREDUCE_UMIN: 7341 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7342 Results.push_back(V); 7343 break; 7344 case ISD::VP_REDUCE_ADD: 7345 case ISD::VP_REDUCE_AND: 7346 case ISD::VP_REDUCE_OR: 7347 case ISD::VP_REDUCE_XOR: 7348 case ISD::VP_REDUCE_SMAX: 7349 case ISD::VP_REDUCE_UMAX: 7350 case ISD::VP_REDUCE_SMIN: 7351 case ISD::VP_REDUCE_UMIN: 7352 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7353 Results.push_back(V); 7354 break; 7355 case ISD::FLT_ROUNDS_: { 7356 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7357 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7358 Results.push_back(Res.getValue(0)); 7359 Results.push_back(Res.getValue(1)); 7360 break; 7361 } 7362 } 7363 } 7364 7365 // A structure to hold one of the bit-manipulation patterns below. Together, a 7366 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7367 // (or (and (shl x, 1), 0xAAAAAAAA), 7368 // (and (srl x, 1), 0x55555555)) 7369 struct RISCVBitmanipPat { 7370 SDValue Op; 7371 unsigned ShAmt; 7372 bool IsSHL; 7373 7374 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7375 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7376 } 7377 }; 7378 7379 // Matches patterns of the form 7380 // (and (shl x, C2), (C1 << C2)) 7381 // (and (srl x, C2), C1) 7382 // (shl (and x, C1), C2) 7383 // (srl (and x, (C1 << C2)), C2) 7384 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7385 // The expected masks for each shift amount are specified in BitmanipMasks where 7386 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7387 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7388 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7389 // XLen is 64. 7390 static Optional<RISCVBitmanipPat> 7391 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7392 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7393 "Unexpected number of masks"); 7394 Optional<uint64_t> Mask; 7395 // Optionally consume a mask around the shift operation. 7396 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7397 Mask = Op.getConstantOperandVal(1); 7398 Op = Op.getOperand(0); 7399 } 7400 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7401 return None; 7402 bool IsSHL = Op.getOpcode() == ISD::SHL; 7403 7404 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7405 return None; 7406 uint64_t ShAmt = Op.getConstantOperandVal(1); 7407 7408 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7409 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7410 return None; 7411 // If we don't have enough masks for 64 bit, then we must be trying to 7412 // match SHFL so we're only allowed to shift 1/4 of the width. 7413 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7414 return None; 7415 7416 SDValue Src = Op.getOperand(0); 7417 7418 // The expected mask is shifted left when the AND is found around SHL 7419 // patterns. 7420 // ((x >> 1) & 0x55555555) 7421 // ((x << 1) & 0xAAAAAAAA) 7422 bool SHLExpMask = IsSHL; 7423 7424 if (!Mask) { 7425 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7426 // the mask is all ones: consume that now. 7427 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7428 Mask = Src.getConstantOperandVal(1); 7429 Src = Src.getOperand(0); 7430 // The expected mask is now in fact shifted left for SRL, so reverse the 7431 // decision. 7432 // ((x & 0xAAAAAAAA) >> 1) 7433 // ((x & 0x55555555) << 1) 7434 SHLExpMask = !SHLExpMask; 7435 } else { 7436 // Use a default shifted mask of all-ones if there's no AND, truncated 7437 // down to the expected width. This simplifies the logic later on. 7438 Mask = maskTrailingOnes<uint64_t>(Width); 7439 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7440 } 7441 } 7442 7443 unsigned MaskIdx = Log2_32(ShAmt); 7444 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7445 7446 if (SHLExpMask) 7447 ExpMask <<= ShAmt; 7448 7449 if (Mask != ExpMask) 7450 return None; 7451 7452 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7453 } 7454 7455 // Matches any of the following bit-manipulation patterns: 7456 // (and (shl x, 1), (0x55555555 << 1)) 7457 // (and (srl x, 1), 0x55555555) 7458 // (shl (and x, 0x55555555), 1) 7459 // (srl (and x, (0x55555555 << 1)), 1) 7460 // where the shift amount and mask may vary thus: 7461 // [1] = 0x55555555 / 0xAAAAAAAA 7462 // [2] = 0x33333333 / 0xCCCCCCCC 7463 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7464 // [8] = 0x00FF00FF / 0xFF00FF00 7465 // [16] = 0x0000FFFF / 0xFFFFFFFF 7466 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7467 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7468 // These are the unshifted masks which we use to match bit-manipulation 7469 // patterns. They may be shifted left in certain circumstances. 7470 static const uint64_t BitmanipMasks[] = { 7471 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7472 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7473 7474 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7475 } 7476 7477 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7478 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7479 auto BinOpToRVVReduce = [](unsigned Opc) { 7480 switch (Opc) { 7481 default: 7482 llvm_unreachable("Unhandled binary to transfrom reduction"); 7483 case ISD::ADD: 7484 return RISCVISD::VECREDUCE_ADD_VL; 7485 case ISD::UMAX: 7486 return RISCVISD::VECREDUCE_UMAX_VL; 7487 case ISD::SMAX: 7488 return RISCVISD::VECREDUCE_SMAX_VL; 7489 case ISD::UMIN: 7490 return RISCVISD::VECREDUCE_UMIN_VL; 7491 case ISD::SMIN: 7492 return RISCVISD::VECREDUCE_SMIN_VL; 7493 case ISD::AND: 7494 return RISCVISD::VECREDUCE_AND_VL; 7495 case ISD::OR: 7496 return RISCVISD::VECREDUCE_OR_VL; 7497 case ISD::XOR: 7498 return RISCVISD::VECREDUCE_XOR_VL; 7499 case ISD::FADD: 7500 return RISCVISD::VECREDUCE_FADD_VL; 7501 case ISD::FMAXNUM: 7502 return RISCVISD::VECREDUCE_FMAX_VL; 7503 case ISD::FMINNUM: 7504 return RISCVISD::VECREDUCE_FMIN_VL; 7505 } 7506 }; 7507 7508 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7509 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7510 isNullConstant(V.getOperand(1)) && 7511 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7512 }; 7513 7514 unsigned Opc = N->getOpcode(); 7515 unsigned ReduceIdx; 7516 if (IsReduction(N->getOperand(0), Opc)) 7517 ReduceIdx = 0; 7518 else if (IsReduction(N->getOperand(1), Opc)) 7519 ReduceIdx = 1; 7520 else 7521 return SDValue(); 7522 7523 // Skip if FADD disallows reassociation but the combiner needs. 7524 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7525 return SDValue(); 7526 7527 SDValue Extract = N->getOperand(ReduceIdx); 7528 SDValue Reduce = Extract.getOperand(0); 7529 if (!Reduce.hasOneUse()) 7530 return SDValue(); 7531 7532 SDValue ScalarV = Reduce.getOperand(2); 7533 7534 // Make sure that ScalarV is a splat with VL=1. 7535 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7536 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7537 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7538 return SDValue(); 7539 7540 if (!isOneConstant(ScalarV.getOperand(2))) 7541 return SDValue(); 7542 7543 // TODO: Deal with value other than neutral element. 7544 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7545 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7546 isNullFPConstant(V)) 7547 return true; 7548 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7549 N->getFlags()) == V; 7550 }; 7551 7552 // Check the scalar of ScalarV is neutral element 7553 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7554 return SDValue(); 7555 7556 if (!ScalarV.hasOneUse()) 7557 return SDValue(); 7558 7559 EVT SplatVT = ScalarV.getValueType(); 7560 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7561 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7562 if (SplatVT.isInteger()) { 7563 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7564 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7565 SplatOpc = RISCVISD::VMV_S_X_VL; 7566 else 7567 SplatOpc = RISCVISD::VMV_V_X_VL; 7568 } 7569 7570 SDValue NewScalarV = 7571 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7572 ScalarV.getOperand(2)); 7573 SDValue NewReduce = 7574 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7575 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7576 Reduce.getOperand(3), Reduce.getOperand(4)); 7577 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7578 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7579 } 7580 7581 // Match the following pattern as a GREVI(W) operation 7582 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7583 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7584 const RISCVSubtarget &Subtarget) { 7585 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7586 EVT VT = Op.getValueType(); 7587 7588 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7589 auto LHS = matchGREVIPat(Op.getOperand(0)); 7590 auto RHS = matchGREVIPat(Op.getOperand(1)); 7591 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7592 SDLoc DL(Op); 7593 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7594 DAG.getConstant(LHS->ShAmt, DL, VT)); 7595 } 7596 } 7597 return SDValue(); 7598 } 7599 7600 // Matches any the following pattern as a GORCI(W) operation 7601 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7602 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7603 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7604 // Note that with the variant of 3., 7605 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7606 // the inner pattern will first be matched as GREVI and then the outer 7607 // pattern will be matched to GORC via the first rule above. 7608 // 4. (or (rotl/rotr x, bitwidth/2), x) 7609 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7610 const RISCVSubtarget &Subtarget) { 7611 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7612 EVT VT = Op.getValueType(); 7613 7614 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7615 SDLoc DL(Op); 7616 SDValue Op0 = Op.getOperand(0); 7617 SDValue Op1 = Op.getOperand(1); 7618 7619 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7620 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7621 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7622 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7623 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7624 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7625 if ((Reverse.getOpcode() == ISD::ROTL || 7626 Reverse.getOpcode() == ISD::ROTR) && 7627 Reverse.getOperand(0) == X && 7628 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7629 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7630 if (RotAmt == (VT.getSizeInBits() / 2)) 7631 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7632 DAG.getConstant(RotAmt, DL, VT)); 7633 } 7634 return SDValue(); 7635 }; 7636 7637 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7638 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7639 return V; 7640 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7641 return V; 7642 7643 // OR is commutable so canonicalize its OR operand to the left 7644 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7645 std::swap(Op0, Op1); 7646 if (Op0.getOpcode() != ISD::OR) 7647 return SDValue(); 7648 SDValue OrOp0 = Op0.getOperand(0); 7649 SDValue OrOp1 = Op0.getOperand(1); 7650 auto LHS = matchGREVIPat(OrOp0); 7651 // OR is commutable so swap the operands and try again: x might have been 7652 // on the left 7653 if (!LHS) { 7654 std::swap(OrOp0, OrOp1); 7655 LHS = matchGREVIPat(OrOp0); 7656 } 7657 auto RHS = matchGREVIPat(Op1); 7658 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7659 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7660 DAG.getConstant(LHS->ShAmt, DL, VT)); 7661 } 7662 } 7663 return SDValue(); 7664 } 7665 7666 // Matches any of the following bit-manipulation patterns: 7667 // (and (shl x, 1), (0x22222222 << 1)) 7668 // (and (srl x, 1), 0x22222222) 7669 // (shl (and x, 0x22222222), 1) 7670 // (srl (and x, (0x22222222 << 1)), 1) 7671 // where the shift amount and mask may vary thus: 7672 // [1] = 0x22222222 / 0x44444444 7673 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7674 // [4] = 0x00F000F0 / 0x0F000F00 7675 // [8] = 0x0000FF00 / 0x00FF0000 7676 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7677 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7678 // These are the unshifted masks which we use to match bit-manipulation 7679 // patterns. They may be shifted left in certain circumstances. 7680 static const uint64_t BitmanipMasks[] = { 7681 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7682 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7683 7684 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7685 } 7686 7687 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7688 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7689 const RISCVSubtarget &Subtarget) { 7690 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7691 EVT VT = Op.getValueType(); 7692 7693 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7694 return SDValue(); 7695 7696 SDValue Op0 = Op.getOperand(0); 7697 SDValue Op1 = Op.getOperand(1); 7698 7699 // Or is commutable so canonicalize the second OR to the LHS. 7700 if (Op0.getOpcode() != ISD::OR) 7701 std::swap(Op0, Op1); 7702 if (Op0.getOpcode() != ISD::OR) 7703 return SDValue(); 7704 7705 // We found an inner OR, so our operands are the operands of the inner OR 7706 // and the other operand of the outer OR. 7707 SDValue A = Op0.getOperand(0); 7708 SDValue B = Op0.getOperand(1); 7709 SDValue C = Op1; 7710 7711 auto Match1 = matchSHFLPat(A); 7712 auto Match2 = matchSHFLPat(B); 7713 7714 // If neither matched, we failed. 7715 if (!Match1 && !Match2) 7716 return SDValue(); 7717 7718 // We had at least one match. if one failed, try the remaining C operand. 7719 if (!Match1) { 7720 std::swap(A, C); 7721 Match1 = matchSHFLPat(A); 7722 if (!Match1) 7723 return SDValue(); 7724 } else if (!Match2) { 7725 std::swap(B, C); 7726 Match2 = matchSHFLPat(B); 7727 if (!Match2) 7728 return SDValue(); 7729 } 7730 assert(Match1 && Match2); 7731 7732 // Make sure our matches pair up. 7733 if (!Match1->formsPairWith(*Match2)) 7734 return SDValue(); 7735 7736 // All the remains is to make sure C is an AND with the same input, that masks 7737 // out the bits that are being shuffled. 7738 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7739 C.getOperand(0) != Match1->Op) 7740 return SDValue(); 7741 7742 uint64_t Mask = C.getConstantOperandVal(1); 7743 7744 static const uint64_t BitmanipMasks[] = { 7745 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7746 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7747 }; 7748 7749 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7750 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7751 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7752 7753 if (Mask != ExpMask) 7754 return SDValue(); 7755 7756 SDLoc DL(Op); 7757 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7758 DAG.getConstant(Match1->ShAmt, DL, VT)); 7759 } 7760 7761 // Optimize (add (shl x, c0), (shl y, c1)) -> 7762 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7763 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7764 const RISCVSubtarget &Subtarget) { 7765 // Perform this optimization only in the zba extension. 7766 if (!Subtarget.hasStdExtZba()) 7767 return SDValue(); 7768 7769 // Skip for vector types and larger types. 7770 EVT VT = N->getValueType(0); 7771 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7772 return SDValue(); 7773 7774 // The two operand nodes must be SHL and have no other use. 7775 SDValue N0 = N->getOperand(0); 7776 SDValue N1 = N->getOperand(1); 7777 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7778 !N0->hasOneUse() || !N1->hasOneUse()) 7779 return SDValue(); 7780 7781 // Check c0 and c1. 7782 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7783 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7784 if (!N0C || !N1C) 7785 return SDValue(); 7786 int64_t C0 = N0C->getSExtValue(); 7787 int64_t C1 = N1C->getSExtValue(); 7788 if (C0 <= 0 || C1 <= 0) 7789 return SDValue(); 7790 7791 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7792 int64_t Bits = std::min(C0, C1); 7793 int64_t Diff = std::abs(C0 - C1); 7794 if (Diff != 1 && Diff != 2 && Diff != 3) 7795 return SDValue(); 7796 7797 // Build nodes. 7798 SDLoc DL(N); 7799 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7800 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7801 SDValue NA0 = 7802 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7803 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7804 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7805 } 7806 7807 // Combine 7808 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7809 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7810 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7811 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7812 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7813 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7814 // The grev patterns represents BSWAP. 7815 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7816 // off the grev. 7817 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7818 const RISCVSubtarget &Subtarget) { 7819 bool IsWInstruction = 7820 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7821 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7822 IsWInstruction) && 7823 "Unexpected opcode!"); 7824 SDValue Src = N->getOperand(0); 7825 EVT VT = N->getValueType(0); 7826 SDLoc DL(N); 7827 7828 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7829 return SDValue(); 7830 7831 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7832 !isa<ConstantSDNode>(Src.getOperand(1))) 7833 return SDValue(); 7834 7835 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7836 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7837 7838 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7839 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7840 unsigned ShAmt1 = N->getConstantOperandVal(1); 7841 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7842 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7843 return SDValue(); 7844 7845 Src = Src.getOperand(0); 7846 7847 // Toggle bit the MSB of the shift. 7848 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7849 if (CombinedShAmt == 0) 7850 return Src; 7851 7852 SDValue Res = DAG.getNode( 7853 RISCVISD::GREV, DL, VT, Src, 7854 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7855 if (!IsWInstruction) 7856 return Res; 7857 7858 // Sign extend the result to match the behavior of the rotate. This will be 7859 // selected to GREVIW in isel. 7860 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7861 DAG.getValueType(MVT::i32)); 7862 } 7863 7864 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7865 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7866 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7867 // not undo itself, but they are redundant. 7868 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7869 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7870 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7871 SDValue Src = N->getOperand(0); 7872 7873 if (Src.getOpcode() != N->getOpcode()) 7874 return SDValue(); 7875 7876 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7877 !isa<ConstantSDNode>(Src.getOperand(1))) 7878 return SDValue(); 7879 7880 unsigned ShAmt1 = N->getConstantOperandVal(1); 7881 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7882 Src = Src.getOperand(0); 7883 7884 unsigned CombinedShAmt; 7885 if (IsGORC) 7886 CombinedShAmt = ShAmt1 | ShAmt2; 7887 else 7888 CombinedShAmt = ShAmt1 ^ ShAmt2; 7889 7890 if (CombinedShAmt == 0) 7891 return Src; 7892 7893 SDLoc DL(N); 7894 return DAG.getNode( 7895 N->getOpcode(), DL, N->getValueType(0), Src, 7896 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7897 } 7898 7899 // Combine a constant select operand into its use: 7900 // 7901 // (and (select cond, -1, c), x) 7902 // -> (select cond, x, (and x, c)) [AllOnes=1] 7903 // (or (select cond, 0, c), x) 7904 // -> (select cond, x, (or x, c)) [AllOnes=0] 7905 // (xor (select cond, 0, c), x) 7906 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7907 // (add (select cond, 0, c), x) 7908 // -> (select cond, x, (add x, c)) [AllOnes=0] 7909 // (sub x, (select cond, 0, c)) 7910 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7911 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7912 SelectionDAG &DAG, bool AllOnes) { 7913 EVT VT = N->getValueType(0); 7914 7915 // Skip vectors. 7916 if (VT.isVector()) 7917 return SDValue(); 7918 7919 if ((Slct.getOpcode() != ISD::SELECT && 7920 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7921 !Slct.hasOneUse()) 7922 return SDValue(); 7923 7924 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7925 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7926 }; 7927 7928 bool SwapSelectOps; 7929 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7930 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7931 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7932 SDValue NonConstantVal; 7933 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7934 SwapSelectOps = false; 7935 NonConstantVal = FalseVal; 7936 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7937 SwapSelectOps = true; 7938 NonConstantVal = TrueVal; 7939 } else 7940 return SDValue(); 7941 7942 // Slct is now know to be the desired identity constant when CC is true. 7943 TrueVal = OtherOp; 7944 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7945 // Unless SwapSelectOps says the condition should be false. 7946 if (SwapSelectOps) 7947 std::swap(TrueVal, FalseVal); 7948 7949 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7950 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7951 {Slct.getOperand(0), Slct.getOperand(1), 7952 Slct.getOperand(2), TrueVal, FalseVal}); 7953 7954 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7955 {Slct.getOperand(0), TrueVal, FalseVal}); 7956 } 7957 7958 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7959 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7960 bool AllOnes) { 7961 SDValue N0 = N->getOperand(0); 7962 SDValue N1 = N->getOperand(1); 7963 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7964 return Result; 7965 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7966 return Result; 7967 return SDValue(); 7968 } 7969 7970 // Transform (add (mul x, c0), c1) -> 7971 // (add (mul (add x, c1/c0), c0), c1%c0). 7972 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7973 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7974 // to an infinite loop in DAGCombine if transformed. 7975 // Or transform (add (mul x, c0), c1) -> 7976 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7977 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7978 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7979 // lead to an infinite loop in DAGCombine if transformed. 7980 // Or transform (add (mul x, c0), c1) -> 7981 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7982 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7983 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7984 // lead to an infinite loop in DAGCombine if transformed. 7985 // Or transform (add (mul x, c0), c1) -> 7986 // (mul (add x, c1/c0), c0). 7987 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7988 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7989 const RISCVSubtarget &Subtarget) { 7990 // Skip for vector types and larger types. 7991 EVT VT = N->getValueType(0); 7992 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7993 return SDValue(); 7994 // The first operand node must be a MUL and has no other use. 7995 SDValue N0 = N->getOperand(0); 7996 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7997 return SDValue(); 7998 // Check if c0 and c1 match above conditions. 7999 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8000 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8001 if (!N0C || !N1C) 8002 return SDValue(); 8003 // If N0C has multiple uses it's possible one of the cases in 8004 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 8005 // in an infinite loop. 8006 if (!N0C->hasOneUse()) 8007 return SDValue(); 8008 int64_t C0 = N0C->getSExtValue(); 8009 int64_t C1 = N1C->getSExtValue(); 8010 int64_t CA, CB; 8011 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 8012 return SDValue(); 8013 // Search for proper CA (non-zero) and CB that both are simm12. 8014 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 8015 !isInt<12>(C0 * (C1 / C0))) { 8016 CA = C1 / C0; 8017 CB = C1 % C0; 8018 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 8019 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 8020 CA = C1 / C0 + 1; 8021 CB = C1 % C0 - C0; 8022 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 8023 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8024 CA = C1 / C0 - 1; 8025 CB = C1 % C0 + C0; 8026 } else 8027 return SDValue(); 8028 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8029 SDLoc DL(N); 8030 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8031 DAG.getConstant(CA, DL, VT)); 8032 SDValue New1 = 8033 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8034 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8035 } 8036 8037 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8038 const RISCVSubtarget &Subtarget) { 8039 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8040 return V; 8041 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8042 return V; 8043 if (SDValue V = combineBinOpToReduce(N, DAG)) 8044 return V; 8045 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8046 // (select lhs, rhs, cc, x, (add x, y)) 8047 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8048 } 8049 8050 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8051 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8052 // (select lhs, rhs, cc, x, (sub x, y)) 8053 SDValue N0 = N->getOperand(0); 8054 SDValue N1 = N->getOperand(1); 8055 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8056 } 8057 8058 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8059 const RISCVSubtarget &Subtarget) { 8060 SDValue N0 = N->getOperand(0); 8061 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8062 // extending X. This is safe since we only need the LSB after the shift and 8063 // shift amounts larger than 31 would produce poison. If we wait until 8064 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8065 // to use a BEXT instruction. 8066 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8067 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8068 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8069 N0.hasOneUse()) { 8070 SDLoc DL(N); 8071 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8072 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8073 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8074 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8075 DAG.getConstant(1, DL, MVT::i64)); 8076 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8077 } 8078 8079 if (SDValue V = combineBinOpToReduce(N, DAG)) 8080 return V; 8081 8082 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8083 // (select lhs, rhs, cc, x, (and x, y)) 8084 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8085 } 8086 8087 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8088 const RISCVSubtarget &Subtarget) { 8089 if (Subtarget.hasStdExtZbp()) { 8090 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8091 return GREV; 8092 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8093 return GORC; 8094 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8095 return SHFL; 8096 } 8097 8098 if (SDValue V = combineBinOpToReduce(N, DAG)) 8099 return V; 8100 // fold (or (select cond, 0, y), x) -> 8101 // (select cond, x, (or x, y)) 8102 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8103 } 8104 8105 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8106 SDValue N0 = N->getOperand(0); 8107 SDValue N1 = N->getOperand(1); 8108 8109 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8110 // NOTE: Assumes ROL being legal means ROLW is legal. 8111 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8112 if (N0.getOpcode() == RISCVISD::SLLW && 8113 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8114 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8115 SDLoc DL(N); 8116 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8117 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8118 } 8119 8120 if (SDValue V = combineBinOpToReduce(N, DAG)) 8121 return V; 8122 // fold (xor (select cond, 0, y), x) -> 8123 // (select cond, x, (xor x, y)) 8124 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8125 } 8126 8127 static SDValue 8128 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8129 const RISCVSubtarget &Subtarget) { 8130 SDValue Src = N->getOperand(0); 8131 EVT VT = N->getValueType(0); 8132 8133 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8134 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8135 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8136 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8137 Src.getOperand(0)); 8138 8139 // Fold (i64 (sext_inreg (abs X), i32)) -> 8140 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8141 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8142 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8143 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8144 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8145 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8146 // may get combined into an earlier operation so we need to use 8147 // ComputeNumSignBits. 8148 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8149 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8150 // we can't assume that X has 33 sign bits. We must check. 8151 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8152 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8153 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8154 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8155 SDLoc DL(N); 8156 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8157 SDValue Neg = 8158 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8159 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8160 DAG.getValueType(MVT::i32)); 8161 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8162 } 8163 8164 return SDValue(); 8165 } 8166 8167 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8168 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8169 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8170 bool Commute = false) { 8171 assert((N->getOpcode() == RISCVISD::ADD_VL || 8172 N->getOpcode() == RISCVISD::SUB_VL) && 8173 "Unexpected opcode"); 8174 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8175 SDValue Op0 = N->getOperand(0); 8176 SDValue Op1 = N->getOperand(1); 8177 if (Commute) 8178 std::swap(Op0, Op1); 8179 8180 MVT VT = N->getSimpleValueType(0); 8181 8182 // Determine the narrow size for a widening add/sub. 8183 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8184 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8185 VT.getVectorElementCount()); 8186 8187 SDValue Mask = N->getOperand(2); 8188 SDValue VL = N->getOperand(3); 8189 8190 SDLoc DL(N); 8191 8192 // If the RHS is a sext or zext, we can form a widening op. 8193 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8194 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8195 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8196 unsigned ExtOpc = Op1.getOpcode(); 8197 Op1 = Op1.getOperand(0); 8198 // Re-introduce narrower extends if needed. 8199 if (Op1.getValueType() != NarrowVT) 8200 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8201 8202 unsigned WOpc; 8203 if (ExtOpc == RISCVISD::VSEXT_VL) 8204 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8205 else 8206 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8207 8208 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8209 } 8210 8211 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8212 // sext/zext? 8213 8214 return SDValue(); 8215 } 8216 8217 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8218 // vwsub(u).vv/vx. 8219 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8220 SDValue Op0 = N->getOperand(0); 8221 SDValue Op1 = N->getOperand(1); 8222 SDValue Mask = N->getOperand(2); 8223 SDValue VL = N->getOperand(3); 8224 8225 MVT VT = N->getSimpleValueType(0); 8226 MVT NarrowVT = Op1.getSimpleValueType(); 8227 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8228 8229 unsigned VOpc; 8230 switch (N->getOpcode()) { 8231 default: llvm_unreachable("Unexpected opcode"); 8232 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8233 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8234 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8235 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8236 } 8237 8238 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8239 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8240 8241 SDLoc DL(N); 8242 8243 // If the LHS is a sext or zext, we can narrow this op to the same size as 8244 // the RHS. 8245 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8246 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8247 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8248 unsigned ExtOpc = Op0.getOpcode(); 8249 Op0 = Op0.getOperand(0); 8250 // Re-introduce narrower extends if needed. 8251 if (Op0.getValueType() != NarrowVT) 8252 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8253 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8254 } 8255 8256 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8257 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8258 8259 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8260 // to commute and use a vwadd(u).vx instead. 8261 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8262 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8263 Op0 = Op0.getOperand(1); 8264 8265 // See if have enough sign bits or zero bits in the scalar to use a 8266 // widening add/sub by splatting to smaller element size. 8267 unsigned EltBits = VT.getScalarSizeInBits(); 8268 unsigned ScalarBits = Op0.getValueSizeInBits(); 8269 // Make sure we're getting all element bits from the scalar register. 8270 // FIXME: Support implicit sign extension of vmv.v.x? 8271 if (ScalarBits < EltBits) 8272 return SDValue(); 8273 8274 if (IsSigned) { 8275 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8276 return SDValue(); 8277 } else { 8278 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8279 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8280 return SDValue(); 8281 } 8282 8283 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8284 DAG.getUNDEF(NarrowVT), Op0, VL); 8285 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8286 } 8287 8288 return SDValue(); 8289 } 8290 8291 // Try to form VWMUL, VWMULU or VWMULSU. 8292 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8293 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8294 bool Commute) { 8295 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8296 SDValue Op0 = N->getOperand(0); 8297 SDValue Op1 = N->getOperand(1); 8298 if (Commute) 8299 std::swap(Op0, Op1); 8300 8301 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8302 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8303 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8304 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8305 return SDValue(); 8306 8307 SDValue Mask = N->getOperand(2); 8308 SDValue VL = N->getOperand(3); 8309 8310 // Make sure the mask and VL match. 8311 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8312 return SDValue(); 8313 8314 MVT VT = N->getSimpleValueType(0); 8315 8316 // Determine the narrow size for a widening multiply. 8317 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8318 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8319 VT.getVectorElementCount()); 8320 8321 SDLoc DL(N); 8322 8323 // See if the other operand is the same opcode. 8324 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8325 if (!Op1.hasOneUse()) 8326 return SDValue(); 8327 8328 // Make sure the mask and VL match. 8329 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8330 return SDValue(); 8331 8332 Op1 = Op1.getOperand(0); 8333 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8334 // The operand is a splat of a scalar. 8335 8336 // The pasthru must be undef for tail agnostic 8337 if (!Op1.getOperand(0).isUndef()) 8338 return SDValue(); 8339 // The VL must be the same. 8340 if (Op1.getOperand(2) != VL) 8341 return SDValue(); 8342 8343 // Get the scalar value. 8344 Op1 = Op1.getOperand(1); 8345 8346 // See if have enough sign bits or zero bits in the scalar to use a 8347 // widening multiply by splatting to smaller element size. 8348 unsigned EltBits = VT.getScalarSizeInBits(); 8349 unsigned ScalarBits = Op1.getValueSizeInBits(); 8350 // Make sure we're getting all element bits from the scalar register. 8351 // FIXME: Support implicit sign extension of vmv.v.x? 8352 if (ScalarBits < EltBits) 8353 return SDValue(); 8354 8355 // If the LHS is a sign extend, try to use vwmul. 8356 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8357 // Can use vwmul. 8358 } else { 8359 // Otherwise try to use vwmulu or vwmulsu. 8360 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8361 if (DAG.MaskedValueIsZero(Op1, Mask)) 8362 IsVWMULSU = IsSignExt; 8363 else 8364 return SDValue(); 8365 } 8366 8367 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8368 DAG.getUNDEF(NarrowVT), Op1, VL); 8369 } else 8370 return SDValue(); 8371 8372 Op0 = Op0.getOperand(0); 8373 8374 // Re-introduce narrower extends if needed. 8375 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8376 if (Op0.getValueType() != NarrowVT) 8377 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8378 // vwmulsu requires second operand to be zero extended. 8379 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8380 if (Op1.getValueType() != NarrowVT) 8381 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8382 8383 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8384 if (!IsVWMULSU) 8385 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8386 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8387 } 8388 8389 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8390 switch (Op.getOpcode()) { 8391 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8392 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8393 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8394 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8395 case ISD::FROUND: return RISCVFPRndMode::RMM; 8396 } 8397 8398 return RISCVFPRndMode::Invalid; 8399 } 8400 8401 // Fold 8402 // (fp_to_int (froundeven X)) -> fcvt X, rne 8403 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8404 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8405 // (fp_to_int (fceil X)) -> fcvt X, rup 8406 // (fp_to_int (fround X)) -> fcvt X, rmm 8407 static SDValue performFP_TO_INTCombine(SDNode *N, 8408 TargetLowering::DAGCombinerInfo &DCI, 8409 const RISCVSubtarget &Subtarget) { 8410 SelectionDAG &DAG = DCI.DAG; 8411 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8412 MVT XLenVT = Subtarget.getXLenVT(); 8413 8414 // Only handle XLen or i32 types. Other types narrower than XLen will 8415 // eventually be legalized to XLenVT. 8416 EVT VT = N->getValueType(0); 8417 if (VT != MVT::i32 && VT != XLenVT) 8418 return SDValue(); 8419 8420 SDValue Src = N->getOperand(0); 8421 8422 // Ensure the FP type is also legal. 8423 if (!TLI.isTypeLegal(Src.getValueType())) 8424 return SDValue(); 8425 8426 // Don't do this for f16 with Zfhmin and not Zfh. 8427 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8428 return SDValue(); 8429 8430 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8431 if (FRM == RISCVFPRndMode::Invalid) 8432 return SDValue(); 8433 8434 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8435 8436 unsigned Opc; 8437 if (VT == XLenVT) 8438 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8439 else 8440 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8441 8442 SDLoc DL(N); 8443 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8444 DAG.getTargetConstant(FRM, DL, XLenVT)); 8445 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8446 } 8447 8448 // Fold 8449 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8450 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8451 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8452 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8453 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8454 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8455 TargetLowering::DAGCombinerInfo &DCI, 8456 const RISCVSubtarget &Subtarget) { 8457 SelectionDAG &DAG = DCI.DAG; 8458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8459 MVT XLenVT = Subtarget.getXLenVT(); 8460 8461 // Only handle XLen types. Other types narrower than XLen will eventually be 8462 // legalized to XLenVT. 8463 EVT DstVT = N->getValueType(0); 8464 if (DstVT != XLenVT) 8465 return SDValue(); 8466 8467 SDValue Src = N->getOperand(0); 8468 8469 // Ensure the FP type is also legal. 8470 if (!TLI.isTypeLegal(Src.getValueType())) 8471 return SDValue(); 8472 8473 // Don't do this for f16 with Zfhmin and not Zfh. 8474 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8475 return SDValue(); 8476 8477 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8478 8479 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8480 if (FRM == RISCVFPRndMode::Invalid) 8481 return SDValue(); 8482 8483 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8484 8485 unsigned Opc; 8486 if (SatVT == DstVT) 8487 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8488 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8489 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8490 else 8491 return SDValue(); 8492 // FIXME: Support other SatVTs by clamping before or after the conversion. 8493 8494 Src = Src.getOperand(0); 8495 8496 SDLoc DL(N); 8497 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8498 DAG.getTargetConstant(FRM, DL, XLenVT)); 8499 8500 // RISCV FP-to-int conversions saturate to the destination register size, but 8501 // don't produce 0 for nan. 8502 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8503 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8504 } 8505 8506 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8507 // smaller than XLenVT. 8508 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8509 const RISCVSubtarget &Subtarget) { 8510 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8511 8512 SDValue Src = N->getOperand(0); 8513 if (Src.getOpcode() != ISD::BSWAP) 8514 return SDValue(); 8515 8516 EVT VT = N->getValueType(0); 8517 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8518 !isPowerOf2_32(VT.getSizeInBits())) 8519 return SDValue(); 8520 8521 SDLoc DL(N); 8522 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8523 DAG.getConstant(7, DL, VT)); 8524 } 8525 8526 // Convert from one FMA opcode to another based on whether we are negating the 8527 // multiply result and/or the accumulator. 8528 // NOTE: Only supports RVV operations with VL. 8529 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8530 assert((NegMul || NegAcc) && "Not negating anything?"); 8531 8532 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8533 if (NegMul) { 8534 // clang-format off 8535 switch (Opcode) { 8536 default: llvm_unreachable("Unexpected opcode"); 8537 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8538 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8539 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8540 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8541 } 8542 // clang-format on 8543 } 8544 8545 // Negating the accumulator changes ADD<->SUB. 8546 if (NegAcc) { 8547 // clang-format off 8548 switch (Opcode) { 8549 default: llvm_unreachable("Unexpected opcode"); 8550 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8551 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8552 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8553 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8554 } 8555 // clang-format on 8556 } 8557 8558 return Opcode; 8559 } 8560 8561 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8562 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8563 // 8564 // Also try these folds where an add or sub is in the middle. 8565 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8566 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8567 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8568 const RISCVSubtarget &Subtarget) { 8569 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8570 8571 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8572 return SDValue(); 8573 8574 auto *ShAmtC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8575 if (!ShAmtC || ShAmtC->getZExtValue() > 32) 8576 return SDValue(); 8577 8578 SDValue N0 = N->getOperand(0); 8579 8580 SDValue Shl; 8581 ConstantSDNode *AddC = nullptr; 8582 8583 // We might have an ADD or SUB between the SRA and SHL. 8584 bool IsAdd = N0.getOpcode() == ISD::ADD; 8585 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8586 if (!N0.hasOneUse()) 8587 return SDValue(); 8588 // Other operand needs to be a constant we can modify. 8589 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8590 if (!AddC) 8591 return SDValue(); 8592 8593 // AddC needs to have at least 32 trailing zeros. 8594 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8595 return SDValue(); 8596 8597 Shl = N0.getOperand(IsAdd ? 0 : 1); 8598 } else { 8599 // Not an ADD or SUB. 8600 Shl = N0; 8601 } 8602 8603 // Look for a shift left by 32. 8604 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8605 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8606 Shl.getConstantOperandVal(1) != 32) 8607 return SDValue(); 8608 8609 SDLoc DL(N); 8610 SDValue In = Shl.getOperand(0); 8611 8612 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8613 // constant. 8614 if (AddC) { 8615 SDValue ShiftedAddC = 8616 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8617 if (IsAdd) 8618 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8619 else 8620 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8621 } 8622 8623 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8624 DAG.getValueType(MVT::i32)); 8625 if (ShAmtC->getZExtValue() == 32) 8626 return SExt; 8627 8628 return DAG.getNode( 8629 ISD::SHL, DL, MVT::i64, SExt, 8630 DAG.getConstant(32 - ShAmtC->getZExtValue(), DL, MVT::i64)); 8631 } 8632 8633 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8634 DAGCombinerInfo &DCI) const { 8635 SelectionDAG &DAG = DCI.DAG; 8636 8637 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8638 // bits are demanded. N will be added to the Worklist if it was not deleted. 8639 // Caller should return SDValue(N, 0) if this returns true. 8640 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8641 SDValue Op = N->getOperand(OpNo); 8642 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8643 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8644 return false; 8645 8646 if (N->getOpcode() != ISD::DELETED_NODE) 8647 DCI.AddToWorklist(N); 8648 return true; 8649 }; 8650 8651 switch (N->getOpcode()) { 8652 default: 8653 break; 8654 case RISCVISD::SplitF64: { 8655 SDValue Op0 = N->getOperand(0); 8656 // If the input to SplitF64 is just BuildPairF64 then the operation is 8657 // redundant. Instead, use BuildPairF64's operands directly. 8658 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8659 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8660 8661 if (Op0->isUndef()) { 8662 SDValue Lo = DAG.getUNDEF(MVT::i32); 8663 SDValue Hi = DAG.getUNDEF(MVT::i32); 8664 return DCI.CombineTo(N, Lo, Hi); 8665 } 8666 8667 SDLoc DL(N); 8668 8669 // It's cheaper to materialise two 32-bit integers than to load a double 8670 // from the constant pool and transfer it to integer registers through the 8671 // stack. 8672 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8673 APInt V = C->getValueAPF().bitcastToAPInt(); 8674 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8675 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8676 return DCI.CombineTo(N, Lo, Hi); 8677 } 8678 8679 // This is a target-specific version of a DAGCombine performed in 8680 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8681 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8682 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8683 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8684 !Op0.getNode()->hasOneUse()) 8685 break; 8686 SDValue NewSplitF64 = 8687 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8688 Op0.getOperand(0)); 8689 SDValue Lo = NewSplitF64.getValue(0); 8690 SDValue Hi = NewSplitF64.getValue(1); 8691 APInt SignBit = APInt::getSignMask(32); 8692 if (Op0.getOpcode() == ISD::FNEG) { 8693 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8694 DAG.getConstant(SignBit, DL, MVT::i32)); 8695 return DCI.CombineTo(N, Lo, NewHi); 8696 } 8697 assert(Op0.getOpcode() == ISD::FABS); 8698 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8699 DAG.getConstant(~SignBit, DL, MVT::i32)); 8700 return DCI.CombineTo(N, Lo, NewHi); 8701 } 8702 case RISCVISD::SLLW: 8703 case RISCVISD::SRAW: 8704 case RISCVISD::SRLW: { 8705 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8706 if (SimplifyDemandedLowBitsHelper(0, 32) || 8707 SimplifyDemandedLowBitsHelper(1, 5)) 8708 return SDValue(N, 0); 8709 8710 break; 8711 } 8712 case ISD::ROTR: 8713 case ISD::ROTL: 8714 case RISCVISD::RORW: 8715 case RISCVISD::ROLW: { 8716 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8717 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8718 if (SimplifyDemandedLowBitsHelper(0, 32) || 8719 SimplifyDemandedLowBitsHelper(1, 5)) 8720 return SDValue(N, 0); 8721 } 8722 8723 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8724 } 8725 case RISCVISD::CLZW: 8726 case RISCVISD::CTZW: { 8727 // Only the lower 32 bits of the first operand are read 8728 if (SimplifyDemandedLowBitsHelper(0, 32)) 8729 return SDValue(N, 0); 8730 break; 8731 } 8732 case RISCVISD::GREV: 8733 case RISCVISD::GORC: { 8734 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8735 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8736 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8737 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8738 return SDValue(N, 0); 8739 8740 return combineGREVI_GORCI(N, DAG); 8741 } 8742 case RISCVISD::GREVW: 8743 case RISCVISD::GORCW: { 8744 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8745 if (SimplifyDemandedLowBitsHelper(0, 32) || 8746 SimplifyDemandedLowBitsHelper(1, 5)) 8747 return SDValue(N, 0); 8748 8749 break; 8750 } 8751 case RISCVISD::SHFL: 8752 case RISCVISD::UNSHFL: { 8753 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8754 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8755 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8756 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8757 return SDValue(N, 0); 8758 8759 break; 8760 } 8761 case RISCVISD::SHFLW: 8762 case RISCVISD::UNSHFLW: { 8763 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8764 if (SimplifyDemandedLowBitsHelper(0, 32) || 8765 SimplifyDemandedLowBitsHelper(1, 4)) 8766 return SDValue(N, 0); 8767 8768 break; 8769 } 8770 case RISCVISD::BCOMPRESSW: 8771 case RISCVISD::BDECOMPRESSW: { 8772 // Only the lower 32 bits of LHS and RHS are read. 8773 if (SimplifyDemandedLowBitsHelper(0, 32) || 8774 SimplifyDemandedLowBitsHelper(1, 32)) 8775 return SDValue(N, 0); 8776 8777 break; 8778 } 8779 case RISCVISD::FSR: 8780 case RISCVISD::FSL: 8781 case RISCVISD::FSRW: 8782 case RISCVISD::FSLW: { 8783 bool IsWInstruction = 8784 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8785 unsigned BitWidth = 8786 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8787 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8788 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8789 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8790 return SDValue(N, 0); 8791 8792 break; 8793 } 8794 case RISCVISD::FMV_X_ANYEXTH: 8795 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8796 SDLoc DL(N); 8797 SDValue Op0 = N->getOperand(0); 8798 MVT VT = N->getSimpleValueType(0); 8799 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8800 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8801 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8802 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8803 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8804 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8805 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8806 assert(Op0.getOperand(0).getValueType() == VT && 8807 "Unexpected value type!"); 8808 return Op0.getOperand(0); 8809 } 8810 8811 // This is a target-specific version of a DAGCombine performed in 8812 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8813 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8814 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8815 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8816 !Op0.getNode()->hasOneUse()) 8817 break; 8818 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8819 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8820 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8821 if (Op0.getOpcode() == ISD::FNEG) 8822 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8823 DAG.getConstant(SignBit, DL, VT)); 8824 8825 assert(Op0.getOpcode() == ISD::FABS); 8826 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8827 DAG.getConstant(~SignBit, DL, VT)); 8828 } 8829 case ISD::ADD: 8830 return performADDCombine(N, DAG, Subtarget); 8831 case ISD::SUB: 8832 return performSUBCombine(N, DAG); 8833 case ISD::AND: 8834 return performANDCombine(N, DAG, Subtarget); 8835 case ISD::OR: 8836 return performORCombine(N, DAG, Subtarget); 8837 case ISD::XOR: 8838 return performXORCombine(N, DAG); 8839 case ISD::FADD: 8840 case ISD::UMAX: 8841 case ISD::UMIN: 8842 case ISD::SMAX: 8843 case ISD::SMIN: 8844 case ISD::FMAXNUM: 8845 case ISD::FMINNUM: 8846 return combineBinOpToReduce(N, DAG); 8847 case ISD::SIGN_EXTEND_INREG: 8848 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8849 case ISD::ZERO_EXTEND: 8850 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8851 // type legalization. This is safe because fp_to_uint produces poison if 8852 // it overflows. 8853 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8854 SDValue Src = N->getOperand(0); 8855 if (Src.getOpcode() == ISD::FP_TO_UINT && 8856 isTypeLegal(Src.getOperand(0).getValueType())) 8857 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8858 Src.getOperand(0)); 8859 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8860 isTypeLegal(Src.getOperand(1).getValueType())) { 8861 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8862 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8863 Src.getOperand(0), Src.getOperand(1)); 8864 DCI.CombineTo(N, Res); 8865 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8866 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8867 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8868 } 8869 } 8870 return SDValue(); 8871 case RISCVISD::SELECT_CC: { 8872 // Transform 8873 SDValue LHS = N->getOperand(0); 8874 SDValue RHS = N->getOperand(1); 8875 SDValue TrueV = N->getOperand(3); 8876 SDValue FalseV = N->getOperand(4); 8877 8878 // If the True and False values are the same, we don't need a select_cc. 8879 if (TrueV == FalseV) 8880 return TrueV; 8881 8882 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8883 if (!ISD::isIntEqualitySetCC(CCVal)) 8884 break; 8885 8886 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8887 // (select_cc X, Y, lt, trueV, falseV) 8888 // Sometimes the setcc is introduced after select_cc has been formed. 8889 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8890 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8891 // If we're looking for eq 0 instead of ne 0, we need to invert the 8892 // condition. 8893 bool Invert = CCVal == ISD::SETEQ; 8894 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8895 if (Invert) 8896 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8897 8898 SDLoc DL(N); 8899 RHS = LHS.getOperand(1); 8900 LHS = LHS.getOperand(0); 8901 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8902 8903 SDValue TargetCC = DAG.getCondCode(CCVal); 8904 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8905 {LHS, RHS, TargetCC, TrueV, FalseV}); 8906 } 8907 8908 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8909 // (select_cc X, Y, eq/ne, trueV, falseV) 8910 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8911 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8912 {LHS.getOperand(0), LHS.getOperand(1), 8913 N->getOperand(2), TrueV, FalseV}); 8914 // (select_cc X, 1, setne, trueV, falseV) -> 8915 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8916 // This can occur when legalizing some floating point comparisons. 8917 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8918 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8919 SDLoc DL(N); 8920 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8921 SDValue TargetCC = DAG.getCondCode(CCVal); 8922 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8923 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8924 {LHS, RHS, TargetCC, TrueV, FalseV}); 8925 } 8926 8927 break; 8928 } 8929 case RISCVISD::BR_CC: { 8930 SDValue LHS = N->getOperand(1); 8931 SDValue RHS = N->getOperand(2); 8932 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8933 if (!ISD::isIntEqualitySetCC(CCVal)) 8934 break; 8935 8936 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8937 // (br_cc X, Y, lt, dest) 8938 // Sometimes the setcc is introduced after br_cc has been formed. 8939 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8940 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8941 // If we're looking for eq 0 instead of ne 0, we need to invert the 8942 // condition. 8943 bool Invert = CCVal == ISD::SETEQ; 8944 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8945 if (Invert) 8946 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8947 8948 SDLoc DL(N); 8949 RHS = LHS.getOperand(1); 8950 LHS = LHS.getOperand(0); 8951 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8952 8953 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8954 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8955 N->getOperand(4)); 8956 } 8957 8958 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8959 // (br_cc X, Y, eq/ne, trueV, falseV) 8960 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8961 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8962 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8963 N->getOperand(3), N->getOperand(4)); 8964 8965 // (br_cc X, 1, setne, br_cc) -> 8966 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8967 // This can occur when legalizing some floating point comparisons. 8968 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8969 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8970 SDLoc DL(N); 8971 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8972 SDValue TargetCC = DAG.getCondCode(CCVal); 8973 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8974 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8975 N->getOperand(0), LHS, RHS, TargetCC, 8976 N->getOperand(4)); 8977 } 8978 break; 8979 } 8980 case ISD::BITREVERSE: 8981 return performBITREVERSECombine(N, DAG, Subtarget); 8982 case ISD::FP_TO_SINT: 8983 case ISD::FP_TO_UINT: 8984 return performFP_TO_INTCombine(N, DCI, Subtarget); 8985 case ISD::FP_TO_SINT_SAT: 8986 case ISD::FP_TO_UINT_SAT: 8987 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8988 case ISD::FCOPYSIGN: { 8989 EVT VT = N->getValueType(0); 8990 if (!VT.isVector()) 8991 break; 8992 // There is a form of VFSGNJ which injects the negated sign of its second 8993 // operand. Try and bubble any FNEG up after the extend/round to produce 8994 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8995 // TRUNC=1. 8996 SDValue In2 = N->getOperand(1); 8997 // Avoid cases where the extend/round has multiple uses, as duplicating 8998 // those is typically more expensive than removing a fneg. 8999 if (!In2.hasOneUse()) 9000 break; 9001 if (In2.getOpcode() != ISD::FP_EXTEND && 9002 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 9003 break; 9004 In2 = In2.getOperand(0); 9005 if (In2.getOpcode() != ISD::FNEG) 9006 break; 9007 SDLoc DL(N); 9008 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 9009 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 9010 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 9011 } 9012 case ISD::MGATHER: 9013 case ISD::MSCATTER: 9014 case ISD::VP_GATHER: 9015 case ISD::VP_SCATTER: { 9016 if (!DCI.isBeforeLegalize()) 9017 break; 9018 SDValue Index, ScaleOp; 9019 bool IsIndexScaled = false; 9020 bool IsIndexSigned = false; 9021 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 9022 Index = VPGSN->getIndex(); 9023 ScaleOp = VPGSN->getScale(); 9024 IsIndexScaled = VPGSN->isIndexScaled(); 9025 IsIndexSigned = VPGSN->isIndexSigned(); 9026 } else { 9027 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9028 Index = MGSN->getIndex(); 9029 ScaleOp = MGSN->getScale(); 9030 IsIndexScaled = MGSN->isIndexScaled(); 9031 IsIndexSigned = MGSN->isIndexSigned(); 9032 } 9033 EVT IndexVT = Index.getValueType(); 9034 MVT XLenVT = Subtarget.getXLenVT(); 9035 // RISCV indexed loads only support the "unsigned unscaled" addressing 9036 // mode, so anything else must be manually legalized. 9037 bool NeedsIdxLegalization = 9038 IsIndexScaled || 9039 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9040 if (!NeedsIdxLegalization) 9041 break; 9042 9043 SDLoc DL(N); 9044 9045 // Any index legalization should first promote to XLenVT, so we don't lose 9046 // bits when scaling. This may create an illegal index type so we let 9047 // LLVM's legalization take care of the splitting. 9048 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9049 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9050 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9051 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9052 DL, IndexVT, Index); 9053 } 9054 9055 if (IsIndexScaled) { 9056 // Manually scale the indices. 9057 // TODO: Sanitize the scale operand here? 9058 // TODO: For VP nodes, should we use VP_SHL here? 9059 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9060 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9061 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9062 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9063 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9064 } 9065 9066 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9067 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9068 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9069 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9070 ScaleOp, VPGN->getMask(), 9071 VPGN->getVectorLength()}, 9072 VPGN->getMemOperand(), NewIndexTy); 9073 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9074 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9075 {VPSN->getChain(), VPSN->getValue(), 9076 VPSN->getBasePtr(), Index, ScaleOp, 9077 VPSN->getMask(), VPSN->getVectorLength()}, 9078 VPSN->getMemOperand(), NewIndexTy); 9079 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9080 return DAG.getMaskedGather( 9081 N->getVTList(), MGN->getMemoryVT(), DL, 9082 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9083 MGN->getBasePtr(), Index, ScaleOp}, 9084 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9085 const auto *MSN = cast<MaskedScatterSDNode>(N); 9086 return DAG.getMaskedScatter( 9087 N->getVTList(), MSN->getMemoryVT(), DL, 9088 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9089 Index, ScaleOp}, 9090 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9091 } 9092 case RISCVISD::SRA_VL: 9093 case RISCVISD::SRL_VL: 9094 case RISCVISD::SHL_VL: { 9095 SDValue ShAmt = N->getOperand(1); 9096 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9097 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9098 SDLoc DL(N); 9099 SDValue VL = N->getOperand(3); 9100 EVT VT = N->getValueType(0); 9101 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9102 ShAmt.getOperand(1), VL); 9103 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9104 N->getOperand(2), N->getOperand(3)); 9105 } 9106 break; 9107 } 9108 case ISD::SRA: 9109 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9110 return V; 9111 LLVM_FALLTHROUGH; 9112 case ISD::SRL: 9113 case ISD::SHL: { 9114 SDValue ShAmt = N->getOperand(1); 9115 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9116 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9117 SDLoc DL(N); 9118 EVT VT = N->getValueType(0); 9119 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9120 ShAmt.getOperand(1), 9121 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9122 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9123 } 9124 break; 9125 } 9126 case RISCVISD::ADD_VL: 9127 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9128 return V; 9129 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9130 case RISCVISD::SUB_VL: 9131 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9132 case RISCVISD::VWADD_W_VL: 9133 case RISCVISD::VWADDU_W_VL: 9134 case RISCVISD::VWSUB_W_VL: 9135 case RISCVISD::VWSUBU_W_VL: 9136 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9137 case RISCVISD::MUL_VL: 9138 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9139 return V; 9140 // Mul is commutative. 9141 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9142 case RISCVISD::VFMADD_VL: 9143 case RISCVISD::VFNMADD_VL: 9144 case RISCVISD::VFMSUB_VL: 9145 case RISCVISD::VFNMSUB_VL: { 9146 // Fold FNEG_VL into FMA opcodes. 9147 SDValue A = N->getOperand(0); 9148 SDValue B = N->getOperand(1); 9149 SDValue C = N->getOperand(2); 9150 SDValue Mask = N->getOperand(3); 9151 SDValue VL = N->getOperand(4); 9152 9153 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9154 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9155 V.getOperand(2) == VL) { 9156 // Return the negated input. 9157 V = V.getOperand(0); 9158 return true; 9159 } 9160 9161 return false; 9162 }; 9163 9164 bool NegA = invertIfNegative(A); 9165 bool NegB = invertIfNegative(B); 9166 bool NegC = invertIfNegative(C); 9167 9168 // If no operands are negated, we're done. 9169 if (!NegA && !NegB && !NegC) 9170 return SDValue(); 9171 9172 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9173 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9174 VL); 9175 } 9176 case ISD::STORE: { 9177 auto *Store = cast<StoreSDNode>(N); 9178 SDValue Val = Store->getValue(); 9179 // Combine store of vmv.x.s to vse with VL of 1. 9180 // FIXME: Support FP. 9181 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9182 SDValue Src = Val.getOperand(0); 9183 EVT VecVT = Src.getValueType(); 9184 EVT MemVT = Store->getMemoryVT(); 9185 // The memory VT and the element type must match. 9186 if (VecVT.getVectorElementType() == MemVT) { 9187 SDLoc DL(N); 9188 MVT MaskVT = getMaskTypeFor(VecVT); 9189 return DAG.getStoreVP( 9190 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9191 DAG.getConstant(1, DL, MaskVT), 9192 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9193 Store->getMemOperand(), Store->getAddressingMode(), 9194 Store->isTruncatingStore(), /*IsCompress*/ false); 9195 } 9196 } 9197 9198 break; 9199 } 9200 case ISD::SPLAT_VECTOR: { 9201 EVT VT = N->getValueType(0); 9202 // Only perform this combine on legal MVT types. 9203 if (!isTypeLegal(VT)) 9204 break; 9205 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9206 DAG, Subtarget)) 9207 return Gather; 9208 break; 9209 } 9210 case RISCVISD::VMV_V_X_VL: { 9211 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9212 // scalar input. 9213 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9214 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9215 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9216 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9217 return SDValue(N, 0); 9218 9219 break; 9220 } 9221 case ISD::INTRINSIC_WO_CHAIN: { 9222 unsigned IntNo = N->getConstantOperandVal(0); 9223 switch (IntNo) { 9224 // By default we do not combine any intrinsic. 9225 default: 9226 return SDValue(); 9227 case Intrinsic::riscv_vcpop: 9228 case Intrinsic::riscv_vcpop_mask: 9229 case Intrinsic::riscv_vfirst: 9230 case Intrinsic::riscv_vfirst_mask: { 9231 SDValue VL = N->getOperand(2); 9232 if (IntNo == Intrinsic::riscv_vcpop_mask || 9233 IntNo == Intrinsic::riscv_vfirst_mask) 9234 VL = N->getOperand(3); 9235 if (!isNullConstant(VL)) 9236 return SDValue(); 9237 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9238 SDLoc DL(N); 9239 EVT VT = N->getValueType(0); 9240 if (IntNo == Intrinsic::riscv_vfirst || 9241 IntNo == Intrinsic::riscv_vfirst_mask) 9242 return DAG.getConstant(-1, DL, VT); 9243 return DAG.getConstant(0, DL, VT); 9244 } 9245 } 9246 } 9247 case ISD::BITCAST: { 9248 assert(Subtarget.useRVVForFixedLengthVectors()); 9249 SDValue N0 = N->getOperand(0); 9250 EVT VT = N->getValueType(0); 9251 EVT SrcVT = N0.getValueType(); 9252 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9253 // type, widen both sides to avoid a trip through memory. 9254 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9255 VT.isScalarInteger()) { 9256 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9257 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9258 Ops[0] = N0; 9259 SDLoc DL(N); 9260 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9261 N0 = DAG.getBitcast(MVT::i8, N0); 9262 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9263 } 9264 9265 return SDValue(); 9266 } 9267 } 9268 9269 return SDValue(); 9270 } 9271 9272 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9273 const SDNode *N, CombineLevel Level) const { 9274 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9275 // materialised in fewer instructions than `(OP _, c1)`: 9276 // 9277 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9278 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9279 SDValue N0 = N->getOperand(0); 9280 EVT Ty = N0.getValueType(); 9281 if (Ty.isScalarInteger() && 9282 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9283 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9284 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9285 if (C1 && C2) { 9286 const APInt &C1Int = C1->getAPIntValue(); 9287 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9288 9289 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9290 // and the combine should happen, to potentially allow further combines 9291 // later. 9292 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9293 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9294 return true; 9295 9296 // We can materialise `c1` in an add immediate, so it's "free", and the 9297 // combine should be prevented. 9298 if (C1Int.getMinSignedBits() <= 64 && 9299 isLegalAddImmediate(C1Int.getSExtValue())) 9300 return false; 9301 9302 // Neither constant will fit into an immediate, so find materialisation 9303 // costs. 9304 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9305 Subtarget.getFeatureBits(), 9306 /*CompressionCost*/true); 9307 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9308 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9309 /*CompressionCost*/true); 9310 9311 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9312 // combine should be prevented. 9313 if (C1Cost < ShiftedC1Cost) 9314 return false; 9315 } 9316 } 9317 return true; 9318 } 9319 9320 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9321 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9322 TargetLoweringOpt &TLO) const { 9323 // Delay this optimization as late as possible. 9324 if (!TLO.LegalOps) 9325 return false; 9326 9327 EVT VT = Op.getValueType(); 9328 if (VT.isVector()) 9329 return false; 9330 9331 // Only handle AND for now. 9332 if (Op.getOpcode() != ISD::AND) 9333 return false; 9334 9335 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9336 if (!C) 9337 return false; 9338 9339 const APInt &Mask = C->getAPIntValue(); 9340 9341 // Clear all non-demanded bits initially. 9342 APInt ShrunkMask = Mask & DemandedBits; 9343 9344 // Try to make a smaller immediate by setting undemanded bits. 9345 9346 APInt ExpandedMask = Mask | ~DemandedBits; 9347 9348 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9349 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9350 }; 9351 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9352 if (NewMask == Mask) 9353 return true; 9354 SDLoc DL(Op); 9355 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9356 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9357 return TLO.CombineTo(Op, NewOp); 9358 }; 9359 9360 // If the shrunk mask fits in sign extended 12 bits, let the target 9361 // independent code apply it. 9362 if (ShrunkMask.isSignedIntN(12)) 9363 return false; 9364 9365 // Preserve (and X, 0xffff) when zext.h is supported. 9366 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9367 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9368 if (IsLegalMask(NewMask)) 9369 return UseMask(NewMask); 9370 } 9371 9372 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9373 if (VT == MVT::i64) { 9374 APInt NewMask = APInt(64, 0xffffffff); 9375 if (IsLegalMask(NewMask)) 9376 return UseMask(NewMask); 9377 } 9378 9379 // For the remaining optimizations, we need to be able to make a negative 9380 // number through a combination of mask and undemanded bits. 9381 if (!ExpandedMask.isNegative()) 9382 return false; 9383 9384 // What is the fewest number of bits we need to represent the negative number. 9385 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9386 9387 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9388 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9389 APInt NewMask = ShrunkMask; 9390 if (MinSignedBits <= 12) 9391 NewMask.setBitsFrom(11); 9392 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9393 NewMask.setBitsFrom(31); 9394 else 9395 return false; 9396 9397 // Check that our new mask is a subset of the demanded mask. 9398 assert(IsLegalMask(NewMask)); 9399 return UseMask(NewMask); 9400 } 9401 9402 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9403 static const uint64_t GREVMasks[] = { 9404 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9405 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9406 9407 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9408 unsigned Shift = 1 << Stage; 9409 if (ShAmt & Shift) { 9410 uint64_t Mask = GREVMasks[Stage]; 9411 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9412 if (IsGORC) 9413 Res |= x; 9414 x = Res; 9415 } 9416 } 9417 9418 return x; 9419 } 9420 9421 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9422 KnownBits &Known, 9423 const APInt &DemandedElts, 9424 const SelectionDAG &DAG, 9425 unsigned Depth) const { 9426 unsigned BitWidth = Known.getBitWidth(); 9427 unsigned Opc = Op.getOpcode(); 9428 assert((Opc >= ISD::BUILTIN_OP_END || 9429 Opc == ISD::INTRINSIC_WO_CHAIN || 9430 Opc == ISD::INTRINSIC_W_CHAIN || 9431 Opc == ISD::INTRINSIC_VOID) && 9432 "Should use MaskedValueIsZero if you don't know whether Op" 9433 " is a target node!"); 9434 9435 Known.resetAll(); 9436 switch (Opc) { 9437 default: break; 9438 case RISCVISD::SELECT_CC: { 9439 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9440 // If we don't know any bits, early out. 9441 if (Known.isUnknown()) 9442 break; 9443 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9444 9445 // Only known if known in both the LHS and RHS. 9446 Known = KnownBits::commonBits(Known, Known2); 9447 break; 9448 } 9449 case RISCVISD::REMUW: { 9450 KnownBits Known2; 9451 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9452 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9453 // We only care about the lower 32 bits. 9454 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9455 // Restore the original width by sign extending. 9456 Known = Known.sext(BitWidth); 9457 break; 9458 } 9459 case RISCVISD::DIVUW: { 9460 KnownBits Known2; 9461 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9462 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9463 // We only care about the lower 32 bits. 9464 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9465 // Restore the original width by sign extending. 9466 Known = Known.sext(BitWidth); 9467 break; 9468 } 9469 case RISCVISD::CTZW: { 9470 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9471 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9472 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9473 Known.Zero.setBitsFrom(LowBits); 9474 break; 9475 } 9476 case RISCVISD::CLZW: { 9477 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9478 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9479 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9480 Known.Zero.setBitsFrom(LowBits); 9481 break; 9482 } 9483 case RISCVISD::GREV: 9484 case RISCVISD::GORC: { 9485 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9486 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9487 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9488 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9489 // To compute zeros, we need to invert the value and invert it back after. 9490 Known.Zero = 9491 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9492 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9493 } 9494 break; 9495 } 9496 case RISCVISD::READ_VLENB: { 9497 // We can use the minimum and maximum VLEN values to bound VLENB. We 9498 // know VLEN must be a power of two. 9499 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9500 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9501 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9502 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9503 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9504 if (MaxVLenB == MinVLenB) 9505 Known.One.setBit(Log2_32(MinVLenB)); 9506 break; 9507 } 9508 case ISD::INTRINSIC_W_CHAIN: 9509 case ISD::INTRINSIC_WO_CHAIN: { 9510 unsigned IntNo = 9511 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9512 switch (IntNo) { 9513 default: 9514 // We can't do anything for most intrinsics. 9515 break; 9516 case Intrinsic::riscv_vsetvli: 9517 case Intrinsic::riscv_vsetvlimax: 9518 case Intrinsic::riscv_vsetvli_opt: 9519 case Intrinsic::riscv_vsetvlimax_opt: 9520 // Assume that VL output is positive and would fit in an int32_t. 9521 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9522 if (BitWidth >= 32) 9523 Known.Zero.setBitsFrom(31); 9524 break; 9525 } 9526 break; 9527 } 9528 } 9529 } 9530 9531 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9532 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9533 unsigned Depth) const { 9534 switch (Op.getOpcode()) { 9535 default: 9536 break; 9537 case RISCVISD::SELECT_CC: { 9538 unsigned Tmp = 9539 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9540 if (Tmp == 1) return 1; // Early out. 9541 unsigned Tmp2 = 9542 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9543 return std::min(Tmp, Tmp2); 9544 } 9545 case RISCVISD::SLLW: 9546 case RISCVISD::SRAW: 9547 case RISCVISD::SRLW: 9548 case RISCVISD::DIVW: 9549 case RISCVISD::DIVUW: 9550 case RISCVISD::REMUW: 9551 case RISCVISD::ROLW: 9552 case RISCVISD::RORW: 9553 case RISCVISD::GREVW: 9554 case RISCVISD::GORCW: 9555 case RISCVISD::FSLW: 9556 case RISCVISD::FSRW: 9557 case RISCVISD::SHFLW: 9558 case RISCVISD::UNSHFLW: 9559 case RISCVISD::BCOMPRESSW: 9560 case RISCVISD::BDECOMPRESSW: 9561 case RISCVISD::BFPW: 9562 case RISCVISD::FCVT_W_RV64: 9563 case RISCVISD::FCVT_WU_RV64: 9564 case RISCVISD::STRICT_FCVT_W_RV64: 9565 case RISCVISD::STRICT_FCVT_WU_RV64: 9566 // TODO: As the result is sign-extended, this is conservatively correct. A 9567 // more precise answer could be calculated for SRAW depending on known 9568 // bits in the shift amount. 9569 return 33; 9570 case RISCVISD::SHFL: 9571 case RISCVISD::UNSHFL: { 9572 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9573 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9574 // will stay within the upper 32 bits. If there were more than 32 sign bits 9575 // before there will be at least 33 sign bits after. 9576 if (Op.getValueType() == MVT::i64 && 9577 isa<ConstantSDNode>(Op.getOperand(1)) && 9578 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9579 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9580 if (Tmp > 32) 9581 return 33; 9582 } 9583 break; 9584 } 9585 case RISCVISD::VMV_X_S: { 9586 // The number of sign bits of the scalar result is computed by obtaining the 9587 // element type of the input vector operand, subtracting its width from the 9588 // XLEN, and then adding one (sign bit within the element type). If the 9589 // element type is wider than XLen, the least-significant XLEN bits are 9590 // taken. 9591 unsigned XLen = Subtarget.getXLen(); 9592 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9593 if (EltBits <= XLen) 9594 return XLen - EltBits + 1; 9595 break; 9596 } 9597 } 9598 9599 return 1; 9600 } 9601 9602 const Constant * 9603 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9604 assert(Ld && "Unexpected null LoadSDNode"); 9605 if (!ISD::isNormalLoad(Ld)) 9606 return nullptr; 9607 9608 SDValue Ptr = Ld->getBasePtr(); 9609 9610 // Only constant pools with no offset are supported. 9611 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9612 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9613 if (!CNode || CNode->isMachineConstantPoolEntry() || 9614 CNode->getOffset() != 0) 9615 return nullptr; 9616 9617 return CNode; 9618 }; 9619 9620 // Simple case, LLA. 9621 if (Ptr.getOpcode() == RISCVISD::LLA) { 9622 auto *CNode = GetSupportedConstantPool(Ptr); 9623 if (!CNode || CNode->getTargetFlags() != 0) 9624 return nullptr; 9625 9626 return CNode->getConstVal(); 9627 } 9628 9629 // Look for a HI and ADD_LO pair. 9630 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9631 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9632 return nullptr; 9633 9634 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9635 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9636 9637 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9638 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9639 return nullptr; 9640 9641 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9642 return nullptr; 9643 9644 return CNodeLo->getConstVal(); 9645 } 9646 9647 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9648 MachineBasicBlock *BB) { 9649 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9650 9651 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9652 // Should the count have wrapped while it was being read, we need to try 9653 // again. 9654 // ... 9655 // read: 9656 // rdcycleh x3 # load high word of cycle 9657 // rdcycle x2 # load low word of cycle 9658 // rdcycleh x4 # load high word of cycle 9659 // bne x3, x4, read # check if high word reads match, otherwise try again 9660 // ... 9661 9662 MachineFunction &MF = *BB->getParent(); 9663 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9664 MachineFunction::iterator It = ++BB->getIterator(); 9665 9666 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9667 MF.insert(It, LoopMBB); 9668 9669 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9670 MF.insert(It, DoneMBB); 9671 9672 // Transfer the remainder of BB and its successor edges to DoneMBB. 9673 DoneMBB->splice(DoneMBB->begin(), BB, 9674 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9675 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9676 9677 BB->addSuccessor(LoopMBB); 9678 9679 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9680 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9681 Register LoReg = MI.getOperand(0).getReg(); 9682 Register HiReg = MI.getOperand(1).getReg(); 9683 DebugLoc DL = MI.getDebugLoc(); 9684 9685 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9686 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9687 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9688 .addReg(RISCV::X0); 9689 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9690 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9691 .addReg(RISCV::X0); 9692 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9693 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9694 .addReg(RISCV::X0); 9695 9696 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9697 .addReg(HiReg) 9698 .addReg(ReadAgainReg) 9699 .addMBB(LoopMBB); 9700 9701 LoopMBB->addSuccessor(LoopMBB); 9702 LoopMBB->addSuccessor(DoneMBB); 9703 9704 MI.eraseFromParent(); 9705 9706 return DoneMBB; 9707 } 9708 9709 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9710 MachineBasicBlock *BB) { 9711 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9712 9713 MachineFunction &MF = *BB->getParent(); 9714 DebugLoc DL = MI.getDebugLoc(); 9715 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9716 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9717 Register LoReg = MI.getOperand(0).getReg(); 9718 Register HiReg = MI.getOperand(1).getReg(); 9719 Register SrcReg = MI.getOperand(2).getReg(); 9720 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9721 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9722 9723 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9724 RI); 9725 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9726 MachineMemOperand *MMOLo = 9727 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9728 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9729 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9730 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9731 .addFrameIndex(FI) 9732 .addImm(0) 9733 .addMemOperand(MMOLo); 9734 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9735 .addFrameIndex(FI) 9736 .addImm(4) 9737 .addMemOperand(MMOHi); 9738 MI.eraseFromParent(); // The pseudo instruction is gone now. 9739 return BB; 9740 } 9741 9742 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9743 MachineBasicBlock *BB) { 9744 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9745 "Unexpected instruction"); 9746 9747 MachineFunction &MF = *BB->getParent(); 9748 DebugLoc DL = MI.getDebugLoc(); 9749 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9750 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9751 Register DstReg = MI.getOperand(0).getReg(); 9752 Register LoReg = MI.getOperand(1).getReg(); 9753 Register HiReg = MI.getOperand(2).getReg(); 9754 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9755 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9756 9757 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9758 MachineMemOperand *MMOLo = 9759 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9760 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9761 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9762 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9763 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9764 .addFrameIndex(FI) 9765 .addImm(0) 9766 .addMemOperand(MMOLo); 9767 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9768 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9769 .addFrameIndex(FI) 9770 .addImm(4) 9771 .addMemOperand(MMOHi); 9772 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9773 MI.eraseFromParent(); // The pseudo instruction is gone now. 9774 return BB; 9775 } 9776 9777 static bool isSelectPseudo(MachineInstr &MI) { 9778 switch (MI.getOpcode()) { 9779 default: 9780 return false; 9781 case RISCV::Select_GPR_Using_CC_GPR: 9782 case RISCV::Select_FPR16_Using_CC_GPR: 9783 case RISCV::Select_FPR32_Using_CC_GPR: 9784 case RISCV::Select_FPR64_Using_CC_GPR: 9785 return true; 9786 } 9787 } 9788 9789 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9790 unsigned RelOpcode, unsigned EqOpcode, 9791 const RISCVSubtarget &Subtarget) { 9792 DebugLoc DL = MI.getDebugLoc(); 9793 Register DstReg = MI.getOperand(0).getReg(); 9794 Register Src1Reg = MI.getOperand(1).getReg(); 9795 Register Src2Reg = MI.getOperand(2).getReg(); 9796 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9797 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9798 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9799 9800 // Save the current FFLAGS. 9801 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9802 9803 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9804 .addReg(Src1Reg) 9805 .addReg(Src2Reg); 9806 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9807 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9808 9809 // Restore the FFLAGS. 9810 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9811 .addReg(SavedFFlags, RegState::Kill); 9812 9813 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9814 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9815 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9816 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9817 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9818 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9819 9820 // Erase the pseudoinstruction. 9821 MI.eraseFromParent(); 9822 return BB; 9823 } 9824 9825 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9826 MachineBasicBlock *BB, 9827 const RISCVSubtarget &Subtarget) { 9828 // To "insert" Select_* instructions, we actually have to insert the triangle 9829 // control-flow pattern. The incoming instructions know the destination vreg 9830 // to set, the condition code register to branch on, the true/false values to 9831 // select between, and the condcode to use to select the appropriate branch. 9832 // 9833 // We produce the following control flow: 9834 // HeadMBB 9835 // | \ 9836 // | IfFalseMBB 9837 // | / 9838 // TailMBB 9839 // 9840 // When we find a sequence of selects we attempt to optimize their emission 9841 // by sharing the control flow. Currently we only handle cases where we have 9842 // multiple selects with the exact same condition (same LHS, RHS and CC). 9843 // The selects may be interleaved with other instructions if the other 9844 // instructions meet some requirements we deem safe: 9845 // - They are debug instructions. Otherwise, 9846 // - They do not have side-effects, do not access memory and their inputs do 9847 // not depend on the results of the select pseudo-instructions. 9848 // The TrueV/FalseV operands of the selects cannot depend on the result of 9849 // previous selects in the sequence. 9850 // These conditions could be further relaxed. See the X86 target for a 9851 // related approach and more information. 9852 Register LHS = MI.getOperand(1).getReg(); 9853 Register RHS = MI.getOperand(2).getReg(); 9854 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9855 9856 SmallVector<MachineInstr *, 4> SelectDebugValues; 9857 SmallSet<Register, 4> SelectDests; 9858 SelectDests.insert(MI.getOperand(0).getReg()); 9859 9860 MachineInstr *LastSelectPseudo = &MI; 9861 9862 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9863 SequenceMBBI != E; ++SequenceMBBI) { 9864 if (SequenceMBBI->isDebugInstr()) 9865 continue; 9866 if (isSelectPseudo(*SequenceMBBI)) { 9867 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9868 SequenceMBBI->getOperand(2).getReg() != RHS || 9869 SequenceMBBI->getOperand(3).getImm() != CC || 9870 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9871 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9872 break; 9873 LastSelectPseudo = &*SequenceMBBI; 9874 SequenceMBBI->collectDebugValues(SelectDebugValues); 9875 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9876 } else { 9877 if (SequenceMBBI->hasUnmodeledSideEffects() || 9878 SequenceMBBI->mayLoadOrStore()) 9879 break; 9880 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9881 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9882 })) 9883 break; 9884 } 9885 } 9886 9887 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9888 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9889 DebugLoc DL = MI.getDebugLoc(); 9890 MachineFunction::iterator I = ++BB->getIterator(); 9891 9892 MachineBasicBlock *HeadMBB = BB; 9893 MachineFunction *F = BB->getParent(); 9894 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9895 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9896 9897 F->insert(I, IfFalseMBB); 9898 F->insert(I, TailMBB); 9899 9900 // Transfer debug instructions associated with the selects to TailMBB. 9901 for (MachineInstr *DebugInstr : SelectDebugValues) { 9902 TailMBB->push_back(DebugInstr->removeFromParent()); 9903 } 9904 9905 // Move all instructions after the sequence to TailMBB. 9906 TailMBB->splice(TailMBB->end(), HeadMBB, 9907 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9908 // Update machine-CFG edges by transferring all successors of the current 9909 // block to the new block which will contain the Phi nodes for the selects. 9910 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9911 // Set the successors for HeadMBB. 9912 HeadMBB->addSuccessor(IfFalseMBB); 9913 HeadMBB->addSuccessor(TailMBB); 9914 9915 // Insert appropriate branch. 9916 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9917 .addReg(LHS) 9918 .addReg(RHS) 9919 .addMBB(TailMBB); 9920 9921 // IfFalseMBB just falls through to TailMBB. 9922 IfFalseMBB->addSuccessor(TailMBB); 9923 9924 // Create PHIs for all of the select pseudo-instructions. 9925 auto SelectMBBI = MI.getIterator(); 9926 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9927 auto InsertionPoint = TailMBB->begin(); 9928 while (SelectMBBI != SelectEnd) { 9929 auto Next = std::next(SelectMBBI); 9930 if (isSelectPseudo(*SelectMBBI)) { 9931 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9932 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9933 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9934 .addReg(SelectMBBI->getOperand(4).getReg()) 9935 .addMBB(HeadMBB) 9936 .addReg(SelectMBBI->getOperand(5).getReg()) 9937 .addMBB(IfFalseMBB); 9938 SelectMBBI->eraseFromParent(); 9939 } 9940 SelectMBBI = Next; 9941 } 9942 9943 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9944 return TailMBB; 9945 } 9946 9947 MachineBasicBlock * 9948 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9949 MachineBasicBlock *BB) const { 9950 switch (MI.getOpcode()) { 9951 default: 9952 llvm_unreachable("Unexpected instr type to insert"); 9953 case RISCV::ReadCycleWide: 9954 assert(!Subtarget.is64Bit() && 9955 "ReadCycleWrite is only to be used on riscv32"); 9956 return emitReadCycleWidePseudo(MI, BB); 9957 case RISCV::Select_GPR_Using_CC_GPR: 9958 case RISCV::Select_FPR16_Using_CC_GPR: 9959 case RISCV::Select_FPR32_Using_CC_GPR: 9960 case RISCV::Select_FPR64_Using_CC_GPR: 9961 return emitSelectPseudo(MI, BB, Subtarget); 9962 case RISCV::BuildPairF64Pseudo: 9963 return emitBuildPairF64Pseudo(MI, BB); 9964 case RISCV::SplitF64Pseudo: 9965 return emitSplitF64Pseudo(MI, BB); 9966 case RISCV::PseudoQuietFLE_H: 9967 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9968 case RISCV::PseudoQuietFLT_H: 9969 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9970 case RISCV::PseudoQuietFLE_S: 9971 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9972 case RISCV::PseudoQuietFLT_S: 9973 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9974 case RISCV::PseudoQuietFLE_D: 9975 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9976 case RISCV::PseudoQuietFLT_D: 9977 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9978 } 9979 } 9980 9981 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9982 SDNode *Node) const { 9983 // Add FRM dependency to any instructions with dynamic rounding mode. 9984 unsigned Opc = MI.getOpcode(); 9985 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9986 if (Idx < 0) 9987 return; 9988 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9989 return; 9990 // If the instruction already reads FRM, don't add another read. 9991 if (MI.readsRegister(RISCV::FRM)) 9992 return; 9993 MI.addOperand( 9994 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9995 } 9996 9997 // Calling Convention Implementation. 9998 // The expectations for frontend ABI lowering vary from target to target. 9999 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 10000 // details, but this is a longer term goal. For now, we simply try to keep the 10001 // role of the frontend as simple and well-defined as possible. The rules can 10002 // be summarised as: 10003 // * Never split up large scalar arguments. We handle them here. 10004 // * If a hardfloat calling convention is being used, and the struct may be 10005 // passed in a pair of registers (fp+fp, int+fp), and both registers are 10006 // available, then pass as two separate arguments. If either the GPRs or FPRs 10007 // are exhausted, then pass according to the rule below. 10008 // * If a struct could never be passed in registers or directly in a stack 10009 // slot (as it is larger than 2*XLEN and the floating point rules don't 10010 // apply), then pass it using a pointer with the byval attribute. 10011 // * If a struct is less than 2*XLEN, then coerce to either a two-element 10012 // word-sized array or a 2*XLEN scalar (depending on alignment). 10013 // * The frontend can determine whether a struct is returned by reference or 10014 // not based on its size and fields. If it will be returned by reference, the 10015 // frontend must modify the prototype so a pointer with the sret annotation is 10016 // passed as the first argument. This is not necessary for large scalar 10017 // returns. 10018 // * Struct return values and varargs should be coerced to structs containing 10019 // register-size fields in the same situations they would be for fixed 10020 // arguments. 10021 10022 static const MCPhysReg ArgGPRs[] = { 10023 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 10024 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 10025 }; 10026 static const MCPhysReg ArgFPR16s[] = { 10027 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10028 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10029 }; 10030 static const MCPhysReg ArgFPR32s[] = { 10031 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10032 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10033 }; 10034 static const MCPhysReg ArgFPR64s[] = { 10035 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10036 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10037 }; 10038 // This is an interim calling convention and it may be changed in the future. 10039 static const MCPhysReg ArgVRs[] = { 10040 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10041 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10042 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10043 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10044 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10045 RISCV::V20M2, RISCV::V22M2}; 10046 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10047 RISCV::V20M4}; 10048 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10049 10050 // Pass a 2*XLEN argument that has been split into two XLEN values through 10051 // registers or the stack as necessary. 10052 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10053 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10054 MVT ValVT2, MVT LocVT2, 10055 ISD::ArgFlagsTy ArgFlags2) { 10056 unsigned XLenInBytes = XLen / 8; 10057 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10058 // At least one half can be passed via register. 10059 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10060 VA1.getLocVT(), CCValAssign::Full)); 10061 } else { 10062 // Both halves must be passed on the stack, with proper alignment. 10063 Align StackAlign = 10064 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10065 State.addLoc( 10066 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10067 State.AllocateStack(XLenInBytes, StackAlign), 10068 VA1.getLocVT(), CCValAssign::Full)); 10069 State.addLoc(CCValAssign::getMem( 10070 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10071 LocVT2, CCValAssign::Full)); 10072 return false; 10073 } 10074 10075 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10076 // The second half can also be passed via register. 10077 State.addLoc( 10078 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10079 } else { 10080 // The second half is passed via the stack, without additional alignment. 10081 State.addLoc(CCValAssign::getMem( 10082 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10083 LocVT2, CCValAssign::Full)); 10084 } 10085 10086 return false; 10087 } 10088 10089 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10090 Optional<unsigned> FirstMaskArgument, 10091 CCState &State, const RISCVTargetLowering &TLI) { 10092 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10093 if (RC == &RISCV::VRRegClass) { 10094 // Assign the first mask argument to V0. 10095 // This is an interim calling convention and it may be changed in the 10096 // future. 10097 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10098 return State.AllocateReg(RISCV::V0); 10099 return State.AllocateReg(ArgVRs); 10100 } 10101 if (RC == &RISCV::VRM2RegClass) 10102 return State.AllocateReg(ArgVRM2s); 10103 if (RC == &RISCV::VRM4RegClass) 10104 return State.AllocateReg(ArgVRM4s); 10105 if (RC == &RISCV::VRM8RegClass) 10106 return State.AllocateReg(ArgVRM8s); 10107 llvm_unreachable("Unhandled register class for ValueType"); 10108 } 10109 10110 // Implements the RISC-V calling convention. Returns true upon failure. 10111 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10112 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10113 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10114 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10115 Optional<unsigned> FirstMaskArgument) { 10116 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10117 assert(XLen == 32 || XLen == 64); 10118 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10119 10120 // Any return value split in to more than two values can't be returned 10121 // directly. Vectors are returned via the available vector registers. 10122 if (!LocVT.isVector() && IsRet && ValNo > 1) 10123 return true; 10124 10125 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10126 // variadic argument, or if no F16/F32 argument registers are available. 10127 bool UseGPRForF16_F32 = true; 10128 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10129 // variadic argument, or if no F64 argument registers are available. 10130 bool UseGPRForF64 = true; 10131 10132 switch (ABI) { 10133 default: 10134 llvm_unreachable("Unexpected ABI"); 10135 case RISCVABI::ABI_ILP32: 10136 case RISCVABI::ABI_LP64: 10137 break; 10138 case RISCVABI::ABI_ILP32F: 10139 case RISCVABI::ABI_LP64F: 10140 UseGPRForF16_F32 = !IsFixed; 10141 break; 10142 case RISCVABI::ABI_ILP32D: 10143 case RISCVABI::ABI_LP64D: 10144 UseGPRForF16_F32 = !IsFixed; 10145 UseGPRForF64 = !IsFixed; 10146 break; 10147 } 10148 10149 // FPR16, FPR32, and FPR64 alias each other. 10150 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10151 UseGPRForF16_F32 = true; 10152 UseGPRForF64 = true; 10153 } 10154 10155 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10156 // similar local variables rather than directly checking against the target 10157 // ABI. 10158 10159 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10160 LocVT = XLenVT; 10161 LocInfo = CCValAssign::BCvt; 10162 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10163 LocVT = MVT::i64; 10164 LocInfo = CCValAssign::BCvt; 10165 } 10166 10167 // If this is a variadic argument, the RISC-V calling convention requires 10168 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10169 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10170 // be used regardless of whether the original argument was split during 10171 // legalisation or not. The argument will not be passed by registers if the 10172 // original type is larger than 2*XLEN, so the register alignment rule does 10173 // not apply. 10174 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10175 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10176 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10177 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10178 // Skip 'odd' register if necessary. 10179 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10180 State.AllocateReg(ArgGPRs); 10181 } 10182 10183 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10184 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10185 State.getPendingArgFlags(); 10186 10187 assert(PendingLocs.size() == PendingArgFlags.size() && 10188 "PendingLocs and PendingArgFlags out of sync"); 10189 10190 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10191 // registers are exhausted. 10192 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10193 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10194 "Can't lower f64 if it is split"); 10195 // Depending on available argument GPRS, f64 may be passed in a pair of 10196 // GPRs, split between a GPR and the stack, or passed completely on the 10197 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10198 // cases. 10199 Register Reg = State.AllocateReg(ArgGPRs); 10200 LocVT = MVT::i32; 10201 if (!Reg) { 10202 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10203 State.addLoc( 10204 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10205 return false; 10206 } 10207 if (!State.AllocateReg(ArgGPRs)) 10208 State.AllocateStack(4, Align(4)); 10209 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10210 return false; 10211 } 10212 10213 // Fixed-length vectors are located in the corresponding scalable-vector 10214 // container types. 10215 if (ValVT.isFixedLengthVector()) 10216 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10217 10218 // Split arguments might be passed indirectly, so keep track of the pending 10219 // values. Split vectors are passed via a mix of registers and indirectly, so 10220 // treat them as we would any other argument. 10221 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10222 LocVT = XLenVT; 10223 LocInfo = CCValAssign::Indirect; 10224 PendingLocs.push_back( 10225 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10226 PendingArgFlags.push_back(ArgFlags); 10227 if (!ArgFlags.isSplitEnd()) { 10228 return false; 10229 } 10230 } 10231 10232 // If the split argument only had two elements, it should be passed directly 10233 // in registers or on the stack. 10234 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10235 PendingLocs.size() <= 2) { 10236 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10237 // Apply the normal calling convention rules to the first half of the 10238 // split argument. 10239 CCValAssign VA = PendingLocs[0]; 10240 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10241 PendingLocs.clear(); 10242 PendingArgFlags.clear(); 10243 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10244 ArgFlags); 10245 } 10246 10247 // Allocate to a register if possible, or else a stack slot. 10248 Register Reg; 10249 unsigned StoreSizeBytes = XLen / 8; 10250 Align StackAlign = Align(XLen / 8); 10251 10252 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10253 Reg = State.AllocateReg(ArgFPR16s); 10254 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10255 Reg = State.AllocateReg(ArgFPR32s); 10256 else if (ValVT == MVT::f64 && !UseGPRForF64) 10257 Reg = State.AllocateReg(ArgFPR64s); 10258 else if (ValVT.isVector()) { 10259 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10260 if (!Reg) { 10261 // For return values, the vector must be passed fully via registers or 10262 // via the stack. 10263 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10264 // but we're using all of them. 10265 if (IsRet) 10266 return true; 10267 // Try using a GPR to pass the address 10268 if ((Reg = State.AllocateReg(ArgGPRs))) { 10269 LocVT = XLenVT; 10270 LocInfo = CCValAssign::Indirect; 10271 } else if (ValVT.isScalableVector()) { 10272 LocVT = XLenVT; 10273 LocInfo = CCValAssign::Indirect; 10274 } else { 10275 // Pass fixed-length vectors on the stack. 10276 LocVT = ValVT; 10277 StoreSizeBytes = ValVT.getStoreSize(); 10278 // Align vectors to their element sizes, being careful for vXi1 10279 // vectors. 10280 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10281 } 10282 } 10283 } else { 10284 Reg = State.AllocateReg(ArgGPRs); 10285 } 10286 10287 unsigned StackOffset = 10288 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10289 10290 // If we reach this point and PendingLocs is non-empty, we must be at the 10291 // end of a split argument that must be passed indirectly. 10292 if (!PendingLocs.empty()) { 10293 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10294 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10295 10296 for (auto &It : PendingLocs) { 10297 if (Reg) 10298 It.convertToReg(Reg); 10299 else 10300 It.convertToMem(StackOffset); 10301 State.addLoc(It); 10302 } 10303 PendingLocs.clear(); 10304 PendingArgFlags.clear(); 10305 return false; 10306 } 10307 10308 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10309 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10310 "Expected an XLenVT or vector types at this stage"); 10311 10312 if (Reg) { 10313 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10314 return false; 10315 } 10316 10317 // When a floating-point value is passed on the stack, no bit-conversion is 10318 // needed. 10319 if (ValVT.isFloatingPoint()) { 10320 LocVT = ValVT; 10321 LocInfo = CCValAssign::Full; 10322 } 10323 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10324 return false; 10325 } 10326 10327 template <typename ArgTy> 10328 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10329 for (const auto &ArgIdx : enumerate(Args)) { 10330 MVT ArgVT = ArgIdx.value().VT; 10331 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10332 return ArgIdx.index(); 10333 } 10334 return None; 10335 } 10336 10337 void RISCVTargetLowering::analyzeInputArgs( 10338 MachineFunction &MF, CCState &CCInfo, 10339 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10340 RISCVCCAssignFn Fn) const { 10341 unsigned NumArgs = Ins.size(); 10342 FunctionType *FType = MF.getFunction().getFunctionType(); 10343 10344 Optional<unsigned> FirstMaskArgument; 10345 if (Subtarget.hasVInstructions()) 10346 FirstMaskArgument = preAssignMask(Ins); 10347 10348 for (unsigned i = 0; i != NumArgs; ++i) { 10349 MVT ArgVT = Ins[i].VT; 10350 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10351 10352 Type *ArgTy = nullptr; 10353 if (IsRet) 10354 ArgTy = FType->getReturnType(); 10355 else if (Ins[i].isOrigArg()) 10356 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10357 10358 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10359 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10360 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10361 FirstMaskArgument)) { 10362 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10363 << EVT(ArgVT).getEVTString() << '\n'); 10364 llvm_unreachable(nullptr); 10365 } 10366 } 10367 } 10368 10369 void RISCVTargetLowering::analyzeOutputArgs( 10370 MachineFunction &MF, CCState &CCInfo, 10371 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10372 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10373 unsigned NumArgs = Outs.size(); 10374 10375 Optional<unsigned> FirstMaskArgument; 10376 if (Subtarget.hasVInstructions()) 10377 FirstMaskArgument = preAssignMask(Outs); 10378 10379 for (unsigned i = 0; i != NumArgs; i++) { 10380 MVT ArgVT = Outs[i].VT; 10381 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10382 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10383 10384 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10385 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10386 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10387 FirstMaskArgument)) { 10388 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10389 << EVT(ArgVT).getEVTString() << "\n"); 10390 llvm_unreachable(nullptr); 10391 } 10392 } 10393 } 10394 10395 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10396 // values. 10397 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10398 const CCValAssign &VA, const SDLoc &DL, 10399 const RISCVSubtarget &Subtarget) { 10400 switch (VA.getLocInfo()) { 10401 default: 10402 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10403 case CCValAssign::Full: 10404 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10405 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10406 break; 10407 case CCValAssign::BCvt: 10408 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10409 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10410 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10411 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10412 else 10413 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10414 break; 10415 } 10416 return Val; 10417 } 10418 10419 // The caller is responsible for loading the full value if the argument is 10420 // passed with CCValAssign::Indirect. 10421 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10422 const CCValAssign &VA, const SDLoc &DL, 10423 const RISCVTargetLowering &TLI) { 10424 MachineFunction &MF = DAG.getMachineFunction(); 10425 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10426 EVT LocVT = VA.getLocVT(); 10427 SDValue Val; 10428 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10429 Register VReg = RegInfo.createVirtualRegister(RC); 10430 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10431 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10432 10433 if (VA.getLocInfo() == CCValAssign::Indirect) 10434 return Val; 10435 10436 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10437 } 10438 10439 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10440 const CCValAssign &VA, const SDLoc &DL, 10441 const RISCVSubtarget &Subtarget) { 10442 EVT LocVT = VA.getLocVT(); 10443 10444 switch (VA.getLocInfo()) { 10445 default: 10446 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10447 case CCValAssign::Full: 10448 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10449 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10450 break; 10451 case CCValAssign::BCvt: 10452 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10453 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10454 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10455 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10456 else 10457 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10458 break; 10459 } 10460 return Val; 10461 } 10462 10463 // The caller is responsible for loading the full value if the argument is 10464 // passed with CCValAssign::Indirect. 10465 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10466 const CCValAssign &VA, const SDLoc &DL) { 10467 MachineFunction &MF = DAG.getMachineFunction(); 10468 MachineFrameInfo &MFI = MF.getFrameInfo(); 10469 EVT LocVT = VA.getLocVT(); 10470 EVT ValVT = VA.getValVT(); 10471 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10472 if (ValVT.isScalableVector()) { 10473 // When the value is a scalable vector, we save the pointer which points to 10474 // the scalable vector value in the stack. The ValVT will be the pointer 10475 // type, instead of the scalable vector type. 10476 ValVT = LocVT; 10477 } 10478 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10479 /*IsImmutable=*/true); 10480 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10481 SDValue Val; 10482 10483 ISD::LoadExtType ExtType; 10484 switch (VA.getLocInfo()) { 10485 default: 10486 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10487 case CCValAssign::Full: 10488 case CCValAssign::Indirect: 10489 case CCValAssign::BCvt: 10490 ExtType = ISD::NON_EXTLOAD; 10491 break; 10492 } 10493 Val = DAG.getExtLoad( 10494 ExtType, DL, LocVT, Chain, FIN, 10495 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10496 return Val; 10497 } 10498 10499 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10500 const CCValAssign &VA, const SDLoc &DL) { 10501 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10502 "Unexpected VA"); 10503 MachineFunction &MF = DAG.getMachineFunction(); 10504 MachineFrameInfo &MFI = MF.getFrameInfo(); 10505 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10506 10507 if (VA.isMemLoc()) { 10508 // f64 is passed on the stack. 10509 int FI = 10510 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10511 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10512 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10513 MachinePointerInfo::getFixedStack(MF, FI)); 10514 } 10515 10516 assert(VA.isRegLoc() && "Expected register VA assignment"); 10517 10518 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10519 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10520 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10521 SDValue Hi; 10522 if (VA.getLocReg() == RISCV::X17) { 10523 // Second half of f64 is passed on the stack. 10524 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10525 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10526 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10527 MachinePointerInfo::getFixedStack(MF, FI)); 10528 } else { 10529 // Second half of f64 is passed in another GPR. 10530 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10531 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10532 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10533 } 10534 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10535 } 10536 10537 // FastCC has less than 1% performance improvement for some particular 10538 // benchmark. But theoretically, it may has benenfit for some cases. 10539 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10540 unsigned ValNo, MVT ValVT, MVT LocVT, 10541 CCValAssign::LocInfo LocInfo, 10542 ISD::ArgFlagsTy ArgFlags, CCState &State, 10543 bool IsFixed, bool IsRet, Type *OrigTy, 10544 const RISCVTargetLowering &TLI, 10545 Optional<unsigned> FirstMaskArgument) { 10546 10547 // X5 and X6 might be used for save-restore libcall. 10548 static const MCPhysReg GPRList[] = { 10549 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10550 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10551 RISCV::X29, RISCV::X30, RISCV::X31}; 10552 10553 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10554 if (unsigned Reg = State.AllocateReg(GPRList)) { 10555 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10556 return false; 10557 } 10558 } 10559 10560 if (LocVT == MVT::f16) { 10561 static const MCPhysReg FPR16List[] = { 10562 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10563 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10564 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10565 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10566 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10567 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10568 return false; 10569 } 10570 } 10571 10572 if (LocVT == MVT::f32) { 10573 static const MCPhysReg FPR32List[] = { 10574 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10575 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10576 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10577 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10578 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10579 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10580 return false; 10581 } 10582 } 10583 10584 if (LocVT == MVT::f64) { 10585 static const MCPhysReg FPR64List[] = { 10586 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10587 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10588 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10589 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10590 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10591 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10592 return false; 10593 } 10594 } 10595 10596 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10597 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10598 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10599 return false; 10600 } 10601 10602 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10603 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10604 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10605 return false; 10606 } 10607 10608 if (LocVT.isVector()) { 10609 if (unsigned Reg = 10610 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10611 // Fixed-length vectors are located in the corresponding scalable-vector 10612 // container types. 10613 if (ValVT.isFixedLengthVector()) 10614 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10615 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10616 } else { 10617 // Try and pass the address via a "fast" GPR. 10618 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10619 LocInfo = CCValAssign::Indirect; 10620 LocVT = TLI.getSubtarget().getXLenVT(); 10621 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10622 } else if (ValVT.isFixedLengthVector()) { 10623 auto StackAlign = 10624 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10625 unsigned StackOffset = 10626 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10627 State.addLoc( 10628 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10629 } else { 10630 // Can't pass scalable vectors on the stack. 10631 return true; 10632 } 10633 } 10634 10635 return false; 10636 } 10637 10638 return true; // CC didn't match. 10639 } 10640 10641 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10642 CCValAssign::LocInfo LocInfo, 10643 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10644 10645 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10646 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10647 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10648 static const MCPhysReg GPRList[] = { 10649 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10650 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10651 if (unsigned Reg = State.AllocateReg(GPRList)) { 10652 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10653 return false; 10654 } 10655 } 10656 10657 if (LocVT == MVT::f32) { 10658 // Pass in STG registers: F1, ..., F6 10659 // fs0 ... fs5 10660 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10661 RISCV::F18_F, RISCV::F19_F, 10662 RISCV::F20_F, RISCV::F21_F}; 10663 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10664 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10665 return false; 10666 } 10667 } 10668 10669 if (LocVT == MVT::f64) { 10670 // Pass in STG registers: D1, ..., D6 10671 // fs6 ... fs11 10672 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10673 RISCV::F24_D, RISCV::F25_D, 10674 RISCV::F26_D, RISCV::F27_D}; 10675 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10676 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10677 return false; 10678 } 10679 } 10680 10681 report_fatal_error("No registers left in GHC calling convention"); 10682 return true; 10683 } 10684 10685 // Transform physical registers into virtual registers. 10686 SDValue RISCVTargetLowering::LowerFormalArguments( 10687 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10688 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10689 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10690 10691 MachineFunction &MF = DAG.getMachineFunction(); 10692 10693 switch (CallConv) { 10694 default: 10695 report_fatal_error("Unsupported calling convention"); 10696 case CallingConv::C: 10697 case CallingConv::Fast: 10698 break; 10699 case CallingConv::GHC: 10700 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10701 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10702 report_fatal_error( 10703 "GHC calling convention requires the F and D instruction set extensions"); 10704 } 10705 10706 const Function &Func = MF.getFunction(); 10707 if (Func.hasFnAttribute("interrupt")) { 10708 if (!Func.arg_empty()) 10709 report_fatal_error( 10710 "Functions with the interrupt attribute cannot have arguments!"); 10711 10712 StringRef Kind = 10713 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10714 10715 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10716 report_fatal_error( 10717 "Function interrupt attribute argument not supported!"); 10718 } 10719 10720 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10721 MVT XLenVT = Subtarget.getXLenVT(); 10722 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10723 // Used with vargs to acumulate store chains. 10724 std::vector<SDValue> OutChains; 10725 10726 // Assign locations to all of the incoming arguments. 10727 SmallVector<CCValAssign, 16> ArgLocs; 10728 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10729 10730 if (CallConv == CallingConv::GHC) 10731 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10732 else 10733 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10734 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10735 : CC_RISCV); 10736 10737 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10738 CCValAssign &VA = ArgLocs[i]; 10739 SDValue ArgValue; 10740 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10741 // case. 10742 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10743 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10744 else if (VA.isRegLoc()) 10745 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10746 else 10747 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10748 10749 if (VA.getLocInfo() == CCValAssign::Indirect) { 10750 // If the original argument was split and passed by reference (e.g. i128 10751 // on RV32), we need to load all parts of it here (using the same 10752 // address). Vectors may be partly split to registers and partly to the 10753 // stack, in which case the base address is partly offset and subsequent 10754 // stores are relative to that. 10755 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10756 MachinePointerInfo())); 10757 unsigned ArgIndex = Ins[i].OrigArgIndex; 10758 unsigned ArgPartOffset = Ins[i].PartOffset; 10759 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10760 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10761 CCValAssign &PartVA = ArgLocs[i + 1]; 10762 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10763 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10764 if (PartVA.getValVT().isScalableVector()) 10765 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10766 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10767 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10768 MachinePointerInfo())); 10769 ++i; 10770 } 10771 continue; 10772 } 10773 InVals.push_back(ArgValue); 10774 } 10775 10776 if (IsVarArg) { 10777 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10778 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10779 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10780 MachineFrameInfo &MFI = MF.getFrameInfo(); 10781 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10782 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10783 10784 // Offset of the first variable argument from stack pointer, and size of 10785 // the vararg save area. For now, the varargs save area is either zero or 10786 // large enough to hold a0-a7. 10787 int VaArgOffset, VarArgsSaveSize; 10788 10789 // If all registers are allocated, then all varargs must be passed on the 10790 // stack and we don't need to save any argregs. 10791 if (ArgRegs.size() == Idx) { 10792 VaArgOffset = CCInfo.getNextStackOffset(); 10793 VarArgsSaveSize = 0; 10794 } else { 10795 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10796 VaArgOffset = -VarArgsSaveSize; 10797 } 10798 10799 // Record the frame index of the first variable argument 10800 // which is a value necessary to VASTART. 10801 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10802 RVFI->setVarArgsFrameIndex(FI); 10803 10804 // If saving an odd number of registers then create an extra stack slot to 10805 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10806 // offsets to even-numbered registered remain 2*XLEN-aligned. 10807 if (Idx % 2) { 10808 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10809 VarArgsSaveSize += XLenInBytes; 10810 } 10811 10812 // Copy the integer registers that may have been used for passing varargs 10813 // to the vararg save area. 10814 for (unsigned I = Idx; I < ArgRegs.size(); 10815 ++I, VaArgOffset += XLenInBytes) { 10816 const Register Reg = RegInfo.createVirtualRegister(RC); 10817 RegInfo.addLiveIn(ArgRegs[I], Reg); 10818 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10819 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10820 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10821 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10822 MachinePointerInfo::getFixedStack(MF, FI)); 10823 cast<StoreSDNode>(Store.getNode()) 10824 ->getMemOperand() 10825 ->setValue((Value *)nullptr); 10826 OutChains.push_back(Store); 10827 } 10828 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10829 } 10830 10831 // All stores are grouped in one node to allow the matching between 10832 // the size of Ins and InVals. This only happens for vararg functions. 10833 if (!OutChains.empty()) { 10834 OutChains.push_back(Chain); 10835 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10836 } 10837 10838 return Chain; 10839 } 10840 10841 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10842 /// for tail call optimization. 10843 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10844 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10845 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10846 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10847 10848 auto &Callee = CLI.Callee; 10849 auto CalleeCC = CLI.CallConv; 10850 auto &Outs = CLI.Outs; 10851 auto &Caller = MF.getFunction(); 10852 auto CallerCC = Caller.getCallingConv(); 10853 10854 // Exception-handling functions need a special set of instructions to 10855 // indicate a return to the hardware. Tail-calling another function would 10856 // probably break this. 10857 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10858 // should be expanded as new function attributes are introduced. 10859 if (Caller.hasFnAttribute("interrupt")) 10860 return false; 10861 10862 // Do not tail call opt if the stack is used to pass parameters. 10863 if (CCInfo.getNextStackOffset() != 0) 10864 return false; 10865 10866 // Do not tail call opt if any parameters need to be passed indirectly. 10867 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10868 // passed indirectly. So the address of the value will be passed in a 10869 // register, or if not available, then the address is put on the stack. In 10870 // order to pass indirectly, space on the stack often needs to be allocated 10871 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10872 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10873 // are passed CCValAssign::Indirect. 10874 for (auto &VA : ArgLocs) 10875 if (VA.getLocInfo() == CCValAssign::Indirect) 10876 return false; 10877 10878 // Do not tail call opt if either caller or callee uses struct return 10879 // semantics. 10880 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10881 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10882 if (IsCallerStructRet || IsCalleeStructRet) 10883 return false; 10884 10885 // Externally-defined functions with weak linkage should not be 10886 // tail-called. The behaviour of branch instructions in this situation (as 10887 // used for tail calls) is implementation-defined, so we cannot rely on the 10888 // linker replacing the tail call with a return. 10889 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10890 const GlobalValue *GV = G->getGlobal(); 10891 if (GV->hasExternalWeakLinkage()) 10892 return false; 10893 } 10894 10895 // The callee has to preserve all registers the caller needs to preserve. 10896 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10897 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10898 if (CalleeCC != CallerCC) { 10899 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10900 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10901 return false; 10902 } 10903 10904 // Byval parameters hand the function a pointer directly into the stack area 10905 // we want to reuse during a tail call. Working around this *is* possible 10906 // but less efficient and uglier in LowerCall. 10907 for (auto &Arg : Outs) 10908 if (Arg.Flags.isByVal()) 10909 return false; 10910 10911 return true; 10912 } 10913 10914 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10915 return DAG.getDataLayout().getPrefTypeAlign( 10916 VT.getTypeForEVT(*DAG.getContext())); 10917 } 10918 10919 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10920 // and output parameter nodes. 10921 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10922 SmallVectorImpl<SDValue> &InVals) const { 10923 SelectionDAG &DAG = CLI.DAG; 10924 SDLoc &DL = CLI.DL; 10925 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10926 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10927 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10928 SDValue Chain = CLI.Chain; 10929 SDValue Callee = CLI.Callee; 10930 bool &IsTailCall = CLI.IsTailCall; 10931 CallingConv::ID CallConv = CLI.CallConv; 10932 bool IsVarArg = CLI.IsVarArg; 10933 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10934 MVT XLenVT = Subtarget.getXLenVT(); 10935 10936 MachineFunction &MF = DAG.getMachineFunction(); 10937 10938 // Analyze the operands of the call, assigning locations to each operand. 10939 SmallVector<CCValAssign, 16> ArgLocs; 10940 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10941 10942 if (CallConv == CallingConv::GHC) 10943 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10944 else 10945 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10946 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10947 : CC_RISCV); 10948 10949 // Check if it's really possible to do a tail call. 10950 if (IsTailCall) 10951 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10952 10953 if (IsTailCall) 10954 ++NumTailCalls; 10955 else if (CLI.CB && CLI.CB->isMustTailCall()) 10956 report_fatal_error("failed to perform tail call elimination on a call " 10957 "site marked musttail"); 10958 10959 // Get a count of how many bytes are to be pushed on the stack. 10960 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10961 10962 // Create local copies for byval args 10963 SmallVector<SDValue, 8> ByValArgs; 10964 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10965 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10966 if (!Flags.isByVal()) 10967 continue; 10968 10969 SDValue Arg = OutVals[i]; 10970 unsigned Size = Flags.getByValSize(); 10971 Align Alignment = Flags.getNonZeroByValAlign(); 10972 10973 int FI = 10974 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10975 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10976 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10977 10978 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10979 /*IsVolatile=*/false, 10980 /*AlwaysInline=*/false, IsTailCall, 10981 MachinePointerInfo(), MachinePointerInfo()); 10982 ByValArgs.push_back(FIPtr); 10983 } 10984 10985 if (!IsTailCall) 10986 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10987 10988 // Copy argument values to their designated locations. 10989 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10990 SmallVector<SDValue, 8> MemOpChains; 10991 SDValue StackPtr; 10992 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10993 CCValAssign &VA = ArgLocs[i]; 10994 SDValue ArgValue = OutVals[i]; 10995 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10996 10997 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10998 bool IsF64OnRV32DSoftABI = 10999 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 11000 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 11001 SDValue SplitF64 = DAG.getNode( 11002 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 11003 SDValue Lo = SplitF64.getValue(0); 11004 SDValue Hi = SplitF64.getValue(1); 11005 11006 Register RegLo = VA.getLocReg(); 11007 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 11008 11009 if (RegLo == RISCV::X17) { 11010 // Second half of f64 is passed on the stack. 11011 // Work out the address of the stack slot. 11012 if (!StackPtr.getNode()) 11013 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11014 // Emit the store. 11015 MemOpChains.push_back( 11016 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 11017 } else { 11018 // Second half of f64 is passed in another GPR. 11019 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11020 Register RegHigh = RegLo + 1; 11021 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 11022 } 11023 continue; 11024 } 11025 11026 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 11027 // as any other MemLoc. 11028 11029 // Promote the value if needed. 11030 // For now, only handle fully promoted and indirect arguments. 11031 if (VA.getLocInfo() == CCValAssign::Indirect) { 11032 // Store the argument in a stack slot and pass its address. 11033 Align StackAlign = 11034 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11035 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11036 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11037 // If the original argument was split (e.g. i128), we need 11038 // to store the required parts of it here (and pass just one address). 11039 // Vectors may be partly split to registers and partly to the stack, in 11040 // which case the base address is partly offset and subsequent stores are 11041 // relative to that. 11042 unsigned ArgIndex = Outs[i].OrigArgIndex; 11043 unsigned ArgPartOffset = Outs[i].PartOffset; 11044 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11045 // Calculate the total size to store. We don't have access to what we're 11046 // actually storing other than performing the loop and collecting the 11047 // info. 11048 SmallVector<std::pair<SDValue, SDValue>> Parts; 11049 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11050 SDValue PartValue = OutVals[i + 1]; 11051 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11052 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11053 EVT PartVT = PartValue.getValueType(); 11054 if (PartVT.isScalableVector()) 11055 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11056 StoredSize += PartVT.getStoreSize(); 11057 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11058 Parts.push_back(std::make_pair(PartValue, Offset)); 11059 ++i; 11060 } 11061 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11062 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11063 MemOpChains.push_back( 11064 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11065 MachinePointerInfo::getFixedStack(MF, FI))); 11066 for (const auto &Part : Parts) { 11067 SDValue PartValue = Part.first; 11068 SDValue PartOffset = Part.second; 11069 SDValue Address = 11070 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11071 MemOpChains.push_back( 11072 DAG.getStore(Chain, DL, PartValue, Address, 11073 MachinePointerInfo::getFixedStack(MF, FI))); 11074 } 11075 ArgValue = SpillSlot; 11076 } else { 11077 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11078 } 11079 11080 // Use local copy if it is a byval arg. 11081 if (Flags.isByVal()) 11082 ArgValue = ByValArgs[j++]; 11083 11084 if (VA.isRegLoc()) { 11085 // Queue up the argument copies and emit them at the end. 11086 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11087 } else { 11088 assert(VA.isMemLoc() && "Argument not register or memory"); 11089 assert(!IsTailCall && "Tail call not allowed if stack is used " 11090 "for passing parameters"); 11091 11092 // Work out the address of the stack slot. 11093 if (!StackPtr.getNode()) 11094 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11095 SDValue Address = 11096 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11097 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11098 11099 // Emit the store. 11100 MemOpChains.push_back( 11101 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11102 } 11103 } 11104 11105 // Join the stores, which are independent of one another. 11106 if (!MemOpChains.empty()) 11107 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11108 11109 SDValue Glue; 11110 11111 // Build a sequence of copy-to-reg nodes, chained and glued together. 11112 for (auto &Reg : RegsToPass) { 11113 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11114 Glue = Chain.getValue(1); 11115 } 11116 11117 // Validate that none of the argument registers have been marked as 11118 // reserved, if so report an error. Do the same for the return address if this 11119 // is not a tailcall. 11120 validateCCReservedRegs(RegsToPass, MF); 11121 if (!IsTailCall && 11122 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11123 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11124 MF.getFunction(), 11125 "Return address register required, but has been reserved."}); 11126 11127 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11128 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11129 // split it and then direct call can be matched by PseudoCALL. 11130 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11131 const GlobalValue *GV = S->getGlobal(); 11132 11133 unsigned OpFlags = RISCVII::MO_CALL; 11134 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11135 OpFlags = RISCVII::MO_PLT; 11136 11137 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11138 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11139 unsigned OpFlags = RISCVII::MO_CALL; 11140 11141 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11142 nullptr)) 11143 OpFlags = RISCVII::MO_PLT; 11144 11145 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11146 } 11147 11148 // The first call operand is the chain and the second is the target address. 11149 SmallVector<SDValue, 8> Ops; 11150 Ops.push_back(Chain); 11151 Ops.push_back(Callee); 11152 11153 // Add argument registers to the end of the list so that they are 11154 // known live into the call. 11155 for (auto &Reg : RegsToPass) 11156 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11157 11158 if (!IsTailCall) { 11159 // Add a register mask operand representing the call-preserved registers. 11160 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11161 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11162 assert(Mask && "Missing call preserved mask for calling convention"); 11163 Ops.push_back(DAG.getRegisterMask(Mask)); 11164 } 11165 11166 // Glue the call to the argument copies, if any. 11167 if (Glue.getNode()) 11168 Ops.push_back(Glue); 11169 11170 // Emit the call. 11171 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11172 11173 if (IsTailCall) { 11174 MF.getFrameInfo().setHasTailCall(); 11175 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11176 } 11177 11178 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11179 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11180 Glue = Chain.getValue(1); 11181 11182 // Mark the end of the call, which is glued to the call itself. 11183 Chain = DAG.getCALLSEQ_END(Chain, 11184 DAG.getConstant(NumBytes, DL, PtrVT, true), 11185 DAG.getConstant(0, DL, PtrVT, true), 11186 Glue, DL); 11187 Glue = Chain.getValue(1); 11188 11189 // Assign locations to each value returned by this call. 11190 SmallVector<CCValAssign, 16> RVLocs; 11191 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11192 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11193 11194 // Copy all of the result registers out of their specified physreg. 11195 for (auto &VA : RVLocs) { 11196 // Copy the value out 11197 SDValue RetValue = 11198 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11199 // Glue the RetValue to the end of the call sequence 11200 Chain = RetValue.getValue(1); 11201 Glue = RetValue.getValue(2); 11202 11203 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11204 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11205 SDValue RetValue2 = 11206 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11207 Chain = RetValue2.getValue(1); 11208 Glue = RetValue2.getValue(2); 11209 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11210 RetValue2); 11211 } 11212 11213 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11214 11215 InVals.push_back(RetValue); 11216 } 11217 11218 return Chain; 11219 } 11220 11221 bool RISCVTargetLowering::CanLowerReturn( 11222 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11223 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11224 SmallVector<CCValAssign, 16> RVLocs; 11225 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11226 11227 Optional<unsigned> FirstMaskArgument; 11228 if (Subtarget.hasVInstructions()) 11229 FirstMaskArgument = preAssignMask(Outs); 11230 11231 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11232 MVT VT = Outs[i].VT; 11233 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11234 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11235 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11236 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11237 *this, FirstMaskArgument)) 11238 return false; 11239 } 11240 return true; 11241 } 11242 11243 SDValue 11244 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11245 bool IsVarArg, 11246 const SmallVectorImpl<ISD::OutputArg> &Outs, 11247 const SmallVectorImpl<SDValue> &OutVals, 11248 const SDLoc &DL, SelectionDAG &DAG) const { 11249 const MachineFunction &MF = DAG.getMachineFunction(); 11250 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11251 11252 // Stores the assignment of the return value to a location. 11253 SmallVector<CCValAssign, 16> RVLocs; 11254 11255 // Info about the registers and stack slot. 11256 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11257 *DAG.getContext()); 11258 11259 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11260 nullptr, CC_RISCV); 11261 11262 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11263 report_fatal_error("GHC functions return void only"); 11264 11265 SDValue Glue; 11266 SmallVector<SDValue, 4> RetOps(1, Chain); 11267 11268 // Copy the result values into the output registers. 11269 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11270 SDValue Val = OutVals[i]; 11271 CCValAssign &VA = RVLocs[i]; 11272 assert(VA.isRegLoc() && "Can only return in registers!"); 11273 11274 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11275 // Handle returning f64 on RV32D with a soft float ABI. 11276 assert(VA.isRegLoc() && "Expected return via registers"); 11277 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11278 DAG.getVTList(MVT::i32, MVT::i32), Val); 11279 SDValue Lo = SplitF64.getValue(0); 11280 SDValue Hi = SplitF64.getValue(1); 11281 Register RegLo = VA.getLocReg(); 11282 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11283 Register RegHi = RegLo + 1; 11284 11285 if (STI.isRegisterReservedByUser(RegLo) || 11286 STI.isRegisterReservedByUser(RegHi)) 11287 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11288 MF.getFunction(), 11289 "Return value register required, but has been reserved."}); 11290 11291 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11292 Glue = Chain.getValue(1); 11293 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11294 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11295 Glue = Chain.getValue(1); 11296 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11297 } else { 11298 // Handle a 'normal' return. 11299 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11300 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11301 11302 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11303 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11304 MF.getFunction(), 11305 "Return value register required, but has been reserved."}); 11306 11307 // Guarantee that all emitted copies are stuck together. 11308 Glue = Chain.getValue(1); 11309 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11310 } 11311 } 11312 11313 RetOps[0] = Chain; // Update chain. 11314 11315 // Add the glue node if we have it. 11316 if (Glue.getNode()) { 11317 RetOps.push_back(Glue); 11318 } 11319 11320 unsigned RetOpc = RISCVISD::RET_FLAG; 11321 // Interrupt service routines use different return instructions. 11322 const Function &Func = DAG.getMachineFunction().getFunction(); 11323 if (Func.hasFnAttribute("interrupt")) { 11324 if (!Func.getReturnType()->isVoidTy()) 11325 report_fatal_error( 11326 "Functions with the interrupt attribute must have void return type!"); 11327 11328 MachineFunction &MF = DAG.getMachineFunction(); 11329 StringRef Kind = 11330 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11331 11332 if (Kind == "user") 11333 RetOpc = RISCVISD::URET_FLAG; 11334 else if (Kind == "supervisor") 11335 RetOpc = RISCVISD::SRET_FLAG; 11336 else 11337 RetOpc = RISCVISD::MRET_FLAG; 11338 } 11339 11340 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11341 } 11342 11343 void RISCVTargetLowering::validateCCReservedRegs( 11344 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11345 MachineFunction &MF) const { 11346 const Function &F = MF.getFunction(); 11347 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11348 11349 if (llvm::any_of(Regs, [&STI](auto Reg) { 11350 return STI.isRegisterReservedByUser(Reg.first); 11351 })) 11352 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11353 F, "Argument register required, but has been reserved."}); 11354 } 11355 11356 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11357 return CI->isTailCall(); 11358 } 11359 11360 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11361 #define NODE_NAME_CASE(NODE) \ 11362 case RISCVISD::NODE: \ 11363 return "RISCVISD::" #NODE; 11364 // clang-format off 11365 switch ((RISCVISD::NodeType)Opcode) { 11366 case RISCVISD::FIRST_NUMBER: 11367 break; 11368 NODE_NAME_CASE(RET_FLAG) 11369 NODE_NAME_CASE(URET_FLAG) 11370 NODE_NAME_CASE(SRET_FLAG) 11371 NODE_NAME_CASE(MRET_FLAG) 11372 NODE_NAME_CASE(CALL) 11373 NODE_NAME_CASE(SELECT_CC) 11374 NODE_NAME_CASE(BR_CC) 11375 NODE_NAME_CASE(BuildPairF64) 11376 NODE_NAME_CASE(SplitF64) 11377 NODE_NAME_CASE(TAIL) 11378 NODE_NAME_CASE(ADD_LO) 11379 NODE_NAME_CASE(HI) 11380 NODE_NAME_CASE(LLA) 11381 NODE_NAME_CASE(ADD_TPREL) 11382 NODE_NAME_CASE(LA) 11383 NODE_NAME_CASE(LA_TLS_IE) 11384 NODE_NAME_CASE(LA_TLS_GD) 11385 NODE_NAME_CASE(MULHSU) 11386 NODE_NAME_CASE(SLLW) 11387 NODE_NAME_CASE(SRAW) 11388 NODE_NAME_CASE(SRLW) 11389 NODE_NAME_CASE(DIVW) 11390 NODE_NAME_CASE(DIVUW) 11391 NODE_NAME_CASE(REMUW) 11392 NODE_NAME_CASE(ROLW) 11393 NODE_NAME_CASE(RORW) 11394 NODE_NAME_CASE(CLZW) 11395 NODE_NAME_CASE(CTZW) 11396 NODE_NAME_CASE(FSLW) 11397 NODE_NAME_CASE(FSRW) 11398 NODE_NAME_CASE(FSL) 11399 NODE_NAME_CASE(FSR) 11400 NODE_NAME_CASE(FMV_H_X) 11401 NODE_NAME_CASE(FMV_X_ANYEXTH) 11402 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11403 NODE_NAME_CASE(FMV_W_X_RV64) 11404 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11405 NODE_NAME_CASE(FCVT_X) 11406 NODE_NAME_CASE(FCVT_XU) 11407 NODE_NAME_CASE(FCVT_W_RV64) 11408 NODE_NAME_CASE(FCVT_WU_RV64) 11409 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11410 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11411 NODE_NAME_CASE(READ_CYCLE_WIDE) 11412 NODE_NAME_CASE(GREV) 11413 NODE_NAME_CASE(GREVW) 11414 NODE_NAME_CASE(GORC) 11415 NODE_NAME_CASE(GORCW) 11416 NODE_NAME_CASE(SHFL) 11417 NODE_NAME_CASE(SHFLW) 11418 NODE_NAME_CASE(UNSHFL) 11419 NODE_NAME_CASE(UNSHFLW) 11420 NODE_NAME_CASE(BFP) 11421 NODE_NAME_CASE(BFPW) 11422 NODE_NAME_CASE(BCOMPRESS) 11423 NODE_NAME_CASE(BCOMPRESSW) 11424 NODE_NAME_CASE(BDECOMPRESS) 11425 NODE_NAME_CASE(BDECOMPRESSW) 11426 NODE_NAME_CASE(VMV_V_X_VL) 11427 NODE_NAME_CASE(VFMV_V_F_VL) 11428 NODE_NAME_CASE(VMV_X_S) 11429 NODE_NAME_CASE(VMV_S_X_VL) 11430 NODE_NAME_CASE(VFMV_S_F_VL) 11431 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11432 NODE_NAME_CASE(READ_VLENB) 11433 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11434 NODE_NAME_CASE(VSLIDEUP_VL) 11435 NODE_NAME_CASE(VSLIDE1UP_VL) 11436 NODE_NAME_CASE(VSLIDEDOWN_VL) 11437 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11438 NODE_NAME_CASE(VID_VL) 11439 NODE_NAME_CASE(VFNCVT_ROD_VL) 11440 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11441 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11442 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11443 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11444 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11445 NODE_NAME_CASE(VECREDUCE_AND_VL) 11446 NODE_NAME_CASE(VECREDUCE_OR_VL) 11447 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11448 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11449 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11450 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11451 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11452 NODE_NAME_CASE(ADD_VL) 11453 NODE_NAME_CASE(AND_VL) 11454 NODE_NAME_CASE(MUL_VL) 11455 NODE_NAME_CASE(OR_VL) 11456 NODE_NAME_CASE(SDIV_VL) 11457 NODE_NAME_CASE(SHL_VL) 11458 NODE_NAME_CASE(SREM_VL) 11459 NODE_NAME_CASE(SRA_VL) 11460 NODE_NAME_CASE(SRL_VL) 11461 NODE_NAME_CASE(SUB_VL) 11462 NODE_NAME_CASE(UDIV_VL) 11463 NODE_NAME_CASE(UREM_VL) 11464 NODE_NAME_CASE(XOR_VL) 11465 NODE_NAME_CASE(SADDSAT_VL) 11466 NODE_NAME_CASE(UADDSAT_VL) 11467 NODE_NAME_CASE(SSUBSAT_VL) 11468 NODE_NAME_CASE(USUBSAT_VL) 11469 NODE_NAME_CASE(FADD_VL) 11470 NODE_NAME_CASE(FSUB_VL) 11471 NODE_NAME_CASE(FMUL_VL) 11472 NODE_NAME_CASE(FDIV_VL) 11473 NODE_NAME_CASE(FNEG_VL) 11474 NODE_NAME_CASE(FABS_VL) 11475 NODE_NAME_CASE(FSQRT_VL) 11476 NODE_NAME_CASE(VFMADD_VL) 11477 NODE_NAME_CASE(VFNMADD_VL) 11478 NODE_NAME_CASE(VFMSUB_VL) 11479 NODE_NAME_CASE(VFNMSUB_VL) 11480 NODE_NAME_CASE(FCOPYSIGN_VL) 11481 NODE_NAME_CASE(SMIN_VL) 11482 NODE_NAME_CASE(SMAX_VL) 11483 NODE_NAME_CASE(UMIN_VL) 11484 NODE_NAME_CASE(UMAX_VL) 11485 NODE_NAME_CASE(FMINNUM_VL) 11486 NODE_NAME_CASE(FMAXNUM_VL) 11487 NODE_NAME_CASE(MULHS_VL) 11488 NODE_NAME_CASE(MULHU_VL) 11489 NODE_NAME_CASE(FP_TO_SINT_VL) 11490 NODE_NAME_CASE(FP_TO_UINT_VL) 11491 NODE_NAME_CASE(SINT_TO_FP_VL) 11492 NODE_NAME_CASE(UINT_TO_FP_VL) 11493 NODE_NAME_CASE(FP_EXTEND_VL) 11494 NODE_NAME_CASE(FP_ROUND_VL) 11495 NODE_NAME_CASE(VWMUL_VL) 11496 NODE_NAME_CASE(VWMULU_VL) 11497 NODE_NAME_CASE(VWMULSU_VL) 11498 NODE_NAME_CASE(VWADD_VL) 11499 NODE_NAME_CASE(VWADDU_VL) 11500 NODE_NAME_CASE(VWSUB_VL) 11501 NODE_NAME_CASE(VWSUBU_VL) 11502 NODE_NAME_CASE(VWADD_W_VL) 11503 NODE_NAME_CASE(VWADDU_W_VL) 11504 NODE_NAME_CASE(VWSUB_W_VL) 11505 NODE_NAME_CASE(VWSUBU_W_VL) 11506 NODE_NAME_CASE(SETCC_VL) 11507 NODE_NAME_CASE(VSELECT_VL) 11508 NODE_NAME_CASE(VP_MERGE_VL) 11509 NODE_NAME_CASE(VMAND_VL) 11510 NODE_NAME_CASE(VMOR_VL) 11511 NODE_NAME_CASE(VMXOR_VL) 11512 NODE_NAME_CASE(VMCLR_VL) 11513 NODE_NAME_CASE(VMSET_VL) 11514 NODE_NAME_CASE(VRGATHER_VX_VL) 11515 NODE_NAME_CASE(VRGATHER_VV_VL) 11516 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11517 NODE_NAME_CASE(VSEXT_VL) 11518 NODE_NAME_CASE(VZEXT_VL) 11519 NODE_NAME_CASE(VCPOP_VL) 11520 NODE_NAME_CASE(READ_CSR) 11521 NODE_NAME_CASE(WRITE_CSR) 11522 NODE_NAME_CASE(SWAP_CSR) 11523 } 11524 // clang-format on 11525 return nullptr; 11526 #undef NODE_NAME_CASE 11527 } 11528 11529 /// getConstraintType - Given a constraint letter, return the type of 11530 /// constraint it is for this target. 11531 RISCVTargetLowering::ConstraintType 11532 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11533 if (Constraint.size() == 1) { 11534 switch (Constraint[0]) { 11535 default: 11536 break; 11537 case 'f': 11538 return C_RegisterClass; 11539 case 'I': 11540 case 'J': 11541 case 'K': 11542 return C_Immediate; 11543 case 'A': 11544 return C_Memory; 11545 case 'S': // A symbolic address 11546 return C_Other; 11547 } 11548 } else { 11549 if (Constraint == "vr" || Constraint == "vm") 11550 return C_RegisterClass; 11551 } 11552 return TargetLowering::getConstraintType(Constraint); 11553 } 11554 11555 std::pair<unsigned, const TargetRegisterClass *> 11556 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11557 StringRef Constraint, 11558 MVT VT) const { 11559 // First, see if this is a constraint that directly corresponds to a 11560 // RISCV register class. 11561 if (Constraint.size() == 1) { 11562 switch (Constraint[0]) { 11563 case 'r': 11564 // TODO: Support fixed vectors up to XLen for P extension? 11565 if (VT.isVector()) 11566 break; 11567 return std::make_pair(0U, &RISCV::GPRRegClass); 11568 case 'f': 11569 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11570 return std::make_pair(0U, &RISCV::FPR16RegClass); 11571 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11572 return std::make_pair(0U, &RISCV::FPR32RegClass); 11573 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11574 return std::make_pair(0U, &RISCV::FPR64RegClass); 11575 break; 11576 default: 11577 break; 11578 } 11579 } else if (Constraint == "vr") { 11580 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11581 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11582 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11583 return std::make_pair(0U, RC); 11584 } 11585 } else if (Constraint == "vm") { 11586 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11587 return std::make_pair(0U, &RISCV::VMV0RegClass); 11588 } 11589 11590 // Clang will correctly decode the usage of register name aliases into their 11591 // official names. However, other frontends like `rustc` do not. This allows 11592 // users of these frontends to use the ABI names for registers in LLVM-style 11593 // register constraints. 11594 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11595 .Case("{zero}", RISCV::X0) 11596 .Case("{ra}", RISCV::X1) 11597 .Case("{sp}", RISCV::X2) 11598 .Case("{gp}", RISCV::X3) 11599 .Case("{tp}", RISCV::X4) 11600 .Case("{t0}", RISCV::X5) 11601 .Case("{t1}", RISCV::X6) 11602 .Case("{t2}", RISCV::X7) 11603 .Cases("{s0}", "{fp}", RISCV::X8) 11604 .Case("{s1}", RISCV::X9) 11605 .Case("{a0}", RISCV::X10) 11606 .Case("{a1}", RISCV::X11) 11607 .Case("{a2}", RISCV::X12) 11608 .Case("{a3}", RISCV::X13) 11609 .Case("{a4}", RISCV::X14) 11610 .Case("{a5}", RISCV::X15) 11611 .Case("{a6}", RISCV::X16) 11612 .Case("{a7}", RISCV::X17) 11613 .Case("{s2}", RISCV::X18) 11614 .Case("{s3}", RISCV::X19) 11615 .Case("{s4}", RISCV::X20) 11616 .Case("{s5}", RISCV::X21) 11617 .Case("{s6}", RISCV::X22) 11618 .Case("{s7}", RISCV::X23) 11619 .Case("{s8}", RISCV::X24) 11620 .Case("{s9}", RISCV::X25) 11621 .Case("{s10}", RISCV::X26) 11622 .Case("{s11}", RISCV::X27) 11623 .Case("{t3}", RISCV::X28) 11624 .Case("{t4}", RISCV::X29) 11625 .Case("{t5}", RISCV::X30) 11626 .Case("{t6}", RISCV::X31) 11627 .Default(RISCV::NoRegister); 11628 if (XRegFromAlias != RISCV::NoRegister) 11629 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11630 11631 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11632 // TableGen record rather than the AsmName to choose registers for InlineAsm 11633 // constraints, plus we want to match those names to the widest floating point 11634 // register type available, manually select floating point registers here. 11635 // 11636 // The second case is the ABI name of the register, so that frontends can also 11637 // use the ABI names in register constraint lists. 11638 if (Subtarget.hasStdExtF()) { 11639 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11640 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11641 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11642 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11643 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11644 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11645 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11646 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11647 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11648 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11649 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11650 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11651 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11652 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11653 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11654 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11655 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11656 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11657 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11658 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11659 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11660 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11661 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11662 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11663 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11664 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11665 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11666 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11667 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11668 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11669 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11670 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11671 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11672 .Default(RISCV::NoRegister); 11673 if (FReg != RISCV::NoRegister) { 11674 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11675 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11676 unsigned RegNo = FReg - RISCV::F0_F; 11677 unsigned DReg = RISCV::F0_D + RegNo; 11678 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11679 } 11680 if (VT == MVT::f32 || VT == MVT::Other) 11681 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11682 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11683 unsigned RegNo = FReg - RISCV::F0_F; 11684 unsigned HReg = RISCV::F0_H + RegNo; 11685 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11686 } 11687 } 11688 } 11689 11690 if (Subtarget.hasVInstructions()) { 11691 Register VReg = StringSwitch<Register>(Constraint.lower()) 11692 .Case("{v0}", RISCV::V0) 11693 .Case("{v1}", RISCV::V1) 11694 .Case("{v2}", RISCV::V2) 11695 .Case("{v3}", RISCV::V3) 11696 .Case("{v4}", RISCV::V4) 11697 .Case("{v5}", RISCV::V5) 11698 .Case("{v6}", RISCV::V6) 11699 .Case("{v7}", RISCV::V7) 11700 .Case("{v8}", RISCV::V8) 11701 .Case("{v9}", RISCV::V9) 11702 .Case("{v10}", RISCV::V10) 11703 .Case("{v11}", RISCV::V11) 11704 .Case("{v12}", RISCV::V12) 11705 .Case("{v13}", RISCV::V13) 11706 .Case("{v14}", RISCV::V14) 11707 .Case("{v15}", RISCV::V15) 11708 .Case("{v16}", RISCV::V16) 11709 .Case("{v17}", RISCV::V17) 11710 .Case("{v18}", RISCV::V18) 11711 .Case("{v19}", RISCV::V19) 11712 .Case("{v20}", RISCV::V20) 11713 .Case("{v21}", RISCV::V21) 11714 .Case("{v22}", RISCV::V22) 11715 .Case("{v23}", RISCV::V23) 11716 .Case("{v24}", RISCV::V24) 11717 .Case("{v25}", RISCV::V25) 11718 .Case("{v26}", RISCV::V26) 11719 .Case("{v27}", RISCV::V27) 11720 .Case("{v28}", RISCV::V28) 11721 .Case("{v29}", RISCV::V29) 11722 .Case("{v30}", RISCV::V30) 11723 .Case("{v31}", RISCV::V31) 11724 .Default(RISCV::NoRegister); 11725 if (VReg != RISCV::NoRegister) { 11726 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11727 return std::make_pair(VReg, &RISCV::VMRegClass); 11728 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11729 return std::make_pair(VReg, &RISCV::VRRegClass); 11730 for (const auto *RC : 11731 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11732 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11733 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11734 return std::make_pair(VReg, RC); 11735 } 11736 } 11737 } 11738 } 11739 11740 std::pair<Register, const TargetRegisterClass *> Res = 11741 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11742 11743 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11744 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11745 // Subtarget into account. 11746 if (Res.second == &RISCV::GPRF16RegClass || 11747 Res.second == &RISCV::GPRF32RegClass || 11748 Res.second == &RISCV::GPRF64RegClass) 11749 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11750 11751 return Res; 11752 } 11753 11754 unsigned 11755 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11756 // Currently only support length 1 constraints. 11757 if (ConstraintCode.size() == 1) { 11758 switch (ConstraintCode[0]) { 11759 case 'A': 11760 return InlineAsm::Constraint_A; 11761 default: 11762 break; 11763 } 11764 } 11765 11766 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11767 } 11768 11769 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11770 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11771 SelectionDAG &DAG) const { 11772 // Currently only support length 1 constraints. 11773 if (Constraint.length() == 1) { 11774 switch (Constraint[0]) { 11775 case 'I': 11776 // Validate & create a 12-bit signed immediate operand. 11777 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11778 uint64_t CVal = C->getSExtValue(); 11779 if (isInt<12>(CVal)) 11780 Ops.push_back( 11781 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11782 } 11783 return; 11784 case 'J': 11785 // Validate & create an integer zero operand. 11786 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11787 if (C->getZExtValue() == 0) 11788 Ops.push_back( 11789 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11790 return; 11791 case 'K': 11792 // Validate & create a 5-bit unsigned immediate operand. 11793 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11794 uint64_t CVal = C->getZExtValue(); 11795 if (isUInt<5>(CVal)) 11796 Ops.push_back( 11797 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11798 } 11799 return; 11800 case 'S': 11801 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11802 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11803 GA->getValueType(0))); 11804 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11805 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11806 BA->getValueType(0))); 11807 } 11808 return; 11809 default: 11810 break; 11811 } 11812 } 11813 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11814 } 11815 11816 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11817 Instruction *Inst, 11818 AtomicOrdering Ord) const { 11819 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11820 return Builder.CreateFence(Ord); 11821 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11822 return Builder.CreateFence(AtomicOrdering::Release); 11823 return nullptr; 11824 } 11825 11826 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11827 Instruction *Inst, 11828 AtomicOrdering Ord) const { 11829 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11830 return Builder.CreateFence(AtomicOrdering::Acquire); 11831 return nullptr; 11832 } 11833 11834 TargetLowering::AtomicExpansionKind 11835 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11836 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11837 // point operations can't be used in an lr/sc sequence without breaking the 11838 // forward-progress guarantee. 11839 if (AI->isFloatingPointOperation()) 11840 return AtomicExpansionKind::CmpXChg; 11841 11842 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11843 if (Size == 8 || Size == 16) 11844 return AtomicExpansionKind::MaskedIntrinsic; 11845 return AtomicExpansionKind::None; 11846 } 11847 11848 static Intrinsic::ID 11849 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11850 if (XLen == 32) { 11851 switch (BinOp) { 11852 default: 11853 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11854 case AtomicRMWInst::Xchg: 11855 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11856 case AtomicRMWInst::Add: 11857 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11858 case AtomicRMWInst::Sub: 11859 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11860 case AtomicRMWInst::Nand: 11861 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11862 case AtomicRMWInst::Max: 11863 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11864 case AtomicRMWInst::Min: 11865 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11866 case AtomicRMWInst::UMax: 11867 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11868 case AtomicRMWInst::UMin: 11869 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11870 } 11871 } 11872 11873 if (XLen == 64) { 11874 switch (BinOp) { 11875 default: 11876 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11877 case AtomicRMWInst::Xchg: 11878 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11879 case AtomicRMWInst::Add: 11880 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11881 case AtomicRMWInst::Sub: 11882 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11883 case AtomicRMWInst::Nand: 11884 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11885 case AtomicRMWInst::Max: 11886 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11887 case AtomicRMWInst::Min: 11888 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11889 case AtomicRMWInst::UMax: 11890 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11891 case AtomicRMWInst::UMin: 11892 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11893 } 11894 } 11895 11896 llvm_unreachable("Unexpected XLen\n"); 11897 } 11898 11899 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11900 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11901 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11902 unsigned XLen = Subtarget.getXLen(); 11903 Value *Ordering = 11904 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11905 Type *Tys[] = {AlignedAddr->getType()}; 11906 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11907 AI->getModule(), 11908 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11909 11910 if (XLen == 64) { 11911 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11912 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11913 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11914 } 11915 11916 Value *Result; 11917 11918 // Must pass the shift amount needed to sign extend the loaded value prior 11919 // to performing a signed comparison for min/max. ShiftAmt is the number of 11920 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11921 // is the number of bits to left+right shift the value in order to 11922 // sign-extend. 11923 if (AI->getOperation() == AtomicRMWInst::Min || 11924 AI->getOperation() == AtomicRMWInst::Max) { 11925 const DataLayout &DL = AI->getModule()->getDataLayout(); 11926 unsigned ValWidth = 11927 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11928 Value *SextShamt = 11929 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11930 Result = Builder.CreateCall(LrwOpScwLoop, 11931 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11932 } else { 11933 Result = 11934 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11935 } 11936 11937 if (XLen == 64) 11938 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11939 return Result; 11940 } 11941 11942 TargetLowering::AtomicExpansionKind 11943 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11944 AtomicCmpXchgInst *CI) const { 11945 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11946 if (Size == 8 || Size == 16) 11947 return AtomicExpansionKind::MaskedIntrinsic; 11948 return AtomicExpansionKind::None; 11949 } 11950 11951 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11952 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11953 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11954 unsigned XLen = Subtarget.getXLen(); 11955 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11956 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11957 if (XLen == 64) { 11958 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11959 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11960 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11961 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11962 } 11963 Type *Tys[] = {AlignedAddr->getType()}; 11964 Function *MaskedCmpXchg = 11965 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11966 Value *Result = Builder.CreateCall( 11967 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11968 if (XLen == 64) 11969 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11970 return Result; 11971 } 11972 11973 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11974 EVT DataVT) const { 11975 return false; 11976 } 11977 11978 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11979 EVT VT) const { 11980 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11981 return false; 11982 11983 switch (FPVT.getSimpleVT().SimpleTy) { 11984 case MVT::f16: 11985 return Subtarget.hasStdExtZfh(); 11986 case MVT::f32: 11987 return Subtarget.hasStdExtF(); 11988 case MVT::f64: 11989 return Subtarget.hasStdExtD(); 11990 default: 11991 return false; 11992 } 11993 } 11994 11995 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11996 // If we are using the small code model, we can reduce size of jump table 11997 // entry to 4 bytes. 11998 if (Subtarget.is64Bit() && !isPositionIndependent() && 11999 getTargetMachine().getCodeModel() == CodeModel::Small) { 12000 return MachineJumpTableInfo::EK_Custom32; 12001 } 12002 return TargetLowering::getJumpTableEncoding(); 12003 } 12004 12005 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 12006 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 12007 unsigned uid, MCContext &Ctx) const { 12008 assert(Subtarget.is64Bit() && !isPositionIndependent() && 12009 getTargetMachine().getCodeModel() == CodeModel::Small); 12010 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 12011 } 12012 12013 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 12014 EVT VT) const { 12015 VT = VT.getScalarType(); 12016 12017 if (!VT.isSimple()) 12018 return false; 12019 12020 switch (VT.getSimpleVT().SimpleTy) { 12021 case MVT::f16: 12022 return Subtarget.hasStdExtZfh(); 12023 case MVT::f32: 12024 return Subtarget.hasStdExtF(); 12025 case MVT::f64: 12026 return Subtarget.hasStdExtD(); 12027 default: 12028 break; 12029 } 12030 12031 return false; 12032 } 12033 12034 Register RISCVTargetLowering::getExceptionPointerRegister( 12035 const Constant *PersonalityFn) const { 12036 return RISCV::X10; 12037 } 12038 12039 Register RISCVTargetLowering::getExceptionSelectorRegister( 12040 const Constant *PersonalityFn) const { 12041 return RISCV::X11; 12042 } 12043 12044 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12045 // Return false to suppress the unnecessary extensions if the LibCall 12046 // arguments or return value is f32 type for LP64 ABI. 12047 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12048 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12049 return false; 12050 12051 return true; 12052 } 12053 12054 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12055 if (Subtarget.is64Bit() && Type == MVT::i32) 12056 return true; 12057 12058 return IsSigned; 12059 } 12060 12061 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12062 SDValue C) const { 12063 // Check integral scalar types. 12064 if (VT.isScalarInteger()) { 12065 // Omit the optimization if the sub target has the M extension and the data 12066 // size exceeds XLen. 12067 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 12068 return false; 12069 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12070 // Break the MUL to a SLLI and an ADD/SUB. 12071 const APInt &Imm = ConstNode->getAPIntValue(); 12072 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12073 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12074 return true; 12075 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12076 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12077 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12078 (Imm - 8).isPowerOf2())) 12079 return true; 12080 // Omit the following optimization if the sub target has the M extension 12081 // and the data size >= XLen. 12082 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 12083 return false; 12084 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12085 // a pair of LUI/ADDI. 12086 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12087 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12088 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12089 (1 - ImmS).isPowerOf2()) 12090 return true; 12091 } 12092 } 12093 } 12094 12095 return false; 12096 } 12097 12098 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12099 SDValue ConstNode) const { 12100 // Let the DAGCombiner decide for vectors. 12101 EVT VT = AddNode.getValueType(); 12102 if (VT.isVector()) 12103 return true; 12104 12105 // Let the DAGCombiner decide for larger types. 12106 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12107 return true; 12108 12109 // It is worse if c1 is simm12 while c1*c2 is not. 12110 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12111 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12112 const APInt &C1 = C1Node->getAPIntValue(); 12113 const APInt &C2 = C2Node->getAPIntValue(); 12114 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12115 return false; 12116 12117 // Default to true and let the DAGCombiner decide. 12118 return true; 12119 } 12120 12121 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12122 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12123 bool *Fast) const { 12124 if (!VT.isVector()) { 12125 if (Fast) 12126 *Fast = false; 12127 return Subtarget.enableUnalignedScalarMem(); 12128 } 12129 12130 // All vector implementations must support element alignment 12131 EVT ElemVT = VT.getVectorElementType(); 12132 if (Alignment >= ElemVT.getStoreSize()) { 12133 if (Fast) 12134 *Fast = true; 12135 return true; 12136 } 12137 12138 return false; 12139 } 12140 12141 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12142 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12143 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12144 bool IsABIRegCopy = CC.has_value(); 12145 EVT ValueVT = Val.getValueType(); 12146 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12147 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12148 // and cast to f32. 12149 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12150 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12151 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12152 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12153 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12154 Parts[0] = Val; 12155 return true; 12156 } 12157 12158 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12159 LLVMContext &Context = *DAG.getContext(); 12160 EVT ValueEltVT = ValueVT.getVectorElementType(); 12161 EVT PartEltVT = PartVT.getVectorElementType(); 12162 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12163 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12164 if (PartVTBitSize % ValueVTBitSize == 0) { 12165 assert(PartVTBitSize >= ValueVTBitSize); 12166 // If the element types are different, bitcast to the same element type of 12167 // PartVT first. 12168 // Give an example here, we want copy a <vscale x 1 x i8> value to 12169 // <vscale x 4 x i16>. 12170 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12171 // subvector, then we can bitcast to <vscale x 4 x i16>. 12172 if (ValueEltVT != PartEltVT) { 12173 if (PartVTBitSize > ValueVTBitSize) { 12174 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12175 assert(Count != 0 && "The number of element should not be zero."); 12176 EVT SameEltTypeVT = 12177 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12178 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12179 DAG.getUNDEF(SameEltTypeVT), Val, 12180 DAG.getVectorIdxConstant(0, DL)); 12181 } 12182 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12183 } else { 12184 Val = 12185 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12186 Val, DAG.getVectorIdxConstant(0, DL)); 12187 } 12188 Parts[0] = Val; 12189 return true; 12190 } 12191 } 12192 return false; 12193 } 12194 12195 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12196 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12197 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12198 bool IsABIRegCopy = CC.has_value(); 12199 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12200 SDValue Val = Parts[0]; 12201 12202 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12203 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12204 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12205 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12206 return Val; 12207 } 12208 12209 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12210 LLVMContext &Context = *DAG.getContext(); 12211 SDValue Val = Parts[0]; 12212 EVT ValueEltVT = ValueVT.getVectorElementType(); 12213 EVT PartEltVT = PartVT.getVectorElementType(); 12214 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12215 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12216 if (PartVTBitSize % ValueVTBitSize == 0) { 12217 assert(PartVTBitSize >= ValueVTBitSize); 12218 EVT SameEltTypeVT = ValueVT; 12219 // If the element types are different, convert it to the same element type 12220 // of PartVT. 12221 // Give an example here, we want copy a <vscale x 1 x i8> value from 12222 // <vscale x 4 x i16>. 12223 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12224 // then we can extract <vscale x 1 x i8>. 12225 if (ValueEltVT != PartEltVT) { 12226 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12227 assert(Count != 0 && "The number of element should not be zero."); 12228 SameEltTypeVT = 12229 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12230 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12231 } 12232 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12233 DAG.getVectorIdxConstant(0, DL)); 12234 return Val; 12235 } 12236 } 12237 return SDValue(); 12238 } 12239 12240 SDValue 12241 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12242 SelectionDAG &DAG, 12243 SmallVectorImpl<SDNode *> &Created) const { 12244 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12245 if (isIntDivCheap(N->getValueType(0), Attr)) 12246 return SDValue(N, 0); // Lower SDIV as SDIV 12247 12248 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12249 "Unexpected divisor!"); 12250 12251 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12252 if (!Subtarget.hasStdExtZbt()) 12253 return SDValue(); 12254 12255 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12256 // Besides, more critical path instructions will be generated when dividing 12257 // by 2. So we keep using the original DAGs for these cases. 12258 unsigned Lg2 = Divisor.countTrailingZeros(); 12259 if (Lg2 == 1 || Lg2 >= 12) 12260 return SDValue(); 12261 12262 // fold (sdiv X, pow2) 12263 EVT VT = N->getValueType(0); 12264 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12265 return SDValue(); 12266 12267 SDLoc DL(N); 12268 SDValue N0 = N->getOperand(0); 12269 SDValue Zero = DAG.getConstant(0, DL, VT); 12270 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12271 12272 // Add (N0 < 0) ? Pow2 - 1 : 0; 12273 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12274 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12275 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12276 12277 Created.push_back(Cmp.getNode()); 12278 Created.push_back(Add.getNode()); 12279 Created.push_back(Sel.getNode()); 12280 12281 // Divide by pow2. 12282 SDValue SRA = 12283 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12284 12285 // If we're dividing by a positive value, we're done. Otherwise, we must 12286 // negate the result. 12287 if (Divisor.isNonNegative()) 12288 return SRA; 12289 12290 Created.push_back(SRA.getNode()); 12291 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12292 } 12293 12294 #define GET_REGISTER_MATCHER 12295 #include "RISCVGenAsmMatcher.inc" 12296 12297 Register 12298 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12299 const MachineFunction &MF) const { 12300 Register Reg = MatchRegisterAltName(RegName); 12301 if (Reg == RISCV::NoRegister) 12302 Reg = MatchRegisterName(RegName); 12303 if (Reg == RISCV::NoRegister) 12304 report_fatal_error( 12305 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12306 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12307 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12308 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12309 StringRef(RegName) + "\".")); 12310 return Reg; 12311 } 12312 12313 namespace llvm { 12314 namespace RISCVVIntrinsicsTable { 12315 12316 #define GET_RISCVVIntrinsicsTable_IMPL 12317 #include "RISCVGenSearchableTables.inc" 12318 12319 } // namespace RISCVVIntrinsicsTable 12320 12321 } // namespace llvm 12322