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 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT, 174 MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand); 188 189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 190 191 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 192 193 if (!Subtarget.hasStdExtZbb()) 194 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 195 196 if (Subtarget.is64Bit()) { 197 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 198 199 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 200 MVT::i32, Custom); 201 202 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 203 MVT::i32, Custom); 204 } else { 205 setLibcallName( 206 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 207 nullptr); 208 setLibcallName(RTLIB::MULO_I64, nullptr); 209 } 210 211 if (!Subtarget.hasStdExtM()) { 212 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 213 ISD::SREM, ISD::UREM}, 214 XLenVT, Expand); 215 } else { 216 if (Subtarget.is64Bit()) { 217 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 218 219 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 220 {MVT::i8, MVT::i16, MVT::i32}, Custom); 221 } else { 222 setOperationAction(ISD::MUL, MVT::i64, Custom); 223 } 224 } 225 226 setOperationAction( 227 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 228 Expand); 229 230 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 231 Custom); 232 233 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 234 Subtarget.hasStdExtZbkb()) { 235 if (Subtarget.is64Bit()) 236 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 237 } else { 238 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 239 } 240 241 if (Subtarget.hasStdExtZbp()) { 242 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 243 // more combining. 244 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 245 246 // BSWAP i8 doesn't exist. 247 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 248 249 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 250 251 if (Subtarget.is64Bit()) 252 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 253 } else { 254 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 255 // pattern match it directly in isel. 256 setOperationAction(ISD::BSWAP, XLenVT, 257 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 258 ? Legal 259 : Expand); 260 // Zbkb can use rev8+brev8 to implement bitreverse. 261 setOperationAction(ISD::BITREVERSE, XLenVT, 262 Subtarget.hasStdExtZbkb() ? Custom : Expand); 263 } 264 265 if (Subtarget.hasStdExtZbb()) { 266 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 267 Legal); 268 269 if (Subtarget.is64Bit()) 270 setOperationAction( 271 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 272 MVT::i32, Custom); 273 } else { 274 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 275 276 if (Subtarget.is64Bit()) 277 setOperationAction(ISD::ABS, MVT::i32, Custom); 278 } 279 280 if (Subtarget.hasStdExtZbt()) { 281 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 282 setOperationAction(ISD::SELECT, XLenVT, Legal); 283 284 if (Subtarget.is64Bit()) 285 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 286 } else { 287 setOperationAction(ISD::SELECT, XLenVT, Custom); 288 } 289 290 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 291 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 292 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 293 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 294 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 295 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 296 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 297 298 static const ISD::CondCode FPCCToExpand[] = { 299 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 300 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 301 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 302 303 static const ISD::NodeType FPOpToExpand[] = { 304 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 305 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 306 307 if (Subtarget.hasStdExtZfh()) 308 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 309 310 if (Subtarget.hasStdExtZfh()) { 311 for (auto NT : FPLegalNodeTypes) 312 setOperationAction(NT, MVT::f16, Legal); 313 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 314 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 315 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 316 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 317 setOperationAction(ISD::SELECT, MVT::f16, Custom); 318 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 319 320 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 321 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 322 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 323 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 324 ISD::FLOG2, ISD::FLOG10}, 325 MVT::f16, Promote); 326 327 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 328 // complete support for all operations in LegalizeDAG. 329 330 // We need to custom promote this. 331 if (Subtarget.is64Bit()) 332 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 333 } 334 335 if (Subtarget.hasStdExtF()) { 336 for (auto NT : FPLegalNodeTypes) 337 setOperationAction(NT, MVT::f32, Legal); 338 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 339 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 340 setOperationAction(ISD::SELECT, MVT::f32, Custom); 341 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 342 for (auto Op : FPOpToExpand) 343 setOperationAction(Op, MVT::f32, Expand); 344 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 345 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 346 } 347 348 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 349 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 350 351 if (Subtarget.hasStdExtD()) { 352 for (auto NT : FPLegalNodeTypes) 353 setOperationAction(NT, MVT::f64, Legal); 354 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 355 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 356 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 357 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 358 setOperationAction(ISD::SELECT, MVT::f64, Custom); 359 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 360 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 361 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 362 for (auto Op : FPOpToExpand) 363 setOperationAction(Op, MVT::f64, Expand); 364 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 365 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 366 } 367 368 if (Subtarget.is64Bit()) 369 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 370 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 371 MVT::i32, Custom); 372 373 if (Subtarget.hasStdExtF()) { 374 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 375 Custom); 376 377 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 378 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 379 XLenVT, Legal); 380 381 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 382 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 383 } 384 385 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 386 ISD::JumpTable}, 387 XLenVT, Custom); 388 389 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 390 391 if (Subtarget.is64Bit()) 392 setOperationAction(ISD::Constant, MVT::i64, Custom); 393 394 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 395 // Unfortunately this can't be determined just from the ISA naming string. 396 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 397 Subtarget.is64Bit() ? Legal : Custom); 398 399 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 400 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 401 if (Subtarget.is64Bit()) 402 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 403 404 if (Subtarget.hasStdExtA()) { 405 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 406 setMinCmpXchgSizeInBits(32); 407 } else { 408 setMaxAtomicSizeInBitsSupported(0); 409 } 410 411 setBooleanContents(ZeroOrOneBooleanContent); 412 413 if (Subtarget.hasVInstructions()) { 414 setBooleanVectorContents(ZeroOrOneBooleanContent); 415 416 setOperationAction(ISD::VSCALE, XLenVT, Custom); 417 418 // RVV intrinsics may have illegal operands. 419 // We also need to custom legalize vmv.x.s. 420 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 421 {MVT::i8, MVT::i16}, Custom); 422 if (Subtarget.is64Bit()) 423 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 424 else 425 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 426 MVT::i64, Custom); 427 428 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 429 MVT::Other, Custom); 430 431 static const unsigned IntegerVPOps[] = { 432 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 433 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 434 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 435 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 436 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 437 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 438 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 439 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 440 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 441 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 442 443 static const unsigned FloatingPointVPOps[] = { 444 ISD::VP_FADD, ISD::VP_FSUB, 445 ISD::VP_FMUL, ISD::VP_FDIV, 446 ISD::VP_FNEG, ISD::VP_FMA, 447 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 448 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 449 ISD::VP_MERGE, ISD::VP_SELECT, 450 ISD::VP_SITOFP, ISD::VP_UITOFP, 451 ISD::VP_SETCC, ISD::VP_FP_ROUND, 452 ISD::VP_FP_EXTEND}; 453 454 if (!Subtarget.is64Bit()) { 455 // We must custom-lower certain vXi64 operations on RV32 due to the vector 456 // element type being illegal. 457 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 458 MVT::i64, Custom); 459 460 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 461 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 462 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 463 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 464 MVT::i64, Custom); 465 466 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 467 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 468 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 469 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 470 MVT::i64, Custom); 471 } 472 473 for (MVT VT : BoolVecVTs) { 474 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 475 476 // Mask VTs are custom-expanded into a series of standard nodes 477 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 478 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 479 VT, Custom); 480 481 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 482 Custom); 483 484 setOperationAction(ISD::SELECT, VT, Custom); 485 setOperationAction( 486 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 487 Expand); 488 489 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 490 491 setOperationAction( 492 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 493 Custom); 494 495 setOperationAction( 496 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 497 Custom); 498 499 // RVV has native int->float & float->int conversions where the 500 // element type sizes are within one power-of-two of each other. Any 501 // wider distances between type sizes have to be lowered as sequences 502 // which progressively narrow the gap in stages. 503 setOperationAction( 504 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 505 VT, Custom); 506 507 // Expand all extending loads to types larger than this, and truncating 508 // stores from types larger than this. 509 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 510 setTruncStoreAction(OtherVT, VT, Expand); 511 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 512 VT, Expand); 513 } 514 515 setOperationAction( 516 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 517 Custom); 518 } 519 520 for (MVT VT : IntVecVTs) { 521 if (VT.getVectorElementType() == MVT::i64 && 522 !Subtarget.hasVInstructionsI64()) 523 continue; 524 525 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 526 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 527 528 // Vectors implement MULHS/MULHU. 529 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 530 531 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 532 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 533 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 534 535 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 536 Legal); 537 538 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 539 540 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 541 Expand); 542 543 setOperationAction(ISD::BSWAP, VT, Expand); 544 545 // Custom-lower extensions and truncations from/to mask types. 546 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 547 VT, Custom); 548 549 // RVV has native int->float & float->int conversions where the 550 // element type sizes are within one power-of-two of each other. Any 551 // wider distances between type sizes have to be lowered as sequences 552 // which progressively narrow the gap in stages. 553 setOperationAction( 554 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 555 VT, Custom); 556 557 setOperationAction( 558 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 559 560 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 561 // nodes which truncate by one power of two at a time. 562 setOperationAction(ISD::TRUNCATE, VT, Custom); 563 564 // Custom-lower insert/extract operations to simplify patterns. 565 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 566 Custom); 567 568 // Custom-lower reduction operations to set up the corresponding custom 569 // nodes' operands. 570 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 571 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 572 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 573 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 574 VT, Custom); 575 576 setOperationAction(IntegerVPOps, VT, Custom); 577 578 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 579 580 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 581 VT, Custom); 582 583 setOperationAction( 584 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 585 Custom); 586 587 setOperationAction( 588 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 589 VT, Custom); 590 591 setOperationAction(ISD::SELECT, VT, Custom); 592 setOperationAction(ISD::SELECT_CC, VT, Expand); 593 594 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 595 596 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 597 setTruncStoreAction(VT, OtherVT, Expand); 598 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 599 VT, Expand); 600 } 601 602 // Splice 603 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 604 605 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 606 // type that can represent the value exactly. 607 if (VT.getVectorElementType() != MVT::i64) { 608 MVT FloatEltVT = 609 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 610 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 611 if (isTypeLegal(FloatVT)) { 612 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 613 Custom); 614 } 615 } 616 } 617 618 // Expand various CCs to best match the RVV ISA, which natively supports UNE 619 // but no other unordered comparisons, and supports all ordered comparisons 620 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 621 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 622 // and we pattern-match those back to the "original", swapping operands once 623 // more. This way we catch both operations and both "vf" and "fv" forms with 624 // fewer patterns. 625 static const ISD::CondCode VFPCCToExpand[] = { 626 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 627 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 628 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 629 }; 630 631 // Sets common operation actions on RVV floating-point vector types. 632 const auto SetCommonVFPActions = [&](MVT VT) { 633 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 634 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 635 // sizes are within one power-of-two of each other. Therefore conversions 636 // between vXf16 and vXf64 must be lowered as sequences which convert via 637 // vXf32. 638 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 639 // Custom-lower insert/extract operations to simplify patterns. 640 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 641 Custom); 642 // Expand various condition codes (explained above). 643 setCondCodeAction(VFPCCToExpand, VT, Expand); 644 645 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 646 647 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 648 VT, Custom); 649 650 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 651 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 652 VT, Custom); 653 654 // Expand FP operations that need libcalls. 655 setOperationAction(ISD::FREM, VT, Expand); 656 setOperationAction(ISD::FPOW, VT, Expand); 657 setOperationAction(ISD::FCOS, VT, Expand); 658 setOperationAction(ISD::FSIN, VT, Expand); 659 setOperationAction(ISD::FSINCOS, VT, Expand); 660 setOperationAction(ISD::FEXP, VT, Expand); 661 setOperationAction(ISD::FEXP2, VT, Expand); 662 setOperationAction(ISD::FLOG, VT, Expand); 663 setOperationAction(ISD::FLOG2, VT, Expand); 664 setOperationAction(ISD::FLOG10, VT, Expand); 665 setOperationAction(ISD::FRINT, VT, Expand); 666 setOperationAction(ISD::FNEARBYINT, VT, Expand); 667 668 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 669 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 670 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 671 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 672 673 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 674 675 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 676 677 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 678 VT, Custom); 679 680 setOperationAction( 681 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 682 Custom); 683 684 setOperationAction(ISD::SELECT, VT, Custom); 685 setOperationAction(ISD::SELECT_CC, VT, Expand); 686 687 setOperationAction( 688 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 689 VT, Custom); 690 691 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 692 693 setOperationAction(FloatingPointVPOps, VT, Custom); 694 }; 695 696 // Sets common extload/truncstore actions on RVV floating-point vector 697 // types. 698 const auto SetCommonVFPExtLoadTruncStoreActions = 699 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 700 for (auto SmallVT : SmallerVTs) { 701 setTruncStoreAction(VT, SmallVT, Expand); 702 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 703 } 704 }; 705 706 if (Subtarget.hasVInstructionsF16()) 707 for (MVT VT : F16VecVTs) 708 SetCommonVFPActions(VT); 709 710 for (MVT VT : F32VecVTs) { 711 if (Subtarget.hasVInstructionsF32()) 712 SetCommonVFPActions(VT); 713 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 714 } 715 716 for (MVT VT : F64VecVTs) { 717 if (Subtarget.hasVInstructionsF64()) 718 SetCommonVFPActions(VT); 719 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 720 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 721 } 722 723 if (Subtarget.useRVVForFixedLengthVectors()) { 724 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 725 if (!useRVVForFixedLengthVectorVT(VT)) 726 continue; 727 728 // By default everything must be expanded. 729 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 730 setOperationAction(Op, VT, Expand); 731 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 732 setTruncStoreAction(VT, OtherVT, Expand); 733 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 734 OtherVT, VT, Expand); 735 } 736 737 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 738 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 739 Custom); 740 741 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 742 Custom); 743 744 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 745 VT, Custom); 746 747 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 748 749 setOperationAction(ISD::SETCC, VT, Custom); 750 751 setOperationAction(ISD::SELECT, VT, Custom); 752 753 setOperationAction(ISD::TRUNCATE, VT, Custom); 754 755 setOperationAction(ISD::BITCAST, VT, Custom); 756 757 setOperationAction( 758 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 759 Custom); 760 761 setOperationAction( 762 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 763 Custom); 764 765 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 766 ISD::FP_TO_UINT}, 767 VT, Custom); 768 769 // Operations below are different for between masks and other vectors. 770 if (VT.getVectorElementType() == MVT::i1) { 771 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 772 ISD::OR, ISD::XOR}, 773 VT, Custom); 774 775 setOperationAction( 776 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 777 VT, Custom); 778 continue; 779 } 780 781 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 782 // it before type legalization for i64 vectors on RV32. It will then be 783 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 784 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 785 // improvements first. 786 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 787 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 788 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 789 } 790 791 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 792 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 793 794 setOperationAction( 795 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 796 797 setOperationAction( 798 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 799 Custom); 800 801 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 802 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 803 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 804 VT, Custom); 805 806 setOperationAction( 807 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 808 809 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 810 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 811 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 812 813 setOperationAction( 814 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 815 Custom); 816 817 setOperationAction(ISD::VSELECT, VT, Custom); 818 setOperationAction(ISD::SELECT_CC, VT, Expand); 819 820 setOperationAction( 821 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 822 823 // Custom-lower reduction operations to set up the corresponding custom 824 // nodes' operands. 825 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 826 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 827 ISD::VECREDUCE_UMIN}, 828 VT, Custom); 829 830 setOperationAction(IntegerVPOps, VT, Custom); 831 832 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 833 // type that can represent the value exactly. 834 if (VT.getVectorElementType() != MVT::i64) { 835 MVT FloatEltVT = 836 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 837 EVT FloatVT = 838 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 839 if (isTypeLegal(FloatVT)) 840 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 841 Custom); 842 } 843 } 844 845 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 846 if (!useRVVForFixedLengthVectorVT(VT)) 847 continue; 848 849 // By default everything must be expanded. 850 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 851 setOperationAction(Op, VT, Expand); 852 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 853 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 854 setTruncStoreAction(VT, OtherVT, Expand); 855 } 856 857 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 858 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 859 Custom); 860 861 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 862 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 863 ISD::EXTRACT_VECTOR_ELT}, 864 VT, Custom); 865 866 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 867 ISD::MGATHER, ISD::MSCATTER}, 868 VT, Custom); 869 870 setOperationAction( 871 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 872 Custom); 873 874 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 875 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 876 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 877 VT, Custom); 878 879 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 880 881 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 882 VT, Custom); 883 884 for (auto CC : VFPCCToExpand) 885 setCondCodeAction(CC, VT, Expand); 886 887 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 888 setOperationAction(ISD::SELECT_CC, VT, Expand); 889 890 setOperationAction(ISD::BITCAST, VT, Custom); 891 892 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 893 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 894 VT, Custom); 895 896 setOperationAction(FloatingPointVPOps, VT, Custom); 897 } 898 899 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 900 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 901 Custom); 902 if (Subtarget.hasStdExtZfh()) 903 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 904 if (Subtarget.hasStdExtF()) 905 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 906 if (Subtarget.hasStdExtD()) 907 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 908 } 909 } 910 911 // Function alignments. 912 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 913 setMinFunctionAlignment(FunctionAlignment); 914 setPrefFunctionAlignment(FunctionAlignment); 915 916 setMinimumJumpTableEntries(5); 917 918 // Jumps are expensive, compared to logic 919 setJumpIsExpensive(); 920 921 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 922 ISD::OR, ISD::XOR}); 923 924 if (Subtarget.hasStdExtF()) 925 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 926 927 if (Subtarget.hasStdExtZbp()) 928 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 929 930 if (Subtarget.hasStdExtZbb()) 931 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 932 933 if (Subtarget.hasStdExtZbkb()) 934 setTargetDAGCombine(ISD::BITREVERSE); 935 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 936 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 937 if (Subtarget.hasStdExtF()) 938 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 939 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 940 if (Subtarget.hasVInstructions()) 941 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 942 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 943 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 944 945 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 946 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 947 } 948 949 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 950 LLVMContext &Context, 951 EVT VT) const { 952 if (!VT.isVector()) 953 return getPointerTy(DL); 954 if (Subtarget.hasVInstructions() && 955 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 956 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 957 return VT.changeVectorElementTypeToInteger(); 958 } 959 960 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 961 return Subtarget.getXLenVT(); 962 } 963 964 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 965 const CallInst &I, 966 MachineFunction &MF, 967 unsigned Intrinsic) const { 968 auto &DL = I.getModule()->getDataLayout(); 969 switch (Intrinsic) { 970 default: 971 return false; 972 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 973 case Intrinsic::riscv_masked_atomicrmw_add_i32: 974 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 975 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 976 case Intrinsic::riscv_masked_atomicrmw_max_i32: 977 case Intrinsic::riscv_masked_atomicrmw_min_i32: 978 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 979 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 980 case Intrinsic::riscv_masked_cmpxchg_i32: 981 Info.opc = ISD::INTRINSIC_W_CHAIN; 982 Info.memVT = MVT::i32; 983 Info.ptrVal = I.getArgOperand(0); 984 Info.offset = 0; 985 Info.align = Align(4); 986 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 987 MachineMemOperand::MOVolatile; 988 return true; 989 case Intrinsic::riscv_masked_strided_load: 990 Info.opc = ISD::INTRINSIC_W_CHAIN; 991 Info.ptrVal = I.getArgOperand(1); 992 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 993 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 994 Info.size = MemoryLocation::UnknownSize; 995 Info.flags |= MachineMemOperand::MOLoad; 996 return true; 997 case Intrinsic::riscv_masked_strided_store: 998 Info.opc = ISD::INTRINSIC_VOID; 999 Info.ptrVal = I.getArgOperand(1); 1000 Info.memVT = 1001 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1002 Info.align = Align( 1003 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1004 8); 1005 Info.size = MemoryLocation::UnknownSize; 1006 Info.flags |= MachineMemOperand::MOStore; 1007 return true; 1008 case Intrinsic::riscv_seg2_load: 1009 case Intrinsic::riscv_seg3_load: 1010 case Intrinsic::riscv_seg4_load: 1011 case Intrinsic::riscv_seg5_load: 1012 case Intrinsic::riscv_seg6_load: 1013 case Intrinsic::riscv_seg7_load: 1014 case Intrinsic::riscv_seg8_load: 1015 Info.opc = ISD::INTRINSIC_W_CHAIN; 1016 Info.ptrVal = I.getArgOperand(0); 1017 Info.memVT = 1018 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1019 Info.align = 1020 Align(DL.getTypeSizeInBits( 1021 I.getType()->getStructElementType(0)->getScalarType()) / 1022 8); 1023 Info.size = MemoryLocation::UnknownSize; 1024 Info.flags |= MachineMemOperand::MOLoad; 1025 return true; 1026 } 1027 } 1028 1029 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1030 const AddrMode &AM, Type *Ty, 1031 unsigned AS, 1032 Instruction *I) const { 1033 // No global is ever allowed as a base. 1034 if (AM.BaseGV) 1035 return false; 1036 1037 // RVV instructions only support register addressing. 1038 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1039 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1040 1041 // Require a 12-bit signed offset. 1042 if (!isInt<12>(AM.BaseOffs)) 1043 return false; 1044 1045 switch (AM.Scale) { 1046 case 0: // "r+i" or just "i", depending on HasBaseReg. 1047 break; 1048 case 1: 1049 if (!AM.HasBaseReg) // allow "r+i". 1050 break; 1051 return false; // disallow "r+r" or "r+r+i". 1052 default: 1053 return false; 1054 } 1055 1056 return true; 1057 } 1058 1059 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1060 return isInt<12>(Imm); 1061 } 1062 1063 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1064 return isInt<12>(Imm); 1065 } 1066 1067 // On RV32, 64-bit integers are split into their high and low parts and held 1068 // in two different registers, so the trunc is free since the low register can 1069 // just be used. 1070 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1071 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1072 return false; 1073 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1074 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1075 return (SrcBits == 64 && DestBits == 32); 1076 } 1077 1078 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1079 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1080 !SrcVT.isInteger() || !DstVT.isInteger()) 1081 return false; 1082 unsigned SrcBits = SrcVT.getSizeInBits(); 1083 unsigned DestBits = DstVT.getSizeInBits(); 1084 return (SrcBits == 64 && DestBits == 32); 1085 } 1086 1087 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1088 // Zexts are free if they can be combined with a load. 1089 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1090 // poorly with type legalization of compares preferring sext. 1091 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1092 EVT MemVT = LD->getMemoryVT(); 1093 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1094 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1095 LD->getExtensionType() == ISD::ZEXTLOAD)) 1096 return true; 1097 } 1098 1099 return TargetLowering::isZExtFree(Val, VT2); 1100 } 1101 1102 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1103 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1104 } 1105 1106 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1107 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1108 } 1109 1110 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1111 return Subtarget.hasStdExtZbb(); 1112 } 1113 1114 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1115 return Subtarget.hasStdExtZbb(); 1116 } 1117 1118 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1119 EVT VT = Y.getValueType(); 1120 1121 // FIXME: Support vectors once we have tests. 1122 if (VT.isVector()) 1123 return false; 1124 1125 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1126 Subtarget.hasStdExtZbkb()) && 1127 !isa<ConstantSDNode>(Y); 1128 } 1129 1130 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1131 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1132 auto *C = dyn_cast<ConstantSDNode>(Y); 1133 return C && C->getAPIntValue().ule(10); 1134 } 1135 1136 bool RISCVTargetLowering:: 1137 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1138 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1139 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1140 SelectionDAG &DAG) const { 1141 // One interesting pattern that we'd want to form is 'bit extract': 1142 // ((1 >> Y) & 1) ==/!= 0 1143 // But we also need to be careful not to try to reverse that fold. 1144 1145 // Is this '((1 >> Y) & 1)'? 1146 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1147 return false; // Keep the 'bit extract' pattern. 1148 1149 // Will this be '((1 >> Y) & 1)' after the transform? 1150 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1151 return true; // Do form the 'bit extract' pattern. 1152 1153 // If 'X' is a constant, and we transform, then we will immediately 1154 // try to undo the fold, thus causing endless combine loop. 1155 // So only do the transform if X is not a constant. This matches the default 1156 // implementation of this function. 1157 return !XC; 1158 } 1159 1160 /// Check if sinking \p I's operands to I's basic block is profitable, because 1161 /// the operands can be folded into a target instruction, e.g. 1162 /// splats of scalars can fold into vector instructions. 1163 bool RISCVTargetLowering::shouldSinkOperands( 1164 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1165 using namespace llvm::PatternMatch; 1166 1167 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1168 return false; 1169 1170 auto IsSinker = [&](Instruction *I, int Operand) { 1171 switch (I->getOpcode()) { 1172 case Instruction::Add: 1173 case Instruction::Sub: 1174 case Instruction::Mul: 1175 case Instruction::And: 1176 case Instruction::Or: 1177 case Instruction::Xor: 1178 case Instruction::FAdd: 1179 case Instruction::FSub: 1180 case Instruction::FMul: 1181 case Instruction::FDiv: 1182 case Instruction::ICmp: 1183 case Instruction::FCmp: 1184 return true; 1185 case Instruction::Shl: 1186 case Instruction::LShr: 1187 case Instruction::AShr: 1188 case Instruction::UDiv: 1189 case Instruction::SDiv: 1190 case Instruction::URem: 1191 case Instruction::SRem: 1192 return Operand == 1; 1193 case Instruction::Call: 1194 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1195 switch (II->getIntrinsicID()) { 1196 case Intrinsic::fma: 1197 case Intrinsic::vp_fma: 1198 return Operand == 0 || Operand == 1; 1199 // FIXME: Our patterns can only match vx/vf instructions when the splat 1200 // it on the RHS, because TableGen doesn't recognize our VP operations 1201 // as commutative. 1202 case Intrinsic::vp_add: 1203 case Intrinsic::vp_mul: 1204 case Intrinsic::vp_and: 1205 case Intrinsic::vp_or: 1206 case Intrinsic::vp_xor: 1207 case Intrinsic::vp_fadd: 1208 case Intrinsic::vp_fmul: 1209 case Intrinsic::vp_shl: 1210 case Intrinsic::vp_lshr: 1211 case Intrinsic::vp_ashr: 1212 case Intrinsic::vp_udiv: 1213 case Intrinsic::vp_sdiv: 1214 case Intrinsic::vp_urem: 1215 case Intrinsic::vp_srem: 1216 return Operand == 1; 1217 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1218 // explicit patterns for both LHS and RHS (as 'vr' versions). 1219 case Intrinsic::vp_sub: 1220 case Intrinsic::vp_fsub: 1221 case Intrinsic::vp_fdiv: 1222 return Operand == 0 || Operand == 1; 1223 default: 1224 return false; 1225 } 1226 } 1227 return false; 1228 default: 1229 return false; 1230 } 1231 }; 1232 1233 for (auto OpIdx : enumerate(I->operands())) { 1234 if (!IsSinker(I, OpIdx.index())) 1235 continue; 1236 1237 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1238 // Make sure we are not already sinking this operand 1239 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1240 continue; 1241 1242 // We are looking for a splat that can be sunk. 1243 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1244 m_Undef(), m_ZeroMask()))) 1245 continue; 1246 1247 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1248 // and vector registers 1249 for (Use &U : Op->uses()) { 1250 Instruction *Insn = cast<Instruction>(U.getUser()); 1251 if (!IsSinker(Insn, U.getOperandNo())) 1252 return false; 1253 } 1254 1255 Ops.push_back(&Op->getOperandUse(0)); 1256 Ops.push_back(&OpIdx.value()); 1257 } 1258 return true; 1259 } 1260 1261 bool RISCVTargetLowering::isOffsetFoldingLegal( 1262 const GlobalAddressSDNode *GA) const { 1263 // In order to maximise the opportunity for common subexpression elimination, 1264 // keep a separate ADD node for the global address offset instead of folding 1265 // it in the global address node. Later peephole optimisations may choose to 1266 // fold it back in when profitable. 1267 return false; 1268 } 1269 1270 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1271 bool ForCodeSize) const { 1272 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1273 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1274 return false; 1275 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1276 return false; 1277 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1278 return false; 1279 return Imm.isZero(); 1280 } 1281 1282 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1283 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1284 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1285 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1286 } 1287 1288 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1289 CallingConv::ID CC, 1290 EVT VT) const { 1291 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1292 // We might still end up using a GPR but that will be decided based on ABI. 1293 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1294 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1295 return MVT::f32; 1296 1297 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1298 } 1299 1300 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1301 CallingConv::ID CC, 1302 EVT VT) const { 1303 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1304 // We might still end up using a GPR but that will be decided based on ABI. 1305 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1306 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1307 return 1; 1308 1309 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1310 } 1311 1312 // Changes the condition code and swaps operands if necessary, so the SetCC 1313 // operation matches one of the comparisons supported directly by branches 1314 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1315 // with 1/-1. 1316 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1317 ISD::CondCode &CC, SelectionDAG &DAG) { 1318 // Convert X > -1 to X >= 0. 1319 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1320 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1321 CC = ISD::SETGE; 1322 return; 1323 } 1324 // Convert X < 1 to 0 >= X. 1325 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1326 RHS = LHS; 1327 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1328 CC = ISD::SETGE; 1329 return; 1330 } 1331 1332 switch (CC) { 1333 default: 1334 break; 1335 case ISD::SETGT: 1336 case ISD::SETLE: 1337 case ISD::SETUGT: 1338 case ISD::SETULE: 1339 CC = ISD::getSetCCSwappedOperands(CC); 1340 std::swap(LHS, RHS); 1341 break; 1342 } 1343 } 1344 1345 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1346 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1347 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1348 if (VT.getVectorElementType() == MVT::i1) 1349 KnownSize *= 8; 1350 1351 switch (KnownSize) { 1352 default: 1353 llvm_unreachable("Invalid LMUL."); 1354 case 8: 1355 return RISCVII::VLMUL::LMUL_F8; 1356 case 16: 1357 return RISCVII::VLMUL::LMUL_F4; 1358 case 32: 1359 return RISCVII::VLMUL::LMUL_F2; 1360 case 64: 1361 return RISCVII::VLMUL::LMUL_1; 1362 case 128: 1363 return RISCVII::VLMUL::LMUL_2; 1364 case 256: 1365 return RISCVII::VLMUL::LMUL_4; 1366 case 512: 1367 return RISCVII::VLMUL::LMUL_8; 1368 } 1369 } 1370 1371 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1372 switch (LMul) { 1373 default: 1374 llvm_unreachable("Invalid LMUL."); 1375 case RISCVII::VLMUL::LMUL_F8: 1376 case RISCVII::VLMUL::LMUL_F4: 1377 case RISCVII::VLMUL::LMUL_F2: 1378 case RISCVII::VLMUL::LMUL_1: 1379 return RISCV::VRRegClassID; 1380 case RISCVII::VLMUL::LMUL_2: 1381 return RISCV::VRM2RegClassID; 1382 case RISCVII::VLMUL::LMUL_4: 1383 return RISCV::VRM4RegClassID; 1384 case RISCVII::VLMUL::LMUL_8: 1385 return RISCV::VRM8RegClassID; 1386 } 1387 } 1388 1389 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1390 RISCVII::VLMUL LMUL = getLMUL(VT); 1391 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1392 LMUL == RISCVII::VLMUL::LMUL_F4 || 1393 LMUL == RISCVII::VLMUL::LMUL_F2 || 1394 LMUL == RISCVII::VLMUL::LMUL_1) { 1395 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1396 "Unexpected subreg numbering"); 1397 return RISCV::sub_vrm1_0 + Index; 1398 } 1399 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1400 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1401 "Unexpected subreg numbering"); 1402 return RISCV::sub_vrm2_0 + Index; 1403 } 1404 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1405 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1406 "Unexpected subreg numbering"); 1407 return RISCV::sub_vrm4_0 + Index; 1408 } 1409 llvm_unreachable("Invalid vector type."); 1410 } 1411 1412 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1413 if (VT.getVectorElementType() == MVT::i1) 1414 return RISCV::VRRegClassID; 1415 return getRegClassIDForLMUL(getLMUL(VT)); 1416 } 1417 1418 // Attempt to decompose a subvector insert/extract between VecVT and 1419 // SubVecVT via subregister indices. Returns the subregister index that 1420 // can perform the subvector insert/extract with the given element index, as 1421 // well as the index corresponding to any leftover subvectors that must be 1422 // further inserted/extracted within the register class for SubVecVT. 1423 std::pair<unsigned, unsigned> 1424 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1425 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1426 const RISCVRegisterInfo *TRI) { 1427 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1428 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1429 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1430 "Register classes not ordered"); 1431 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1432 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1433 // Try to compose a subregister index that takes us from the incoming 1434 // LMUL>1 register class down to the outgoing one. At each step we half 1435 // the LMUL: 1436 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1437 // Note that this is not guaranteed to find a subregister index, such as 1438 // when we are extracting from one VR type to another. 1439 unsigned SubRegIdx = RISCV::NoSubRegister; 1440 for (const unsigned RCID : 1441 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1442 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1443 VecVT = VecVT.getHalfNumVectorElementsVT(); 1444 bool IsHi = 1445 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1446 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1447 getSubregIndexByMVT(VecVT, IsHi)); 1448 if (IsHi) 1449 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1450 } 1451 return {SubRegIdx, InsertExtractIdx}; 1452 } 1453 1454 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1455 // stores for those types. 1456 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1457 return !Subtarget.useRVVForFixedLengthVectors() || 1458 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1459 } 1460 1461 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1462 if (ScalarTy->isPointerTy()) 1463 return true; 1464 1465 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1466 ScalarTy->isIntegerTy(32)) 1467 return true; 1468 1469 if (ScalarTy->isIntegerTy(64)) 1470 return Subtarget.hasVInstructionsI64(); 1471 1472 if (ScalarTy->isHalfTy()) 1473 return Subtarget.hasVInstructionsF16(); 1474 if (ScalarTy->isFloatTy()) 1475 return Subtarget.hasVInstructionsF32(); 1476 if (ScalarTy->isDoubleTy()) 1477 return Subtarget.hasVInstructionsF64(); 1478 1479 return false; 1480 } 1481 1482 static SDValue getVLOperand(SDValue Op) { 1483 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1484 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1485 "Unexpected opcode"); 1486 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1487 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1488 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1489 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1490 if (!II) 1491 return SDValue(); 1492 return Op.getOperand(II->VLOperand + 1 + HasChain); 1493 } 1494 1495 static bool useRVVForFixedLengthVectorVT(MVT VT, 1496 const RISCVSubtarget &Subtarget) { 1497 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1498 if (!Subtarget.useRVVForFixedLengthVectors()) 1499 return false; 1500 1501 // We only support a set of vector types with a consistent maximum fixed size 1502 // across all supported vector element types to avoid legalization issues. 1503 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1504 // fixed-length vector type we support is 1024 bytes. 1505 if (VT.getFixedSizeInBits() > 1024 * 8) 1506 return false; 1507 1508 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1509 1510 MVT EltVT = VT.getVectorElementType(); 1511 1512 // Don't use RVV for vectors we cannot scalarize if required. 1513 switch (EltVT.SimpleTy) { 1514 // i1 is supported but has different rules. 1515 default: 1516 return false; 1517 case MVT::i1: 1518 // Masks can only use a single register. 1519 if (VT.getVectorNumElements() > MinVLen) 1520 return false; 1521 MinVLen /= 8; 1522 break; 1523 case MVT::i8: 1524 case MVT::i16: 1525 case MVT::i32: 1526 break; 1527 case MVT::i64: 1528 if (!Subtarget.hasVInstructionsI64()) 1529 return false; 1530 break; 1531 case MVT::f16: 1532 if (!Subtarget.hasVInstructionsF16()) 1533 return false; 1534 break; 1535 case MVT::f32: 1536 if (!Subtarget.hasVInstructionsF32()) 1537 return false; 1538 break; 1539 case MVT::f64: 1540 if (!Subtarget.hasVInstructionsF64()) 1541 return false; 1542 break; 1543 } 1544 1545 // Reject elements larger than ELEN. 1546 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1547 return false; 1548 1549 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1550 // Don't use RVV for types that don't fit. 1551 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1552 return false; 1553 1554 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1555 // the base fixed length RVV support in place. 1556 if (!VT.isPow2VectorType()) 1557 return false; 1558 1559 return true; 1560 } 1561 1562 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1563 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1564 } 1565 1566 // Return the largest legal scalable vector type that matches VT's element type. 1567 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1568 const RISCVSubtarget &Subtarget) { 1569 // This may be called before legal types are setup. 1570 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1571 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1572 "Expected legal fixed length vector!"); 1573 1574 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1575 unsigned MaxELen = Subtarget.getELEN(); 1576 1577 MVT EltVT = VT.getVectorElementType(); 1578 switch (EltVT.SimpleTy) { 1579 default: 1580 llvm_unreachable("unexpected element type for RVV container"); 1581 case MVT::i1: 1582 case MVT::i8: 1583 case MVT::i16: 1584 case MVT::i32: 1585 case MVT::i64: 1586 case MVT::f16: 1587 case MVT::f32: 1588 case MVT::f64: { 1589 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1590 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1591 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1592 unsigned NumElts = 1593 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1594 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1595 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1596 return MVT::getScalableVectorVT(EltVT, NumElts); 1597 } 1598 } 1599 } 1600 1601 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1602 const RISCVSubtarget &Subtarget) { 1603 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1604 Subtarget); 1605 } 1606 1607 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1608 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1609 } 1610 1611 // Grow V to consume an entire RVV register. 1612 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1613 const RISCVSubtarget &Subtarget) { 1614 assert(VT.isScalableVector() && 1615 "Expected to convert into a scalable vector!"); 1616 assert(V.getValueType().isFixedLengthVector() && 1617 "Expected a fixed length vector operand!"); 1618 SDLoc DL(V); 1619 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1620 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1621 } 1622 1623 // Shrink V so it's just big enough to maintain a VT's worth of data. 1624 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1625 const RISCVSubtarget &Subtarget) { 1626 assert(VT.isFixedLengthVector() && 1627 "Expected to convert into a fixed length vector!"); 1628 assert(V.getValueType().isScalableVector() && 1629 "Expected a scalable vector operand!"); 1630 SDLoc DL(V); 1631 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1632 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1633 } 1634 1635 /// Return the type of the mask type suitable for masking the provided 1636 /// vector type. This is simply an i1 element type vector of the same 1637 /// (possibly scalable) length. 1638 static MVT getMaskTypeFor(EVT VecVT) { 1639 assert(VecVT.isVector()); 1640 ElementCount EC = VecVT.getVectorElementCount(); 1641 return MVT::getVectorVT(MVT::i1, EC); 1642 } 1643 1644 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1645 /// vector length VL. . 1646 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1647 SelectionDAG &DAG) { 1648 MVT MaskVT = getMaskTypeFor(VecVT); 1649 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1650 } 1651 1652 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1653 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1654 // the vector type that it is contained in. 1655 static std::pair<SDValue, SDValue> 1656 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1657 const RISCVSubtarget &Subtarget) { 1658 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1659 MVT XLenVT = Subtarget.getXLenVT(); 1660 SDValue VL = VecVT.isFixedLengthVector() 1661 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1662 : DAG.getRegister(RISCV::X0, XLenVT); 1663 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1664 return {Mask, VL}; 1665 } 1666 1667 // As above but assuming the given type is a scalable vector type. 1668 static std::pair<SDValue, SDValue> 1669 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1670 const RISCVSubtarget &Subtarget) { 1671 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1672 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1673 } 1674 1675 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1676 // of either is (currently) supported. This can get us into an infinite loop 1677 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1678 // as a ..., etc. 1679 // Until either (or both) of these can reliably lower any node, reporting that 1680 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1681 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1682 // which is not desirable. 1683 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1684 EVT VT, unsigned DefinedValues) const { 1685 return false; 1686 } 1687 1688 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1689 const RISCVSubtarget &Subtarget) { 1690 // RISCV FP-to-int conversions saturate to the destination register size, but 1691 // don't produce 0 for nan. We can use a conversion instruction and fix the 1692 // nan case with a compare and a select. 1693 SDValue Src = Op.getOperand(0); 1694 1695 EVT DstVT = Op.getValueType(); 1696 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1697 1698 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1699 unsigned Opc; 1700 if (SatVT == DstVT) 1701 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1702 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1703 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1704 else 1705 return SDValue(); 1706 // FIXME: Support other SatVTs by clamping before or after the conversion. 1707 1708 SDLoc DL(Op); 1709 SDValue FpToInt = DAG.getNode( 1710 Opc, DL, DstVT, Src, 1711 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1712 1713 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1714 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1715 } 1716 1717 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1718 // and back. Taking care to avoid converting values that are nan or already 1719 // correct. 1720 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1721 // have FRM dependencies modeled yet. 1722 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1723 MVT VT = Op.getSimpleValueType(); 1724 assert(VT.isVector() && "Unexpected type"); 1725 1726 SDLoc DL(Op); 1727 1728 // Freeze the source since we are increasing the number of uses. 1729 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1730 1731 // Truncate to integer and convert back to FP. 1732 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1733 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1734 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1735 1736 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1737 1738 if (Op.getOpcode() == ISD::FCEIL) { 1739 // If the truncated value is the greater than or equal to the original 1740 // value, we've computed the ceil. Otherwise, we went the wrong way and 1741 // need to increase by 1. 1742 // FIXME: This should use a masked operation. Handle here or in isel? 1743 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1744 DAG.getConstantFP(1.0, DL, VT)); 1745 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1746 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1747 } else if (Op.getOpcode() == ISD::FFLOOR) { 1748 // If the truncated value is the less than or equal to the original value, 1749 // we've computed the floor. Otherwise, we went the wrong way and need to 1750 // decrease by 1. 1751 // FIXME: This should use a masked operation. Handle here or in isel? 1752 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1753 DAG.getConstantFP(1.0, DL, VT)); 1754 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1755 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1756 } 1757 1758 // Restore the original sign so that -0.0 is preserved. 1759 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1760 1761 // Determine the largest integer that can be represented exactly. This and 1762 // values larger than it don't have any fractional bits so don't need to 1763 // be converted. 1764 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1765 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1766 APFloat MaxVal = APFloat(FltSem); 1767 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1768 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1769 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1770 1771 // If abs(Src) was larger than MaxVal or nan, keep it. 1772 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1773 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1774 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1775 } 1776 1777 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1778 // This mode isn't supported in vector hardware on RISCV. But as long as we 1779 // aren't compiling with trapping math, we can emulate this with 1780 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1781 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1782 // dependencies modeled yet. 1783 // FIXME: Use masked operations to avoid final merge. 1784 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1785 MVT VT = Op.getSimpleValueType(); 1786 assert(VT.isVector() && "Unexpected type"); 1787 1788 SDLoc DL(Op); 1789 1790 // Freeze the source since we are increasing the number of uses. 1791 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1792 1793 // We do the conversion on the absolute value and fix the sign at the end. 1794 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1795 1796 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1797 bool Ignored; 1798 APFloat Point5Pred = APFloat(0.5f); 1799 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1800 Point5Pred.next(/*nextDown*/ true); 1801 1802 // Add the adjustment. 1803 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1804 DAG.getConstantFP(Point5Pred, DL, VT)); 1805 1806 // Truncate to integer and convert back to fp. 1807 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1808 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1809 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1810 1811 // Restore the original sign. 1812 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1813 1814 // Determine the largest integer that can be represented exactly. This and 1815 // values larger than it don't have any fractional bits so don't need to 1816 // be converted. 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 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1825 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1826 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1827 } 1828 1829 struct VIDSequence { 1830 int64_t StepNumerator; 1831 unsigned StepDenominator; 1832 int64_t Addend; 1833 }; 1834 1835 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1836 // to the (non-zero) step S and start value X. This can be then lowered as the 1837 // RVV sequence (VID * S) + X, for example. 1838 // The step S is represented as an integer numerator divided by a positive 1839 // denominator. Note that the implementation currently only identifies 1840 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1841 // cannot detect 2/3, for example. 1842 // Note that this method will also match potentially unappealing index 1843 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1844 // determine whether this is worth generating code for. 1845 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1846 unsigned NumElts = Op.getNumOperands(); 1847 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1848 if (!Op.getValueType().isInteger()) 1849 return None; 1850 1851 Optional<unsigned> SeqStepDenom; 1852 Optional<int64_t> SeqStepNum, SeqAddend; 1853 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1854 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1855 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1856 // Assume undef elements match the sequence; we just have to be careful 1857 // when interpolating across them. 1858 if (Op.getOperand(Idx).isUndef()) 1859 continue; 1860 // The BUILD_VECTOR must be all constants. 1861 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1862 return None; 1863 1864 uint64_t Val = Op.getConstantOperandVal(Idx) & 1865 maskTrailingOnes<uint64_t>(EltSizeInBits); 1866 1867 if (PrevElt) { 1868 // Calculate the step since the last non-undef element, and ensure 1869 // it's consistent across the entire sequence. 1870 unsigned IdxDiff = Idx - PrevElt->second; 1871 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1872 1873 // A zero-value value difference means that we're somewhere in the middle 1874 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1875 // step change before evaluating the sequence. 1876 if (ValDiff == 0) 1877 continue; 1878 1879 int64_t Remainder = ValDiff % IdxDiff; 1880 // Normalize the step if it's greater than 1. 1881 if (Remainder != ValDiff) { 1882 // The difference must cleanly divide the element span. 1883 if (Remainder != 0) 1884 return None; 1885 ValDiff /= IdxDiff; 1886 IdxDiff = 1; 1887 } 1888 1889 if (!SeqStepNum) 1890 SeqStepNum = ValDiff; 1891 else if (ValDiff != SeqStepNum) 1892 return None; 1893 1894 if (!SeqStepDenom) 1895 SeqStepDenom = IdxDiff; 1896 else if (IdxDiff != *SeqStepDenom) 1897 return None; 1898 } 1899 1900 // Record this non-undef element for later. 1901 if (!PrevElt || PrevElt->first != Val) 1902 PrevElt = std::make_pair(Val, Idx); 1903 } 1904 1905 // We need to have logged a step for this to count as a legal index sequence. 1906 if (!SeqStepNum || !SeqStepDenom) 1907 return None; 1908 1909 // Loop back through the sequence and validate elements we might have skipped 1910 // while waiting for a valid step. While doing this, log any sequence addend. 1911 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1912 if (Op.getOperand(Idx).isUndef()) 1913 continue; 1914 uint64_t Val = Op.getConstantOperandVal(Idx) & 1915 maskTrailingOnes<uint64_t>(EltSizeInBits); 1916 uint64_t ExpectedVal = 1917 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1918 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1919 if (!SeqAddend) 1920 SeqAddend = Addend; 1921 else if (Addend != SeqAddend) 1922 return None; 1923 } 1924 1925 assert(SeqAddend && "Must have an addend if we have a step"); 1926 1927 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1928 } 1929 1930 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1931 // and lower it as a VRGATHER_VX_VL from the source vector. 1932 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1933 SelectionDAG &DAG, 1934 const RISCVSubtarget &Subtarget) { 1935 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1936 return SDValue(); 1937 SDValue Vec = SplatVal.getOperand(0); 1938 // Only perform this optimization on vectors of the same size for simplicity. 1939 // Don't perform this optimization for i1 vectors. 1940 // FIXME: Support i1 vectors, maybe by promoting to i8? 1941 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 1942 return SDValue(); 1943 SDValue Idx = SplatVal.getOperand(1); 1944 // The index must be a legal type. 1945 if (Idx.getValueType() != Subtarget.getXLenVT()) 1946 return SDValue(); 1947 1948 MVT ContainerVT = VT; 1949 if (VT.isFixedLengthVector()) { 1950 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1951 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1952 } 1953 1954 SDValue Mask, VL; 1955 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1956 1957 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1958 Idx, Mask, VL); 1959 1960 if (!VT.isFixedLengthVector()) 1961 return Gather; 1962 1963 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1964 } 1965 1966 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1967 const RISCVSubtarget &Subtarget) { 1968 MVT VT = Op.getSimpleValueType(); 1969 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1970 1971 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1972 1973 SDLoc DL(Op); 1974 SDValue Mask, VL; 1975 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1976 1977 MVT XLenVT = Subtarget.getXLenVT(); 1978 unsigned NumElts = Op.getNumOperands(); 1979 1980 if (VT.getVectorElementType() == MVT::i1) { 1981 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1982 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1983 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1984 } 1985 1986 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1987 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1988 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1989 } 1990 1991 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1992 // scalar integer chunks whose bit-width depends on the number of mask 1993 // bits and XLEN. 1994 // First, determine the most appropriate scalar integer type to use. This 1995 // is at most XLenVT, but may be shrunk to a smaller vector element type 1996 // according to the size of the final vector - use i8 chunks rather than 1997 // XLenVT if we're producing a v8i1. This results in more consistent 1998 // codegen across RV32 and RV64. 1999 unsigned NumViaIntegerBits = 2000 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2001 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2002 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2003 // If we have to use more than one INSERT_VECTOR_ELT then this 2004 // optimization is likely to increase code size; avoid peforming it in 2005 // such a case. We can use a load from a constant pool in this case. 2006 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2007 return SDValue(); 2008 // Now we can create our integer vector type. Note that it may be larger 2009 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2010 MVT IntegerViaVecVT = 2011 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2012 divideCeil(NumElts, NumViaIntegerBits)); 2013 2014 uint64_t Bits = 0; 2015 unsigned BitPos = 0, IntegerEltIdx = 0; 2016 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2017 2018 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2019 // Once we accumulate enough bits to fill our scalar type, insert into 2020 // our vector and clear our accumulated data. 2021 if (I != 0 && I % NumViaIntegerBits == 0) { 2022 if (NumViaIntegerBits <= 32) 2023 Bits = SignExtend64<32>(Bits); 2024 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2025 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2026 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2027 Bits = 0; 2028 BitPos = 0; 2029 IntegerEltIdx++; 2030 } 2031 SDValue V = Op.getOperand(I); 2032 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2033 Bits |= ((uint64_t)BitValue << BitPos); 2034 } 2035 2036 // Insert the (remaining) scalar value into position in our integer 2037 // vector type. 2038 if (NumViaIntegerBits <= 32) 2039 Bits = SignExtend64<32>(Bits); 2040 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2041 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2042 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2043 2044 if (NumElts < NumViaIntegerBits) { 2045 // If we're producing a smaller vector than our minimum legal integer 2046 // type, bitcast to the equivalent (known-legal) mask type, and extract 2047 // our final mask. 2048 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2049 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2050 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2051 DAG.getConstant(0, DL, XLenVT)); 2052 } else { 2053 // Else we must have produced an integer type with the same size as the 2054 // mask type; bitcast for the final result. 2055 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2056 Vec = DAG.getBitcast(VT, Vec); 2057 } 2058 2059 return Vec; 2060 } 2061 2062 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2063 // vector type, we have a legal equivalently-sized i8 type, so we can use 2064 // that. 2065 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2066 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2067 2068 SDValue WideVec; 2069 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2070 // For a splat, perform a scalar truncate before creating the wider 2071 // vector. 2072 assert(Splat.getValueType() == XLenVT && 2073 "Unexpected type for i1 splat value"); 2074 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2075 DAG.getConstant(1, DL, XLenVT)); 2076 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2077 } else { 2078 SmallVector<SDValue, 8> Ops(Op->op_values()); 2079 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2080 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2081 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2082 } 2083 2084 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2085 } 2086 2087 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2088 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2089 return Gather; 2090 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2091 : RISCVISD::VMV_V_X_VL; 2092 Splat = 2093 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2094 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2095 } 2096 2097 // Try and match index sequences, which we can lower to the vid instruction 2098 // with optional modifications. An all-undef vector is matched by 2099 // getSplatValue, above. 2100 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2101 int64_t StepNumerator = SimpleVID->StepNumerator; 2102 unsigned StepDenominator = SimpleVID->StepDenominator; 2103 int64_t Addend = SimpleVID->Addend; 2104 2105 assert(StepNumerator != 0 && "Invalid step"); 2106 bool Negate = false; 2107 int64_t SplatStepVal = StepNumerator; 2108 unsigned StepOpcode = ISD::MUL; 2109 if (StepNumerator != 1) { 2110 if (isPowerOf2_64(std::abs(StepNumerator))) { 2111 Negate = StepNumerator < 0; 2112 StepOpcode = ISD::SHL; 2113 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2114 } 2115 } 2116 2117 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2118 // threshold since it's the immediate value many RVV instructions accept. 2119 // There is no vmul.vi instruction so ensure multiply constant can fit in 2120 // a single addi instruction. 2121 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2122 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2123 isPowerOf2_32(StepDenominator) && 2124 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2125 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2126 // Convert right out of the scalable type so we can use standard ISD 2127 // nodes for the rest of the computation. If we used scalable types with 2128 // these, we'd lose the fixed-length vector info and generate worse 2129 // vsetvli code. 2130 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2131 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2132 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2133 SDValue SplatStep = DAG.getSplatBuildVector( 2134 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2135 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2136 } 2137 if (StepDenominator != 1) { 2138 SDValue SplatStep = DAG.getSplatBuildVector( 2139 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2140 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2141 } 2142 if (Addend != 0 || Negate) { 2143 SDValue SplatAddend = DAG.getSplatBuildVector( 2144 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2145 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2146 } 2147 return VID; 2148 } 2149 } 2150 2151 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2152 // when re-interpreted as a vector with a larger element type. For example, 2153 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2154 // could be instead splat as 2155 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2156 // TODO: This optimization could also work on non-constant splats, but it 2157 // would require bit-manipulation instructions to construct the splat value. 2158 SmallVector<SDValue> Sequence; 2159 unsigned EltBitSize = VT.getScalarSizeInBits(); 2160 const auto *BV = cast<BuildVectorSDNode>(Op); 2161 if (VT.isInteger() && EltBitSize < 64 && 2162 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2163 BV->getRepeatedSequence(Sequence) && 2164 (Sequence.size() * EltBitSize) <= 64) { 2165 unsigned SeqLen = Sequence.size(); 2166 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2167 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2168 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2169 ViaIntVT == MVT::i64) && 2170 "Unexpected sequence type"); 2171 2172 unsigned EltIdx = 0; 2173 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2174 uint64_t SplatValue = 0; 2175 // Construct the amalgamated value which can be splatted as this larger 2176 // vector type. 2177 for (const auto &SeqV : Sequence) { 2178 if (!SeqV.isUndef()) 2179 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2180 << (EltIdx * EltBitSize)); 2181 EltIdx++; 2182 } 2183 2184 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2185 // achieve better constant materializion. 2186 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2187 SplatValue = SignExtend64<32>(SplatValue); 2188 2189 // Since we can't introduce illegal i64 types at this stage, we can only 2190 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2191 // way we can use RVV instructions to splat. 2192 assert((ViaIntVT.bitsLE(XLenVT) || 2193 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2194 "Unexpected bitcast sequence"); 2195 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2196 SDValue ViaVL = 2197 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2198 MVT ViaContainerVT = 2199 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2200 SDValue Splat = 2201 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2202 DAG.getUNDEF(ViaContainerVT), 2203 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2204 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2205 return DAG.getBitcast(VT, Splat); 2206 } 2207 } 2208 2209 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2210 // which constitute a large proportion of the elements. In such cases we can 2211 // splat a vector with the dominant element and make up the shortfall with 2212 // INSERT_VECTOR_ELTs. 2213 // Note that this includes vectors of 2 elements by association. The 2214 // upper-most element is the "dominant" one, allowing us to use a splat to 2215 // "insert" the upper element, and an insert of the lower element at position 2216 // 0, which improves codegen. 2217 SDValue DominantValue; 2218 unsigned MostCommonCount = 0; 2219 DenseMap<SDValue, unsigned> ValueCounts; 2220 unsigned NumUndefElts = 2221 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2222 2223 // Track the number of scalar loads we know we'd be inserting, estimated as 2224 // any non-zero floating-point constant. Other kinds of element are either 2225 // already in registers or are materialized on demand. The threshold at which 2226 // a vector load is more desirable than several scalar materializion and 2227 // vector-insertion instructions is not known. 2228 unsigned NumScalarLoads = 0; 2229 2230 for (SDValue V : Op->op_values()) { 2231 if (V.isUndef()) 2232 continue; 2233 2234 ValueCounts.insert(std::make_pair(V, 0)); 2235 unsigned &Count = ValueCounts[V]; 2236 2237 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2238 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2239 2240 // Is this value dominant? In case of a tie, prefer the highest element as 2241 // it's cheaper to insert near the beginning of a vector than it is at the 2242 // end. 2243 if (++Count >= MostCommonCount) { 2244 DominantValue = V; 2245 MostCommonCount = Count; 2246 } 2247 } 2248 2249 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2250 unsigned NumDefElts = NumElts - NumUndefElts; 2251 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2252 2253 // Don't perform this optimization when optimizing for size, since 2254 // materializing elements and inserting them tends to cause code bloat. 2255 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2256 ((MostCommonCount > DominantValueCountThreshold) || 2257 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2258 // Start by splatting the most common element. 2259 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2260 2261 DenseSet<SDValue> Processed{DominantValue}; 2262 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2263 for (const auto &OpIdx : enumerate(Op->ops())) { 2264 const SDValue &V = OpIdx.value(); 2265 if (V.isUndef() || !Processed.insert(V).second) 2266 continue; 2267 if (ValueCounts[V] == 1) { 2268 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2269 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2270 } else { 2271 // Blend in all instances of this value using a VSELECT, using a 2272 // mask where each bit signals whether that element is the one 2273 // we're after. 2274 SmallVector<SDValue> Ops; 2275 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2276 return DAG.getConstant(V == V1, DL, XLenVT); 2277 }); 2278 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2279 DAG.getBuildVector(SelMaskTy, DL, Ops), 2280 DAG.getSplatBuildVector(VT, DL, V), Vec); 2281 } 2282 } 2283 2284 return Vec; 2285 } 2286 2287 return SDValue(); 2288 } 2289 2290 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2291 SDValue Lo, SDValue Hi, SDValue VL, 2292 SelectionDAG &DAG) { 2293 if (!Passthru) 2294 Passthru = DAG.getUNDEF(VT); 2295 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2296 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2297 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2298 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2299 // node in order to try and match RVV vector/scalar instructions. 2300 if ((LoC >> 31) == HiC) 2301 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2302 2303 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2304 // vmv.v.x whose EEW = 32 to lower it. 2305 auto *Const = dyn_cast<ConstantSDNode>(VL); 2306 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2307 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2308 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2309 // access the subtarget here now. 2310 auto InterVec = DAG.getNode( 2311 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2312 DAG.getRegister(RISCV::X0, MVT::i32)); 2313 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2314 } 2315 } 2316 2317 // Fall back to a stack store and stride x0 vector load. 2318 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2319 Hi, VL); 2320 } 2321 2322 // Called by type legalization to handle splat of i64 on RV32. 2323 // FIXME: We can optimize this when the type has sign or zero bits in one 2324 // of the halves. 2325 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2326 SDValue Scalar, SDValue VL, 2327 SelectionDAG &DAG) { 2328 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2329 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2330 DAG.getConstant(0, DL, MVT::i32)); 2331 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2332 DAG.getConstant(1, DL, MVT::i32)); 2333 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2334 } 2335 2336 // This function lowers a splat of a scalar operand Splat with the vector 2337 // length VL. It ensures the final sequence is type legal, which is useful when 2338 // lowering a splat after type legalization. 2339 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2340 MVT VT, SDLoc DL, SelectionDAG &DAG, 2341 const RISCVSubtarget &Subtarget) { 2342 bool HasPassthru = Passthru && !Passthru.isUndef(); 2343 if (!HasPassthru && !Passthru) 2344 Passthru = DAG.getUNDEF(VT); 2345 if (VT.isFloatingPoint()) { 2346 // If VL is 1, we could use vfmv.s.f. 2347 if (isOneConstant(VL)) 2348 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2349 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2350 } 2351 2352 MVT XLenVT = Subtarget.getXLenVT(); 2353 2354 // Simplest case is that the operand needs to be promoted to XLenVT. 2355 if (Scalar.getValueType().bitsLE(XLenVT)) { 2356 // If the operand is a constant, sign extend to increase our chances 2357 // of being able to use a .vi instruction. ANY_EXTEND would become a 2358 // a zero extend and the simm5 check in isel would fail. 2359 // FIXME: Should we ignore the upper bits in isel instead? 2360 unsigned ExtOpc = 2361 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2362 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2363 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2364 // If VL is 1 and the scalar value won't benefit from immediate, we could 2365 // use vmv.s.x. 2366 if (isOneConstant(VL) && 2367 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2368 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2369 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2370 } 2371 2372 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2373 "Unexpected scalar for splat lowering!"); 2374 2375 if (isOneConstant(VL) && isNullConstant(Scalar)) 2376 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2377 DAG.getConstant(0, DL, XLenVT), VL); 2378 2379 // Otherwise use the more complicated splatting algorithm. 2380 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2381 } 2382 2383 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2384 const RISCVSubtarget &Subtarget) { 2385 // We need to be able to widen elements to the next larger integer type. 2386 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2387 return false; 2388 2389 int Size = Mask.size(); 2390 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2391 2392 int Srcs[] = {-1, -1}; 2393 for (int i = 0; i != Size; ++i) { 2394 // Ignore undef elements. 2395 if (Mask[i] < 0) 2396 continue; 2397 2398 // Is this an even or odd element. 2399 int Pol = i % 2; 2400 2401 // Ensure we consistently use the same source for this element polarity. 2402 int Src = Mask[i] / Size; 2403 if (Srcs[Pol] < 0) 2404 Srcs[Pol] = Src; 2405 if (Srcs[Pol] != Src) 2406 return false; 2407 2408 // Make sure the element within the source is appropriate for this element 2409 // in the destination. 2410 int Elt = Mask[i] % Size; 2411 if (Elt != i / 2) 2412 return false; 2413 } 2414 2415 // We need to find a source for each polarity and they can't be the same. 2416 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2417 return false; 2418 2419 // Swap the sources if the second source was in the even polarity. 2420 SwapSources = Srcs[0] > Srcs[1]; 2421 2422 return true; 2423 } 2424 2425 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2426 /// and then extract the original number of elements from the rotated result. 2427 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2428 /// returned rotation amount is for a rotate right, where elements move from 2429 /// higher elements to lower elements. \p LoSrc indicates the first source 2430 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2431 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2432 /// 0 or 1 if a rotation is found. 2433 /// 2434 /// NOTE: We talk about rotate to the right which matches how bit shift and 2435 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2436 /// and the table below write vectors with the lowest elements on the left. 2437 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2438 int Size = Mask.size(); 2439 2440 // We need to detect various ways of spelling a rotation: 2441 // [11, 12, 13, 14, 15, 0, 1, 2] 2442 // [-1, 12, 13, 14, -1, -1, 1, -1] 2443 // [-1, -1, -1, -1, -1, -1, 1, 2] 2444 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2445 // [-1, 4, 5, 6, -1, -1, 9, -1] 2446 // [-1, 4, 5, 6, -1, -1, -1, -1] 2447 int Rotation = 0; 2448 LoSrc = -1; 2449 HiSrc = -1; 2450 for (int i = 0; i != Size; ++i) { 2451 int M = Mask[i]; 2452 if (M < 0) 2453 continue; 2454 2455 // Determine where a rotate vector would have started. 2456 int StartIdx = i - (M % Size); 2457 // The identity rotation isn't interesting, stop. 2458 if (StartIdx == 0) 2459 return -1; 2460 2461 // If we found the tail of a vector the rotation must be the missing 2462 // front. If we found the head of a vector, it must be how much of the 2463 // head. 2464 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2465 2466 if (Rotation == 0) 2467 Rotation = CandidateRotation; 2468 else if (Rotation != CandidateRotation) 2469 // The rotations don't match, so we can't match this mask. 2470 return -1; 2471 2472 // Compute which value this mask is pointing at. 2473 int MaskSrc = M < Size ? 0 : 1; 2474 2475 // Compute which of the two target values this index should be assigned to. 2476 // This reflects whether the high elements are remaining or the low elemnts 2477 // are remaining. 2478 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2479 2480 // Either set up this value if we've not encountered it before, or check 2481 // that it remains consistent. 2482 if (TargetSrc < 0) 2483 TargetSrc = MaskSrc; 2484 else if (TargetSrc != MaskSrc) 2485 // This may be a rotation, but it pulls from the inputs in some 2486 // unsupported interleaving. 2487 return -1; 2488 } 2489 2490 // Check that we successfully analyzed the mask, and normalize the results. 2491 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2492 assert((LoSrc >= 0 || HiSrc >= 0) && 2493 "Failed to find a rotated input vector!"); 2494 2495 return Rotation; 2496 } 2497 2498 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2499 const RISCVSubtarget &Subtarget) { 2500 SDValue V1 = Op.getOperand(0); 2501 SDValue V2 = Op.getOperand(1); 2502 SDLoc DL(Op); 2503 MVT XLenVT = Subtarget.getXLenVT(); 2504 MVT VT = Op.getSimpleValueType(); 2505 unsigned NumElts = VT.getVectorNumElements(); 2506 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2507 2508 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2509 2510 SDValue TrueMask, VL; 2511 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2512 2513 if (SVN->isSplat()) { 2514 const int Lane = SVN->getSplatIndex(); 2515 if (Lane >= 0) { 2516 MVT SVT = VT.getVectorElementType(); 2517 2518 // Turn splatted vector load into a strided load with an X0 stride. 2519 SDValue V = V1; 2520 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2521 // with undef. 2522 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2523 int Offset = Lane; 2524 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2525 int OpElements = 2526 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2527 V = V.getOperand(Offset / OpElements); 2528 Offset %= OpElements; 2529 } 2530 2531 // We need to ensure the load isn't atomic or volatile. 2532 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2533 auto *Ld = cast<LoadSDNode>(V); 2534 Offset *= SVT.getStoreSize(); 2535 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2536 TypeSize::Fixed(Offset), DL); 2537 2538 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2539 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2540 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2541 SDValue IntID = 2542 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2543 SDValue Ops[] = {Ld->getChain(), 2544 IntID, 2545 DAG.getUNDEF(ContainerVT), 2546 NewAddr, 2547 DAG.getRegister(RISCV::X0, XLenVT), 2548 VL}; 2549 SDValue NewLoad = DAG.getMemIntrinsicNode( 2550 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2551 DAG.getMachineFunction().getMachineMemOperand( 2552 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2553 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2554 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2555 } 2556 2557 // Otherwise use a scalar load and splat. This will give the best 2558 // opportunity to fold a splat into the operation. ISel can turn it into 2559 // the x0 strided load if we aren't able to fold away the select. 2560 if (SVT.isFloatingPoint()) 2561 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2562 Ld->getPointerInfo().getWithOffset(Offset), 2563 Ld->getOriginalAlign(), 2564 Ld->getMemOperand()->getFlags()); 2565 else 2566 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2567 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2568 Ld->getOriginalAlign(), 2569 Ld->getMemOperand()->getFlags()); 2570 DAG.makeEquivalentMemoryOrdering(Ld, V); 2571 2572 unsigned Opc = 2573 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2574 SDValue Splat = 2575 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2576 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2577 } 2578 2579 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2580 assert(Lane < (int)NumElts && "Unexpected lane!"); 2581 SDValue Gather = 2582 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2583 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2584 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2585 } 2586 } 2587 2588 ArrayRef<int> Mask = SVN->getMask(); 2589 2590 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2591 // be undef which can be handled with a single SLIDEDOWN/UP. 2592 int LoSrc, HiSrc; 2593 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2594 if (Rotation > 0) { 2595 SDValue LoV, HiV; 2596 if (LoSrc >= 0) { 2597 LoV = LoSrc == 0 ? V1 : V2; 2598 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2599 } 2600 if (HiSrc >= 0) { 2601 HiV = HiSrc == 0 ? V1 : V2; 2602 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2603 } 2604 2605 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2606 // to slide LoV up by (NumElts - Rotation). 2607 unsigned InvRotate = NumElts - Rotation; 2608 2609 SDValue Res = DAG.getUNDEF(ContainerVT); 2610 if (HiV) { 2611 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2612 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2613 // causes multiple vsetvlis in some test cases such as lowering 2614 // reduce.mul 2615 SDValue DownVL = VL; 2616 if (LoV) 2617 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2618 Res = 2619 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2620 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2621 } 2622 if (LoV) 2623 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2624 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2625 2626 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2627 } 2628 2629 // Detect an interleave shuffle and lower to 2630 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2631 bool SwapSources; 2632 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2633 // Swap sources if needed. 2634 if (SwapSources) 2635 std::swap(V1, V2); 2636 2637 // Extract the lower half of the vectors. 2638 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2639 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2640 DAG.getConstant(0, DL, XLenVT)); 2641 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2642 DAG.getConstant(0, DL, XLenVT)); 2643 2644 // Double the element width and halve the number of elements in an int type. 2645 unsigned EltBits = VT.getScalarSizeInBits(); 2646 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2647 MVT WideIntVT = 2648 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2649 // Convert this to a scalable vector. We need to base this on the 2650 // destination size to ensure there's always a type with a smaller LMUL. 2651 MVT WideIntContainerVT = 2652 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2653 2654 // Convert sources to scalable vectors with the same element count as the 2655 // larger type. 2656 MVT HalfContainerVT = MVT::getVectorVT( 2657 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2658 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2659 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2660 2661 // Cast sources to integer. 2662 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2663 MVT IntHalfVT = 2664 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2665 V1 = DAG.getBitcast(IntHalfVT, V1); 2666 V2 = DAG.getBitcast(IntHalfVT, V2); 2667 2668 // Freeze V2 since we use it twice and we need to be sure that the add and 2669 // multiply see the same value. 2670 V2 = DAG.getFreeze(V2); 2671 2672 // Recreate TrueMask using the widened type's element count. 2673 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2674 2675 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2676 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2677 V2, TrueMask, VL); 2678 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2679 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2680 DAG.getUNDEF(IntHalfVT), 2681 DAG.getAllOnesConstant(DL, XLenVT)); 2682 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2683 V2, Multiplier, TrueMask, VL); 2684 // Add the new copies to our previous addition giving us 2^eltbits copies of 2685 // V2. This is equivalent to shifting V2 left by eltbits. This should 2686 // combine with the vwmulu.vv above to form vwmaccu.vv. 2687 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2688 TrueMask, VL); 2689 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2690 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2691 // vector VT. 2692 ContainerVT = 2693 MVT::getVectorVT(VT.getVectorElementType(), 2694 WideIntContainerVT.getVectorElementCount() * 2); 2695 Add = DAG.getBitcast(ContainerVT, Add); 2696 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2697 } 2698 2699 // Detect shuffles which can be re-expressed as vector selects; these are 2700 // shuffles in which each element in the destination is taken from an element 2701 // at the corresponding index in either source vectors. 2702 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2703 int MaskIndex = MaskIdx.value(); 2704 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2705 }); 2706 2707 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2708 2709 SmallVector<SDValue> MaskVals; 2710 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2711 // merged with a second vrgather. 2712 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2713 2714 // By default we preserve the original operand order, and use a mask to 2715 // select LHS as true and RHS as false. However, since RVV vector selects may 2716 // feature splats but only on the LHS, we may choose to invert our mask and 2717 // instead select between RHS and LHS. 2718 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2719 bool InvertMask = IsSelect == SwapOps; 2720 2721 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2722 // half. 2723 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2724 2725 // Now construct the mask that will be used by the vselect or blended 2726 // vrgather operation. For vrgathers, construct the appropriate indices into 2727 // each vector. 2728 for (int MaskIndex : Mask) { 2729 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2730 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2731 if (!IsSelect) { 2732 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2733 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2734 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2735 : DAG.getUNDEF(XLenVT)); 2736 GatherIndicesRHS.push_back( 2737 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2738 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2739 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2740 ++LHSIndexCounts[MaskIndex]; 2741 if (!IsLHSOrUndefIndex) 2742 ++RHSIndexCounts[MaskIndex - NumElts]; 2743 } 2744 } 2745 2746 if (SwapOps) { 2747 std::swap(V1, V2); 2748 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2749 } 2750 2751 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2752 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2753 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2754 2755 if (IsSelect) 2756 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2757 2758 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2759 // On such a large vector we're unable to use i8 as the index type. 2760 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2761 // may involve vector splitting if we're already at LMUL=8, or our 2762 // user-supplied maximum fixed-length LMUL. 2763 return SDValue(); 2764 } 2765 2766 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2767 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2768 MVT IndexVT = VT.changeTypeToInteger(); 2769 // Since we can't introduce illegal index types at this stage, use i16 and 2770 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2771 // than XLenVT. 2772 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2773 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2774 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2775 } 2776 2777 MVT IndexContainerVT = 2778 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2779 2780 SDValue Gather; 2781 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2782 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2783 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2784 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2785 Subtarget); 2786 } else { 2787 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2788 // If only one index is used, we can use a "splat" vrgather. 2789 // TODO: We can splat the most-common index and fix-up any stragglers, if 2790 // that's beneficial. 2791 if (LHSIndexCounts.size() == 1) { 2792 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2793 Gather = 2794 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2795 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2796 } else { 2797 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2798 LHSIndices = 2799 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2800 2801 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2802 TrueMask, VL); 2803 } 2804 } 2805 2806 // If a second vector operand is used by this shuffle, blend it in with an 2807 // additional vrgather. 2808 if (!V2.isUndef()) { 2809 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2810 // If only one index is used, we can use a "splat" vrgather. 2811 // TODO: We can splat the most-common index and fix-up any stragglers, if 2812 // that's beneficial. 2813 if (RHSIndexCounts.size() == 1) { 2814 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2815 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2816 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2817 } else { 2818 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2819 RHSIndices = 2820 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2821 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2822 VL); 2823 } 2824 2825 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2826 SelectMask = 2827 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2828 2829 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2830 Gather, VL); 2831 } 2832 2833 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2834 } 2835 2836 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2837 // Support splats for any type. These should type legalize well. 2838 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2839 return true; 2840 2841 // Only support legal VTs for other shuffles for now. 2842 if (!isTypeLegal(VT)) 2843 return false; 2844 2845 MVT SVT = VT.getSimpleVT(); 2846 2847 bool SwapSources; 2848 int LoSrc, HiSrc; 2849 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2850 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2851 } 2852 2853 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2854 // the exponent. 2855 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2856 MVT VT = Op.getSimpleValueType(); 2857 unsigned EltSize = VT.getScalarSizeInBits(); 2858 SDValue Src = Op.getOperand(0); 2859 SDLoc DL(Op); 2860 2861 // We need a FP type that can represent the value. 2862 // TODO: Use f16 for i8 when possible? 2863 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2864 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2865 2866 // Legal types should have been checked in the RISCVTargetLowering 2867 // constructor. 2868 // TODO: Splitting may make sense in some cases. 2869 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2870 "Expected legal float type!"); 2871 2872 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2873 // The trailing zero count is equal to log2 of this single bit value. 2874 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2875 SDValue Neg = 2876 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2877 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2878 } 2879 2880 // We have a legal FP type, convert to it. 2881 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2882 // Bitcast to integer and shift the exponent to the LSB. 2883 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2884 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2885 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2886 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2887 DAG.getConstant(ShiftAmt, DL, IntVT)); 2888 // Truncate back to original type to allow vnsrl. 2889 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2890 // The exponent contains log2 of the value in biased form. 2891 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2892 2893 // For trailing zeros, we just need to subtract the bias. 2894 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2895 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2896 DAG.getConstant(ExponentBias, DL, VT)); 2897 2898 // For leading zeros, we need to remove the bias and convert from log2 to 2899 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2900 unsigned Adjust = ExponentBias + (EltSize - 1); 2901 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2902 } 2903 2904 // While RVV has alignment restrictions, we should always be able to load as a 2905 // legal equivalently-sized byte-typed vector instead. This method is 2906 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2907 // the load is already correctly-aligned, it returns SDValue(). 2908 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2909 SelectionDAG &DAG) const { 2910 auto *Load = cast<LoadSDNode>(Op); 2911 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2912 2913 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2914 Load->getMemoryVT(), 2915 *Load->getMemOperand())) 2916 return SDValue(); 2917 2918 SDLoc DL(Op); 2919 MVT VT = Op.getSimpleValueType(); 2920 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2921 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2922 "Unexpected unaligned RVV load type"); 2923 MVT NewVT = 2924 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2925 assert(NewVT.isValid() && 2926 "Expecting equally-sized RVV vector types to be legal"); 2927 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2928 Load->getPointerInfo(), Load->getOriginalAlign(), 2929 Load->getMemOperand()->getFlags()); 2930 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2931 } 2932 2933 // While RVV has alignment restrictions, we should always be able to store as a 2934 // legal equivalently-sized byte-typed vector instead. This method is 2935 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2936 // returns SDValue() if the store is already correctly aligned. 2937 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2938 SelectionDAG &DAG) const { 2939 auto *Store = cast<StoreSDNode>(Op); 2940 assert(Store && Store->getValue().getValueType().isVector() && 2941 "Expected vector store"); 2942 2943 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2944 Store->getMemoryVT(), 2945 *Store->getMemOperand())) 2946 return SDValue(); 2947 2948 SDLoc DL(Op); 2949 SDValue StoredVal = Store->getValue(); 2950 MVT VT = StoredVal.getSimpleValueType(); 2951 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2952 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2953 "Unexpected unaligned RVV store type"); 2954 MVT NewVT = 2955 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2956 assert(NewVT.isValid() && 2957 "Expecting equally-sized RVV vector types to be legal"); 2958 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2959 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2960 Store->getPointerInfo(), Store->getOriginalAlign(), 2961 Store->getMemOperand()->getFlags()); 2962 } 2963 2964 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 2965 const RISCVSubtarget &Subtarget) { 2966 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 2967 2968 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 2969 2970 // All simm32 constants should be handled by isel. 2971 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 2972 // this check redundant, but small immediates are common so this check 2973 // should have better compile time. 2974 if (isInt<32>(Imm)) 2975 return Op; 2976 2977 // We only need to cost the immediate, if constant pool lowering is enabled. 2978 if (!Subtarget.useConstantPoolForLargeInts()) 2979 return Op; 2980 2981 RISCVMatInt::InstSeq Seq = 2982 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 2983 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 2984 return Op; 2985 2986 // Expand to a constant pool using the default expansion code. 2987 return SDValue(); 2988 } 2989 2990 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2991 SelectionDAG &DAG) const { 2992 switch (Op.getOpcode()) { 2993 default: 2994 report_fatal_error("unimplemented operand"); 2995 case ISD::GlobalAddress: 2996 return lowerGlobalAddress(Op, DAG); 2997 case ISD::BlockAddress: 2998 return lowerBlockAddress(Op, DAG); 2999 case ISD::ConstantPool: 3000 return lowerConstantPool(Op, DAG); 3001 case ISD::JumpTable: 3002 return lowerJumpTable(Op, DAG); 3003 case ISD::GlobalTLSAddress: 3004 return lowerGlobalTLSAddress(Op, DAG); 3005 case ISD::Constant: 3006 return lowerConstant(Op, DAG, Subtarget); 3007 case ISD::SELECT: 3008 return lowerSELECT(Op, DAG); 3009 case ISD::BRCOND: 3010 return lowerBRCOND(Op, DAG); 3011 case ISD::VASTART: 3012 return lowerVASTART(Op, DAG); 3013 case ISD::FRAMEADDR: 3014 return lowerFRAMEADDR(Op, DAG); 3015 case ISD::RETURNADDR: 3016 return lowerRETURNADDR(Op, DAG); 3017 case ISD::SHL_PARTS: 3018 return lowerShiftLeftParts(Op, DAG); 3019 case ISD::SRA_PARTS: 3020 return lowerShiftRightParts(Op, DAG, true); 3021 case ISD::SRL_PARTS: 3022 return lowerShiftRightParts(Op, DAG, false); 3023 case ISD::BITCAST: { 3024 SDLoc DL(Op); 3025 EVT VT = Op.getValueType(); 3026 SDValue Op0 = Op.getOperand(0); 3027 EVT Op0VT = Op0.getValueType(); 3028 MVT XLenVT = Subtarget.getXLenVT(); 3029 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3030 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3031 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3032 return FPConv; 3033 } 3034 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3035 Subtarget.hasStdExtF()) { 3036 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3037 SDValue FPConv = 3038 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3039 return FPConv; 3040 } 3041 3042 // Consider other scalar<->scalar casts as legal if the types are legal. 3043 // Otherwise expand them. 3044 if (!VT.isVector() && !Op0VT.isVector()) { 3045 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3046 return Op; 3047 return SDValue(); 3048 } 3049 3050 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3051 "Unexpected types"); 3052 3053 if (VT.isFixedLengthVector()) { 3054 // We can handle fixed length vector bitcasts with a simple replacement 3055 // in isel. 3056 if (Op0VT.isFixedLengthVector()) 3057 return Op; 3058 // When bitcasting from scalar to fixed-length vector, insert the scalar 3059 // into a one-element vector of the result type, and perform a vector 3060 // bitcast. 3061 if (!Op0VT.isVector()) { 3062 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3063 if (!isTypeLegal(BVT)) 3064 return SDValue(); 3065 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3066 DAG.getUNDEF(BVT), Op0, 3067 DAG.getConstant(0, DL, XLenVT))); 3068 } 3069 return SDValue(); 3070 } 3071 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3072 // thus: bitcast the vector to a one-element vector type whose element type 3073 // is the same as the result type, and extract the first element. 3074 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3075 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3076 if (!isTypeLegal(BVT)) 3077 return SDValue(); 3078 SDValue BVec = DAG.getBitcast(BVT, Op0); 3079 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3080 DAG.getConstant(0, DL, XLenVT)); 3081 } 3082 return SDValue(); 3083 } 3084 case ISD::INTRINSIC_WO_CHAIN: 3085 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3086 case ISD::INTRINSIC_W_CHAIN: 3087 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3088 case ISD::INTRINSIC_VOID: 3089 return LowerINTRINSIC_VOID(Op, DAG); 3090 case ISD::BSWAP: 3091 case ISD::BITREVERSE: { 3092 MVT VT = Op.getSimpleValueType(); 3093 SDLoc DL(Op); 3094 if (Subtarget.hasStdExtZbp()) { 3095 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3096 // Start with the maximum immediate value which is the bitwidth - 1. 3097 unsigned Imm = VT.getSizeInBits() - 1; 3098 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3099 if (Op.getOpcode() == ISD::BSWAP) 3100 Imm &= ~0x7U; 3101 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3102 DAG.getConstant(Imm, DL, VT)); 3103 } 3104 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3105 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3106 // Expand bitreverse to a bswap(rev8) followed by brev8. 3107 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3108 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3109 // as brev8 by an isel pattern. 3110 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3111 DAG.getConstant(7, DL, VT)); 3112 } 3113 case ISD::FSHL: 3114 case ISD::FSHR: { 3115 MVT VT = Op.getSimpleValueType(); 3116 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3117 SDLoc DL(Op); 3118 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3119 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3120 // accidentally setting the extra bit. 3121 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3122 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3123 DAG.getConstant(ShAmtWidth, DL, VT)); 3124 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3125 // instruction use different orders. fshl will return its first operand for 3126 // shift of zero, fshr will return its second operand. fsl and fsr both 3127 // return rs1 so the ISD nodes need to have different operand orders. 3128 // Shift amount is in rs2. 3129 SDValue Op0 = Op.getOperand(0); 3130 SDValue Op1 = Op.getOperand(1); 3131 unsigned Opc = RISCVISD::FSL; 3132 if (Op.getOpcode() == ISD::FSHR) { 3133 std::swap(Op0, Op1); 3134 Opc = RISCVISD::FSR; 3135 } 3136 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3137 } 3138 case ISD::TRUNCATE: 3139 // Only custom-lower vector truncates 3140 if (!Op.getSimpleValueType().isVector()) 3141 return Op; 3142 return lowerVectorTruncLike(Op, DAG); 3143 case ISD::ANY_EXTEND: 3144 case ISD::ZERO_EXTEND: 3145 if (Op.getOperand(0).getValueType().isVector() && 3146 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3147 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3148 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3149 case ISD::SIGN_EXTEND: 3150 if (Op.getOperand(0).getValueType().isVector() && 3151 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3152 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3153 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3154 case ISD::SPLAT_VECTOR_PARTS: 3155 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3156 case ISD::INSERT_VECTOR_ELT: 3157 return lowerINSERT_VECTOR_ELT(Op, DAG); 3158 case ISD::EXTRACT_VECTOR_ELT: 3159 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3160 case ISD::VSCALE: { 3161 MVT VT = Op.getSimpleValueType(); 3162 SDLoc DL(Op); 3163 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3164 // We define our scalable vector types for lmul=1 to use a 64 bit known 3165 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3166 // vscale as VLENB / 8. 3167 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3168 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3169 report_fatal_error("Support for VLEN==32 is incomplete."); 3170 // We assume VLENB is a multiple of 8. We manually choose the best shift 3171 // here because SimplifyDemandedBits isn't always able to simplify it. 3172 uint64_t Val = Op.getConstantOperandVal(0); 3173 if (isPowerOf2_64(Val)) { 3174 uint64_t Log2 = Log2_64(Val); 3175 if (Log2 < 3) 3176 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3177 DAG.getConstant(3 - Log2, DL, VT)); 3178 if (Log2 > 3) 3179 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3180 DAG.getConstant(Log2 - 3, DL, VT)); 3181 return VLENB; 3182 } 3183 // If the multiplier is a multiple of 8, scale it down to avoid needing 3184 // to shift the VLENB value. 3185 if ((Val % 8) == 0) 3186 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3187 DAG.getConstant(Val / 8, DL, VT)); 3188 3189 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3190 DAG.getConstant(3, DL, VT)); 3191 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3192 } 3193 case ISD::FPOWI: { 3194 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3195 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3196 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3197 Op.getOperand(1).getValueType() == MVT::i32) { 3198 SDLoc DL(Op); 3199 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3200 SDValue Powi = 3201 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3202 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3203 DAG.getIntPtrConstant(0, DL)); 3204 } 3205 return SDValue(); 3206 } 3207 case ISD::FP_EXTEND: 3208 case ISD::FP_ROUND: 3209 if (!Op.getValueType().isVector()) 3210 return Op; 3211 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3212 case ISD::FP_TO_SINT: 3213 case ISD::FP_TO_UINT: 3214 case ISD::SINT_TO_FP: 3215 case ISD::UINT_TO_FP: { 3216 // RVV can only do fp<->int conversions to types half/double the size as 3217 // the source. We custom-lower any conversions that do two hops into 3218 // sequences. 3219 MVT VT = Op.getSimpleValueType(); 3220 if (!VT.isVector()) 3221 return Op; 3222 SDLoc DL(Op); 3223 SDValue Src = Op.getOperand(0); 3224 MVT EltVT = VT.getVectorElementType(); 3225 MVT SrcVT = Src.getSimpleValueType(); 3226 MVT SrcEltVT = SrcVT.getVectorElementType(); 3227 unsigned EltSize = EltVT.getSizeInBits(); 3228 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3229 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3230 "Unexpected vector element types"); 3231 3232 bool IsInt2FP = SrcEltVT.isInteger(); 3233 // Widening conversions 3234 if (EltSize > (2 * SrcEltSize)) { 3235 if (IsInt2FP) { 3236 // Do a regular integer sign/zero extension then convert to float. 3237 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3238 VT.getVectorElementCount()); 3239 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3240 ? ISD::ZERO_EXTEND 3241 : ISD::SIGN_EXTEND; 3242 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3243 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3244 } 3245 // FP2Int 3246 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3247 // Do one doubling fp_extend then complete the operation by converting 3248 // to int. 3249 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3250 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3251 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3252 } 3253 3254 // Narrowing conversions 3255 if (SrcEltSize > (2 * EltSize)) { 3256 if (IsInt2FP) { 3257 // One narrowing int_to_fp, then an fp_round. 3258 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3259 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3260 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3261 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3262 } 3263 // FP2Int 3264 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3265 // representable by the integer, the result is poison. 3266 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3267 VT.getVectorElementCount()); 3268 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3269 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3270 } 3271 3272 // Scalable vectors can exit here. Patterns will handle equally-sized 3273 // conversions halving/doubling ones. 3274 if (!VT.isFixedLengthVector()) 3275 return Op; 3276 3277 // For fixed-length vectors we lower to a custom "VL" node. 3278 unsigned RVVOpc = 0; 3279 switch (Op.getOpcode()) { 3280 default: 3281 llvm_unreachable("Impossible opcode"); 3282 case ISD::FP_TO_SINT: 3283 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3284 break; 3285 case ISD::FP_TO_UINT: 3286 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3287 break; 3288 case ISD::SINT_TO_FP: 3289 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3290 break; 3291 case ISD::UINT_TO_FP: 3292 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3293 break; 3294 } 3295 3296 MVT ContainerVT, SrcContainerVT; 3297 // Derive the reference container type from the larger vector type. 3298 if (SrcEltSize > EltSize) { 3299 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3300 ContainerVT = 3301 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3302 } else { 3303 ContainerVT = getContainerForFixedLengthVector(VT); 3304 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3305 } 3306 3307 SDValue Mask, VL; 3308 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3309 3310 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3311 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3312 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3313 } 3314 case ISD::FP_TO_SINT_SAT: 3315 case ISD::FP_TO_UINT_SAT: 3316 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3317 case ISD::FTRUNC: 3318 case ISD::FCEIL: 3319 case ISD::FFLOOR: 3320 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3321 case ISD::FROUND: 3322 return lowerFROUND(Op, DAG); 3323 case ISD::VECREDUCE_ADD: 3324 case ISD::VECREDUCE_UMAX: 3325 case ISD::VECREDUCE_SMAX: 3326 case ISD::VECREDUCE_UMIN: 3327 case ISD::VECREDUCE_SMIN: 3328 return lowerVECREDUCE(Op, DAG); 3329 case ISD::VECREDUCE_AND: 3330 case ISD::VECREDUCE_OR: 3331 case ISD::VECREDUCE_XOR: 3332 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3333 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3334 return lowerVECREDUCE(Op, DAG); 3335 case ISD::VECREDUCE_FADD: 3336 case ISD::VECREDUCE_SEQ_FADD: 3337 case ISD::VECREDUCE_FMIN: 3338 case ISD::VECREDUCE_FMAX: 3339 return lowerFPVECREDUCE(Op, DAG); 3340 case ISD::VP_REDUCE_ADD: 3341 case ISD::VP_REDUCE_UMAX: 3342 case ISD::VP_REDUCE_SMAX: 3343 case ISD::VP_REDUCE_UMIN: 3344 case ISD::VP_REDUCE_SMIN: 3345 case ISD::VP_REDUCE_FADD: 3346 case ISD::VP_REDUCE_SEQ_FADD: 3347 case ISD::VP_REDUCE_FMIN: 3348 case ISD::VP_REDUCE_FMAX: 3349 return lowerVPREDUCE(Op, DAG); 3350 case ISD::VP_REDUCE_AND: 3351 case ISD::VP_REDUCE_OR: 3352 case ISD::VP_REDUCE_XOR: 3353 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3354 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3355 return lowerVPREDUCE(Op, DAG); 3356 case ISD::INSERT_SUBVECTOR: 3357 return lowerINSERT_SUBVECTOR(Op, DAG); 3358 case ISD::EXTRACT_SUBVECTOR: 3359 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3360 case ISD::STEP_VECTOR: 3361 return lowerSTEP_VECTOR(Op, DAG); 3362 case ISD::VECTOR_REVERSE: 3363 return lowerVECTOR_REVERSE(Op, DAG); 3364 case ISD::VECTOR_SPLICE: 3365 return lowerVECTOR_SPLICE(Op, DAG); 3366 case ISD::BUILD_VECTOR: 3367 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3368 case ISD::SPLAT_VECTOR: 3369 if (Op.getValueType().getVectorElementType() == MVT::i1) 3370 return lowerVectorMaskSplat(Op, DAG); 3371 return SDValue(); 3372 case ISD::VECTOR_SHUFFLE: 3373 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3374 case ISD::CONCAT_VECTORS: { 3375 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3376 // better than going through the stack, as the default expansion does. 3377 SDLoc DL(Op); 3378 MVT VT = Op.getSimpleValueType(); 3379 unsigned NumOpElts = 3380 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3381 SDValue Vec = DAG.getUNDEF(VT); 3382 for (const auto &OpIdx : enumerate(Op->ops())) { 3383 SDValue SubVec = OpIdx.value(); 3384 // Don't insert undef subvectors. 3385 if (SubVec.isUndef()) 3386 continue; 3387 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3388 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3389 } 3390 return Vec; 3391 } 3392 case ISD::LOAD: 3393 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3394 return V; 3395 if (Op.getValueType().isFixedLengthVector()) 3396 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3397 return Op; 3398 case ISD::STORE: 3399 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3400 return V; 3401 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3402 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3403 return Op; 3404 case ISD::MLOAD: 3405 case ISD::VP_LOAD: 3406 return lowerMaskedLoad(Op, DAG); 3407 case ISD::MSTORE: 3408 case ISD::VP_STORE: 3409 return lowerMaskedStore(Op, DAG); 3410 case ISD::SETCC: 3411 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3412 case ISD::ADD: 3413 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3414 case ISD::SUB: 3415 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3416 case ISD::MUL: 3417 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3418 case ISD::MULHS: 3419 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3420 case ISD::MULHU: 3421 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3422 case ISD::AND: 3423 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3424 RISCVISD::AND_VL); 3425 case ISD::OR: 3426 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3427 RISCVISD::OR_VL); 3428 case ISD::XOR: 3429 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3430 RISCVISD::XOR_VL); 3431 case ISD::SDIV: 3432 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3433 case ISD::SREM: 3434 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3435 case ISD::UDIV: 3436 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3437 case ISD::UREM: 3438 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3439 case ISD::SHL: 3440 case ISD::SRA: 3441 case ISD::SRL: 3442 if (Op.getSimpleValueType().isFixedLengthVector()) 3443 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3444 // This can be called for an i32 shift amount that needs to be promoted. 3445 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3446 "Unexpected custom legalisation"); 3447 return SDValue(); 3448 case ISD::SADDSAT: 3449 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3450 case ISD::UADDSAT: 3451 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3452 case ISD::SSUBSAT: 3453 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3454 case ISD::USUBSAT: 3455 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3456 case ISD::FADD: 3457 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3458 case ISD::FSUB: 3459 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3460 case ISD::FMUL: 3461 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3462 case ISD::FDIV: 3463 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3464 case ISD::FNEG: 3465 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3466 case ISD::FABS: 3467 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3468 case ISD::FSQRT: 3469 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3470 case ISD::FMA: 3471 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3472 case ISD::SMIN: 3473 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3474 case ISD::SMAX: 3475 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3476 case ISD::UMIN: 3477 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3478 case ISD::UMAX: 3479 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3480 case ISD::FMINNUM: 3481 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3482 case ISD::FMAXNUM: 3483 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3484 case ISD::ABS: 3485 return lowerABS(Op, DAG); 3486 case ISD::CTLZ_ZERO_UNDEF: 3487 case ISD::CTTZ_ZERO_UNDEF: 3488 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3489 case ISD::VSELECT: 3490 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3491 case ISD::FCOPYSIGN: 3492 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3493 case ISD::MGATHER: 3494 case ISD::VP_GATHER: 3495 return lowerMaskedGather(Op, DAG); 3496 case ISD::MSCATTER: 3497 case ISD::VP_SCATTER: 3498 return lowerMaskedScatter(Op, DAG); 3499 case ISD::FLT_ROUNDS_: 3500 return lowerGET_ROUNDING(Op, DAG); 3501 case ISD::SET_ROUNDING: 3502 return lowerSET_ROUNDING(Op, DAG); 3503 case ISD::EH_DWARF_CFA: 3504 return lowerEH_DWARF_CFA(Op, DAG); 3505 case ISD::VP_SELECT: 3506 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3507 case ISD::VP_MERGE: 3508 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3509 case ISD::VP_ADD: 3510 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3511 case ISD::VP_SUB: 3512 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3513 case ISD::VP_MUL: 3514 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3515 case ISD::VP_SDIV: 3516 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3517 case ISD::VP_UDIV: 3518 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3519 case ISD::VP_SREM: 3520 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3521 case ISD::VP_UREM: 3522 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3523 case ISD::VP_AND: 3524 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3525 case ISD::VP_OR: 3526 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3527 case ISD::VP_XOR: 3528 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3529 case ISD::VP_ASHR: 3530 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3531 case ISD::VP_LSHR: 3532 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3533 case ISD::VP_SHL: 3534 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3535 case ISD::VP_FADD: 3536 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3537 case ISD::VP_FSUB: 3538 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3539 case ISD::VP_FMUL: 3540 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3541 case ISD::VP_FDIV: 3542 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3543 case ISD::VP_FNEG: 3544 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3545 case ISD::VP_FMA: 3546 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3547 case ISD::VP_SIGN_EXTEND: 3548 case ISD::VP_ZERO_EXTEND: 3549 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3550 return lowerVPExtMaskOp(Op, DAG); 3551 return lowerVPOp(Op, DAG, 3552 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3553 ? RISCVISD::VSEXT_VL 3554 : RISCVISD::VZEXT_VL); 3555 case ISD::VP_TRUNCATE: 3556 return lowerVectorTruncLike(Op, DAG); 3557 case ISD::VP_FP_EXTEND: 3558 case ISD::VP_FP_ROUND: 3559 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3560 case ISD::VP_FPTOSI: 3561 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3562 case ISD::VP_FPTOUI: 3563 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3564 case ISD::VP_SITOFP: 3565 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3566 case ISD::VP_UITOFP: 3567 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3568 case ISD::VP_SETCC: 3569 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3570 return lowerVPSetCCMaskOp(Op, DAG); 3571 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3572 } 3573 } 3574 3575 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3576 SelectionDAG &DAG, unsigned Flags) { 3577 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3578 } 3579 3580 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3581 SelectionDAG &DAG, unsigned Flags) { 3582 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3583 Flags); 3584 } 3585 3586 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3587 SelectionDAG &DAG, unsigned Flags) { 3588 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3589 N->getOffset(), Flags); 3590 } 3591 3592 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3593 SelectionDAG &DAG, unsigned Flags) { 3594 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3595 } 3596 3597 template <class NodeTy> 3598 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3599 bool IsLocal) const { 3600 SDLoc DL(N); 3601 EVT Ty = getPointerTy(DAG.getDataLayout()); 3602 3603 if (isPositionIndependent()) { 3604 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3605 if (IsLocal) 3606 // Use PC-relative addressing to access the symbol. This generates the 3607 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3608 // %pcrel_lo(auipc)). 3609 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3610 3611 // Use PC-relative addressing to access the GOT for this symbol, then load 3612 // the address from the GOT. This generates the pattern (PseudoLA sym), 3613 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3614 SDValue Load = 3615 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3616 MachineFunction &MF = DAG.getMachineFunction(); 3617 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3618 MachinePointerInfo::getGOT(MF), 3619 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3620 MachineMemOperand::MOInvariant, 3621 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3622 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3623 return Load; 3624 } 3625 3626 switch (getTargetMachine().getCodeModel()) { 3627 default: 3628 report_fatal_error("Unsupported code model for lowering"); 3629 case CodeModel::Small: { 3630 // Generate a sequence for accessing addresses within the first 2 GiB of 3631 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3632 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3633 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3634 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3635 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3636 } 3637 case CodeModel::Medium: { 3638 // Generate a sequence for accessing addresses within any 2GiB range within 3639 // the address space. This generates the pattern (PseudoLLA sym), which 3640 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3641 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3642 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3643 } 3644 } 3645 } 3646 3647 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3648 SelectionDAG &DAG) const { 3649 SDLoc DL(Op); 3650 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3651 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3652 3653 const GlobalValue *GV = N->getGlobal(); 3654 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3655 return getAddr(N, DAG, IsLocal); 3656 } 3657 3658 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3659 SelectionDAG &DAG) const { 3660 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3661 3662 return getAddr(N, DAG); 3663 } 3664 3665 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3666 SelectionDAG &DAG) const { 3667 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3668 3669 return getAddr(N, DAG); 3670 } 3671 3672 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3673 SelectionDAG &DAG) const { 3674 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3675 3676 return getAddr(N, DAG); 3677 } 3678 3679 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3680 SelectionDAG &DAG, 3681 bool UseGOT) const { 3682 SDLoc DL(N); 3683 EVT Ty = getPointerTy(DAG.getDataLayout()); 3684 const GlobalValue *GV = N->getGlobal(); 3685 MVT XLenVT = Subtarget.getXLenVT(); 3686 3687 if (UseGOT) { 3688 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3689 // load the address from the GOT and add the thread pointer. This generates 3690 // the pattern (PseudoLA_TLS_IE sym), which expands to 3691 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3692 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3693 SDValue Load = 3694 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3695 MachineFunction &MF = DAG.getMachineFunction(); 3696 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3697 MachinePointerInfo::getGOT(MF), 3698 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3699 MachineMemOperand::MOInvariant, 3700 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3701 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3702 3703 // Add the thread pointer. 3704 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3705 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3706 } 3707 3708 // Generate a sequence for accessing the address relative to the thread 3709 // pointer, with the appropriate adjustment for the thread pointer offset. 3710 // This generates the pattern 3711 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3712 SDValue AddrHi = 3713 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3714 SDValue AddrAdd = 3715 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3716 SDValue AddrLo = 3717 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3718 3719 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3720 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3721 SDValue MNAdd = SDValue( 3722 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3723 0); 3724 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3725 } 3726 3727 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3728 SelectionDAG &DAG) const { 3729 SDLoc DL(N); 3730 EVT Ty = getPointerTy(DAG.getDataLayout()); 3731 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3732 const GlobalValue *GV = N->getGlobal(); 3733 3734 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3735 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3736 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3737 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3738 SDValue Load = 3739 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3740 3741 // Prepare argument list to generate call. 3742 ArgListTy Args; 3743 ArgListEntry Entry; 3744 Entry.Node = Load; 3745 Entry.Ty = CallTy; 3746 Args.push_back(Entry); 3747 3748 // Setup call to __tls_get_addr. 3749 TargetLowering::CallLoweringInfo CLI(DAG); 3750 CLI.setDebugLoc(DL) 3751 .setChain(DAG.getEntryNode()) 3752 .setLibCallee(CallingConv::C, CallTy, 3753 DAG.getExternalSymbol("__tls_get_addr", Ty), 3754 std::move(Args)); 3755 3756 return LowerCallTo(CLI).first; 3757 } 3758 3759 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3760 SelectionDAG &DAG) const { 3761 SDLoc DL(Op); 3762 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3763 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3764 3765 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3766 3767 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3768 CallingConv::GHC) 3769 report_fatal_error("In GHC calling convention TLS is not supported"); 3770 3771 SDValue Addr; 3772 switch (Model) { 3773 case TLSModel::LocalExec: 3774 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3775 break; 3776 case TLSModel::InitialExec: 3777 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3778 break; 3779 case TLSModel::LocalDynamic: 3780 case TLSModel::GeneralDynamic: 3781 Addr = getDynamicTLSAddr(N, DAG); 3782 break; 3783 } 3784 3785 return Addr; 3786 } 3787 3788 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3789 SDValue CondV = Op.getOperand(0); 3790 SDValue TrueV = Op.getOperand(1); 3791 SDValue FalseV = Op.getOperand(2); 3792 SDLoc DL(Op); 3793 MVT VT = Op.getSimpleValueType(); 3794 MVT XLenVT = Subtarget.getXLenVT(); 3795 3796 // Lower vector SELECTs to VSELECTs by splatting the condition. 3797 if (VT.isVector()) { 3798 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3799 SDValue CondSplat = VT.isScalableVector() 3800 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3801 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3802 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3803 } 3804 3805 // If the result type is XLenVT and CondV is the output of a SETCC node 3806 // which also operated on XLenVT inputs, then merge the SETCC node into the 3807 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3808 // compare+branch instructions. i.e.: 3809 // (select (setcc lhs, rhs, cc), truev, falsev) 3810 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3811 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3812 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3813 SDValue LHS = CondV.getOperand(0); 3814 SDValue RHS = CondV.getOperand(1); 3815 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3816 ISD::CondCode CCVal = CC->get(); 3817 3818 // Special case for a select of 2 constants that have a diffence of 1. 3819 // Normally this is done by DAGCombine, but if the select is introduced by 3820 // type legalization or op legalization, we miss it. Restricting to SETLT 3821 // case for now because that is what signed saturating add/sub need. 3822 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3823 // but we would probably want to swap the true/false values if the condition 3824 // is SETGE/SETLE to avoid an XORI. 3825 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3826 CCVal == ISD::SETLT) { 3827 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3828 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3829 if (TrueVal - 1 == FalseVal) 3830 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3831 if (TrueVal + 1 == FalseVal) 3832 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3833 } 3834 3835 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3836 3837 SDValue TargetCC = DAG.getCondCode(CCVal); 3838 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3839 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3840 } 3841 3842 // Otherwise: 3843 // (select condv, truev, falsev) 3844 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3845 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3846 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3847 3848 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3849 3850 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3851 } 3852 3853 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3854 SDValue CondV = Op.getOperand(1); 3855 SDLoc DL(Op); 3856 MVT XLenVT = Subtarget.getXLenVT(); 3857 3858 if (CondV.getOpcode() == ISD::SETCC && 3859 CondV.getOperand(0).getValueType() == XLenVT) { 3860 SDValue LHS = CondV.getOperand(0); 3861 SDValue RHS = CondV.getOperand(1); 3862 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3863 3864 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3865 3866 SDValue TargetCC = DAG.getCondCode(CCVal); 3867 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3868 LHS, RHS, TargetCC, Op.getOperand(2)); 3869 } 3870 3871 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3872 CondV, DAG.getConstant(0, DL, XLenVT), 3873 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3874 } 3875 3876 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3877 MachineFunction &MF = DAG.getMachineFunction(); 3878 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3879 3880 SDLoc DL(Op); 3881 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3882 getPointerTy(MF.getDataLayout())); 3883 3884 // vastart just stores the address of the VarArgsFrameIndex slot into the 3885 // memory location argument. 3886 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3887 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3888 MachinePointerInfo(SV)); 3889 } 3890 3891 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3892 SelectionDAG &DAG) const { 3893 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3894 MachineFunction &MF = DAG.getMachineFunction(); 3895 MachineFrameInfo &MFI = MF.getFrameInfo(); 3896 MFI.setFrameAddressIsTaken(true); 3897 Register FrameReg = RI.getFrameRegister(MF); 3898 int XLenInBytes = Subtarget.getXLen() / 8; 3899 3900 EVT VT = Op.getValueType(); 3901 SDLoc DL(Op); 3902 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3903 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3904 while (Depth--) { 3905 int Offset = -(XLenInBytes * 2); 3906 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3907 DAG.getIntPtrConstant(Offset, DL)); 3908 FrameAddr = 3909 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3910 } 3911 return FrameAddr; 3912 } 3913 3914 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3915 SelectionDAG &DAG) const { 3916 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3917 MachineFunction &MF = DAG.getMachineFunction(); 3918 MachineFrameInfo &MFI = MF.getFrameInfo(); 3919 MFI.setReturnAddressIsTaken(true); 3920 MVT XLenVT = Subtarget.getXLenVT(); 3921 int XLenInBytes = Subtarget.getXLen() / 8; 3922 3923 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3924 return SDValue(); 3925 3926 EVT VT = Op.getValueType(); 3927 SDLoc DL(Op); 3928 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3929 if (Depth) { 3930 int Off = -XLenInBytes; 3931 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3932 SDValue Offset = DAG.getConstant(Off, DL, VT); 3933 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3934 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3935 MachinePointerInfo()); 3936 } 3937 3938 // Return the value of the return address register, marking it an implicit 3939 // live-in. 3940 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3941 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3942 } 3943 3944 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3945 SelectionDAG &DAG) const { 3946 SDLoc DL(Op); 3947 SDValue Lo = Op.getOperand(0); 3948 SDValue Hi = Op.getOperand(1); 3949 SDValue Shamt = Op.getOperand(2); 3950 EVT VT = Lo.getValueType(); 3951 3952 // if Shamt-XLEN < 0: // Shamt < XLEN 3953 // Lo = Lo << Shamt 3954 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3955 // else: 3956 // Lo = 0 3957 // Hi = Lo << (Shamt-XLEN) 3958 3959 SDValue Zero = DAG.getConstant(0, DL, VT); 3960 SDValue One = DAG.getConstant(1, DL, VT); 3961 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3962 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3963 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3964 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3965 3966 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3967 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3968 SDValue ShiftRightLo = 3969 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3970 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3971 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3972 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3973 3974 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3975 3976 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3977 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3978 3979 SDValue Parts[2] = {Lo, Hi}; 3980 return DAG.getMergeValues(Parts, DL); 3981 } 3982 3983 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3984 bool IsSRA) const { 3985 SDLoc DL(Op); 3986 SDValue Lo = Op.getOperand(0); 3987 SDValue Hi = Op.getOperand(1); 3988 SDValue Shamt = Op.getOperand(2); 3989 EVT VT = Lo.getValueType(); 3990 3991 // SRA expansion: 3992 // if Shamt-XLEN < 0: // Shamt < XLEN 3993 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3994 // Hi = Hi >>s Shamt 3995 // else: 3996 // Lo = Hi >>s (Shamt-XLEN); 3997 // Hi = Hi >>s (XLEN-1) 3998 // 3999 // SRL expansion: 4000 // if Shamt-XLEN < 0: // Shamt < XLEN 4001 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4002 // Hi = Hi >>u Shamt 4003 // else: 4004 // Lo = Hi >>u (Shamt-XLEN); 4005 // Hi = 0; 4006 4007 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4008 4009 SDValue Zero = DAG.getConstant(0, DL, VT); 4010 SDValue One = DAG.getConstant(1, DL, VT); 4011 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4012 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4013 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4014 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4015 4016 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4017 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4018 SDValue ShiftLeftHi = 4019 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4020 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4021 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4022 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4023 SDValue HiFalse = 4024 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4025 4026 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4027 4028 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4029 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4030 4031 SDValue Parts[2] = {Lo, Hi}; 4032 return DAG.getMergeValues(Parts, DL); 4033 } 4034 4035 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4036 // legal equivalently-sized i8 type, so we can use that as a go-between. 4037 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4038 SelectionDAG &DAG) const { 4039 SDLoc DL(Op); 4040 MVT VT = Op.getSimpleValueType(); 4041 SDValue SplatVal = Op.getOperand(0); 4042 // All-zeros or all-ones splats are handled specially. 4043 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4044 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4045 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4046 } 4047 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4048 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4049 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4050 } 4051 MVT XLenVT = Subtarget.getXLenVT(); 4052 assert(SplatVal.getValueType() == XLenVT && 4053 "Unexpected type for i1 splat value"); 4054 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4055 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4056 DAG.getConstant(1, DL, XLenVT)); 4057 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4058 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4059 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4060 } 4061 4062 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4063 // illegal (currently only vXi64 RV32). 4064 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4065 // them to VMV_V_X_VL. 4066 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4067 SelectionDAG &DAG) const { 4068 SDLoc DL(Op); 4069 MVT VecVT = Op.getSimpleValueType(); 4070 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4071 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4072 4073 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4074 SDValue Lo = Op.getOperand(0); 4075 SDValue Hi = Op.getOperand(1); 4076 4077 if (VecVT.isFixedLengthVector()) { 4078 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4079 SDLoc DL(Op); 4080 SDValue Mask, VL; 4081 std::tie(Mask, VL) = 4082 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4083 4084 SDValue Res = 4085 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4086 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4087 } 4088 4089 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4090 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4091 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4092 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4093 // node in order to try and match RVV vector/scalar instructions. 4094 if ((LoC >> 31) == HiC) 4095 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4096 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4097 } 4098 4099 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4100 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4101 isa<ConstantSDNode>(Hi.getOperand(1)) && 4102 Hi.getConstantOperandVal(1) == 31) 4103 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4104 DAG.getRegister(RISCV::X0, MVT::i32)); 4105 4106 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4107 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4108 DAG.getUNDEF(VecVT), Lo, Hi, 4109 DAG.getRegister(RISCV::X0, MVT::i32)); 4110 } 4111 4112 // Custom-lower extensions from mask vectors by using a vselect either with 1 4113 // for zero/any-extension or -1 for sign-extension: 4114 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4115 // Note that any-extension is lowered identically to zero-extension. 4116 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4117 int64_t ExtTrueVal) const { 4118 SDLoc DL(Op); 4119 MVT VecVT = Op.getSimpleValueType(); 4120 SDValue Src = Op.getOperand(0); 4121 // Only custom-lower extensions from mask types 4122 assert(Src.getValueType().isVector() && 4123 Src.getValueType().getVectorElementType() == MVT::i1); 4124 4125 if (VecVT.isScalableVector()) { 4126 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4127 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4128 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4129 } 4130 4131 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4132 MVT I1ContainerVT = 4133 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4134 4135 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4136 4137 SDValue Mask, VL; 4138 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4139 4140 MVT XLenVT = Subtarget.getXLenVT(); 4141 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4142 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4143 4144 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4145 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4146 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4147 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4148 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4149 SplatTrueVal, SplatZero, VL); 4150 4151 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4152 } 4153 4154 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4155 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4156 MVT ExtVT = Op.getSimpleValueType(); 4157 // Only custom-lower extensions from fixed-length vector types. 4158 if (!ExtVT.isFixedLengthVector()) 4159 return Op; 4160 MVT VT = Op.getOperand(0).getSimpleValueType(); 4161 // Grab the canonical container type for the extended type. Infer the smaller 4162 // type from that to ensure the same number of vector elements, as we know 4163 // the LMUL will be sufficient to hold the smaller type. 4164 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4165 // Get the extended container type manually to ensure the same number of 4166 // vector elements between source and dest. 4167 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4168 ContainerExtVT.getVectorElementCount()); 4169 4170 SDValue Op1 = 4171 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4172 4173 SDLoc DL(Op); 4174 SDValue Mask, VL; 4175 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4176 4177 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4178 4179 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4180 } 4181 4182 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4183 // setcc operation: 4184 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4185 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4186 SelectionDAG &DAG) const { 4187 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4188 SDLoc DL(Op); 4189 EVT MaskVT = Op.getValueType(); 4190 // Only expect to custom-lower truncations to mask types 4191 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4192 "Unexpected type for vector mask lowering"); 4193 SDValue Src = Op.getOperand(0); 4194 MVT VecVT = Src.getSimpleValueType(); 4195 SDValue Mask, VL; 4196 if (IsVPTrunc) { 4197 Mask = Op.getOperand(1); 4198 VL = Op.getOperand(2); 4199 } 4200 // If this is a fixed vector, we need to convert it to a scalable vector. 4201 MVT ContainerVT = VecVT; 4202 4203 if (VecVT.isFixedLengthVector()) { 4204 ContainerVT = getContainerForFixedLengthVector(VecVT); 4205 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4206 if (IsVPTrunc) { 4207 MVT MaskContainerVT = 4208 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4209 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4210 } 4211 } 4212 4213 if (!IsVPTrunc) { 4214 std::tie(Mask, VL) = 4215 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4216 } 4217 4218 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4219 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4220 4221 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4222 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4223 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4224 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4225 4226 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4227 SDValue Trunc = 4228 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4229 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4230 DAG.getCondCode(ISD::SETNE), Mask, VL); 4231 if (MaskVT.isFixedLengthVector()) 4232 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4233 return Trunc; 4234 } 4235 4236 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4237 SelectionDAG &DAG) const { 4238 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4239 SDLoc DL(Op); 4240 4241 MVT VT = Op.getSimpleValueType(); 4242 // Only custom-lower vector truncates 4243 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4244 4245 // Truncates to mask types are handled differently 4246 if (VT.getVectorElementType() == MVT::i1) 4247 return lowerVectorMaskTruncLike(Op, DAG); 4248 4249 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4250 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4251 // truncate by one power of two at a time. 4252 MVT DstEltVT = VT.getVectorElementType(); 4253 4254 SDValue Src = Op.getOperand(0); 4255 MVT SrcVT = Src.getSimpleValueType(); 4256 MVT SrcEltVT = SrcVT.getVectorElementType(); 4257 4258 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4259 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4260 "Unexpected vector truncate lowering"); 4261 4262 MVT ContainerVT = SrcVT; 4263 SDValue Mask, VL; 4264 if (IsVPTrunc) { 4265 Mask = Op.getOperand(1); 4266 VL = Op.getOperand(2); 4267 } 4268 if (SrcVT.isFixedLengthVector()) { 4269 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4270 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4271 if (IsVPTrunc) { 4272 MVT MaskVT = getMaskTypeFor(ContainerVT); 4273 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4274 } 4275 } 4276 4277 SDValue Result = Src; 4278 if (!IsVPTrunc) { 4279 std::tie(Mask, VL) = 4280 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4281 } 4282 4283 LLVMContext &Context = *DAG.getContext(); 4284 const ElementCount Count = ContainerVT.getVectorElementCount(); 4285 do { 4286 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4287 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4288 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4289 Mask, VL); 4290 } while (SrcEltVT != DstEltVT); 4291 4292 if (SrcVT.isFixedLengthVector()) 4293 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4294 4295 return Result; 4296 } 4297 4298 SDValue 4299 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4300 SelectionDAG &DAG) const { 4301 bool IsVP = 4302 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4303 bool IsExtend = 4304 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4305 // RVV can only do truncate fp to types half the size as the source. We 4306 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4307 // conversion instruction. 4308 SDLoc DL(Op); 4309 MVT VT = Op.getSimpleValueType(); 4310 4311 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4312 4313 SDValue Src = Op.getOperand(0); 4314 MVT SrcVT = Src.getSimpleValueType(); 4315 4316 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4317 SrcVT.getVectorElementType() != MVT::f16); 4318 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4319 SrcVT.getVectorElementType() != MVT::f64); 4320 4321 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4322 4323 // Prepare any fixed-length vector operands. 4324 MVT ContainerVT = VT; 4325 SDValue Mask, VL; 4326 if (IsVP) { 4327 Mask = Op.getOperand(1); 4328 VL = Op.getOperand(2); 4329 } 4330 if (VT.isFixedLengthVector()) { 4331 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4332 ContainerVT = 4333 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4334 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4335 if (IsVP) { 4336 MVT MaskVT = getMaskTypeFor(ContainerVT); 4337 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4338 } 4339 } 4340 4341 if (!IsVP) 4342 std::tie(Mask, VL) = 4343 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4344 4345 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4346 4347 if (IsDirectConv) { 4348 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4349 if (VT.isFixedLengthVector()) 4350 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4351 return Src; 4352 } 4353 4354 unsigned InterConvOpc = 4355 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4356 4357 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4358 SDValue IntermediateConv = 4359 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4360 SDValue Result = 4361 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4362 if (VT.isFixedLengthVector()) 4363 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4364 return Result; 4365 } 4366 4367 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4368 // first position of a vector, and that vector is slid up to the insert index. 4369 // By limiting the active vector length to index+1 and merging with the 4370 // original vector (with an undisturbed tail policy for elements >= VL), we 4371 // achieve the desired result of leaving all elements untouched except the one 4372 // at VL-1, which is replaced with the desired value. 4373 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4374 SelectionDAG &DAG) const { 4375 SDLoc DL(Op); 4376 MVT VecVT = Op.getSimpleValueType(); 4377 SDValue Vec = Op.getOperand(0); 4378 SDValue Val = Op.getOperand(1); 4379 SDValue Idx = Op.getOperand(2); 4380 4381 if (VecVT.getVectorElementType() == MVT::i1) { 4382 // FIXME: For now we just promote to an i8 vector and insert into that, 4383 // but this is probably not optimal. 4384 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4385 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4386 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4387 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4388 } 4389 4390 MVT ContainerVT = VecVT; 4391 // If the operand is a fixed-length vector, convert to a scalable one. 4392 if (VecVT.isFixedLengthVector()) { 4393 ContainerVT = getContainerForFixedLengthVector(VecVT); 4394 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4395 } 4396 4397 MVT XLenVT = Subtarget.getXLenVT(); 4398 4399 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4400 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4401 // Even i64-element vectors on RV32 can be lowered without scalar 4402 // legalization if the most-significant 32 bits of the value are not affected 4403 // by the sign-extension of the lower 32 bits. 4404 // TODO: We could also catch sign extensions of a 32-bit value. 4405 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4406 const auto *CVal = cast<ConstantSDNode>(Val); 4407 if (isInt<32>(CVal->getSExtValue())) { 4408 IsLegalInsert = true; 4409 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4410 } 4411 } 4412 4413 SDValue Mask, VL; 4414 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4415 4416 SDValue ValInVec; 4417 4418 if (IsLegalInsert) { 4419 unsigned Opc = 4420 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4421 if (isNullConstant(Idx)) { 4422 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4423 if (!VecVT.isFixedLengthVector()) 4424 return Vec; 4425 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4426 } 4427 ValInVec = 4428 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4429 } else { 4430 // On RV32, i64-element vectors must be specially handled to place the 4431 // value at element 0, by using two vslide1up instructions in sequence on 4432 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4433 // this. 4434 SDValue One = DAG.getConstant(1, DL, XLenVT); 4435 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4436 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4437 MVT I32ContainerVT = 4438 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4439 SDValue I32Mask = 4440 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4441 // Limit the active VL to two. 4442 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4443 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4444 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4445 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4446 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4447 // First slide in the hi value, then the lo in underneath it. 4448 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4449 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4450 I32Mask, InsertI64VL); 4451 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4452 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4453 I32Mask, InsertI64VL); 4454 // Bitcast back to the right container type. 4455 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4456 } 4457 4458 // Now that the value is in a vector, slide it into position. 4459 SDValue InsertVL = 4460 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4461 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4462 ValInVec, Idx, Mask, InsertVL); 4463 if (!VecVT.isFixedLengthVector()) 4464 return Slideup; 4465 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4466 } 4467 4468 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4469 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4470 // types this is done using VMV_X_S to allow us to glean information about the 4471 // sign bits of the result. 4472 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4473 SelectionDAG &DAG) const { 4474 SDLoc DL(Op); 4475 SDValue Idx = Op.getOperand(1); 4476 SDValue Vec = Op.getOperand(0); 4477 EVT EltVT = Op.getValueType(); 4478 MVT VecVT = Vec.getSimpleValueType(); 4479 MVT XLenVT = Subtarget.getXLenVT(); 4480 4481 if (VecVT.getVectorElementType() == MVT::i1) { 4482 if (VecVT.isFixedLengthVector()) { 4483 unsigned NumElts = VecVT.getVectorNumElements(); 4484 if (NumElts >= 8) { 4485 MVT WideEltVT; 4486 unsigned WidenVecLen; 4487 SDValue ExtractElementIdx; 4488 SDValue ExtractBitIdx; 4489 unsigned MaxEEW = Subtarget.getELEN(); 4490 MVT LargestEltVT = MVT::getIntegerVT( 4491 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4492 if (NumElts <= LargestEltVT.getSizeInBits()) { 4493 assert(isPowerOf2_32(NumElts) && 4494 "the number of elements should be power of 2"); 4495 WideEltVT = MVT::getIntegerVT(NumElts); 4496 WidenVecLen = 1; 4497 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4498 ExtractBitIdx = Idx; 4499 } else { 4500 WideEltVT = LargestEltVT; 4501 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4502 // extract element index = index / element width 4503 ExtractElementIdx = DAG.getNode( 4504 ISD::SRL, DL, XLenVT, Idx, 4505 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4506 // mask bit index = index % element width 4507 ExtractBitIdx = DAG.getNode( 4508 ISD::AND, DL, XLenVT, Idx, 4509 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4510 } 4511 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4512 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4513 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4514 Vec, ExtractElementIdx); 4515 // Extract the bit from GPR. 4516 SDValue ShiftRight = 4517 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4518 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4519 DAG.getConstant(1, DL, XLenVT)); 4520 } 4521 } 4522 // Otherwise, promote to an i8 vector and extract from that. 4523 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4524 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4525 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4526 } 4527 4528 // If this is a fixed vector, we need to convert it to a scalable vector. 4529 MVT ContainerVT = VecVT; 4530 if (VecVT.isFixedLengthVector()) { 4531 ContainerVT = getContainerForFixedLengthVector(VecVT); 4532 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4533 } 4534 4535 // If the index is 0, the vector is already in the right position. 4536 if (!isNullConstant(Idx)) { 4537 // Use a VL of 1 to avoid processing more elements than we need. 4538 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4539 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4540 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4541 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4542 } 4543 4544 if (!EltVT.isInteger()) { 4545 // Floating-point extracts are handled in TableGen. 4546 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4547 DAG.getConstant(0, DL, XLenVT)); 4548 } 4549 4550 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4551 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4552 } 4553 4554 // Some RVV intrinsics may claim that they want an integer operand to be 4555 // promoted or expanded. 4556 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4557 const RISCVSubtarget &Subtarget) { 4558 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4559 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4560 "Unexpected opcode"); 4561 4562 if (!Subtarget.hasVInstructions()) 4563 return SDValue(); 4564 4565 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4566 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4567 SDLoc DL(Op); 4568 4569 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4570 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4571 if (!II || !II->hasScalarOperand()) 4572 return SDValue(); 4573 4574 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4575 assert(SplatOp < Op.getNumOperands()); 4576 4577 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4578 SDValue &ScalarOp = Operands[SplatOp]; 4579 MVT OpVT = ScalarOp.getSimpleValueType(); 4580 MVT XLenVT = Subtarget.getXLenVT(); 4581 4582 // If this isn't a scalar, or its type is XLenVT we're done. 4583 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4584 return SDValue(); 4585 4586 // Simplest case is that the operand needs to be promoted to XLenVT. 4587 if (OpVT.bitsLT(XLenVT)) { 4588 // If the operand is a constant, sign extend to increase our chances 4589 // of being able to use a .vi instruction. ANY_EXTEND would become a 4590 // a zero extend and the simm5 check in isel would fail. 4591 // FIXME: Should we ignore the upper bits in isel instead? 4592 unsigned ExtOpc = 4593 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4594 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4595 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4596 } 4597 4598 // Use the previous operand to get the vXi64 VT. The result might be a mask 4599 // VT for compares. Using the previous operand assumes that the previous 4600 // operand will never have a smaller element size than a scalar operand and 4601 // that a widening operation never uses SEW=64. 4602 // NOTE: If this fails the below assert, we can probably just find the 4603 // element count from any operand or result and use it to construct the VT. 4604 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4605 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4606 4607 // The more complex case is when the scalar is larger than XLenVT. 4608 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4609 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4610 4611 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4612 // instruction to sign-extend since SEW>XLEN. 4613 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4614 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4615 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4616 } 4617 4618 switch (IntNo) { 4619 case Intrinsic::riscv_vslide1up: 4620 case Intrinsic::riscv_vslide1down: 4621 case Intrinsic::riscv_vslide1up_mask: 4622 case Intrinsic::riscv_vslide1down_mask: { 4623 // We need to special case these when the scalar is larger than XLen. 4624 unsigned NumOps = Op.getNumOperands(); 4625 bool IsMasked = NumOps == 7; 4626 4627 // Convert the vector source to the equivalent nxvXi32 vector. 4628 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4629 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4630 4631 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4632 DAG.getConstant(0, DL, XLenVT)); 4633 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4634 DAG.getConstant(1, DL, XLenVT)); 4635 4636 // Double the VL since we halved SEW. 4637 SDValue AVL = getVLOperand(Op); 4638 SDValue I32VL; 4639 4640 // Optimize for constant AVL 4641 if (isa<ConstantSDNode>(AVL)) { 4642 unsigned EltSize = VT.getScalarSizeInBits(); 4643 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4644 4645 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4646 unsigned MaxVLMAX = 4647 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4648 4649 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4650 unsigned MinVLMAX = 4651 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4652 4653 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4654 if (AVLInt <= MinVLMAX) { 4655 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4656 } else if (AVLInt >= 2 * MaxVLMAX) { 4657 // Just set vl to VLMAX in this situation 4658 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4659 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4660 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4661 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4662 SDValue SETVLMAX = DAG.getTargetConstant( 4663 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4664 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4665 LMUL); 4666 } else { 4667 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4668 // is related to the hardware implementation. 4669 // So let the following code handle 4670 } 4671 } 4672 if (!I32VL) { 4673 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4674 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4675 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4676 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4677 SDValue SETVL = 4678 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4679 // Using vsetvli instruction to get actually used length which related to 4680 // the hardware implementation 4681 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4682 SEW, LMUL); 4683 I32VL = 4684 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4685 } 4686 4687 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4688 4689 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4690 // instructions. 4691 SDValue Passthru; 4692 if (IsMasked) 4693 Passthru = DAG.getUNDEF(I32VT); 4694 else 4695 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4696 4697 if (IntNo == Intrinsic::riscv_vslide1up || 4698 IntNo == Intrinsic::riscv_vslide1up_mask) { 4699 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4700 ScalarHi, I32Mask, I32VL); 4701 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4702 ScalarLo, I32Mask, I32VL); 4703 } else { 4704 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4705 ScalarLo, I32Mask, I32VL); 4706 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4707 ScalarHi, I32Mask, I32VL); 4708 } 4709 4710 // Convert back to nxvXi64. 4711 Vec = DAG.getBitcast(VT, Vec); 4712 4713 if (!IsMasked) 4714 return Vec; 4715 // Apply mask after the operation. 4716 SDValue Mask = Operands[NumOps - 3]; 4717 SDValue MaskedOff = Operands[1]; 4718 // Assume Policy operand is the last operand. 4719 uint64_t Policy = 4720 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4721 // We don't need to select maskedoff if it's undef. 4722 if (MaskedOff.isUndef()) 4723 return Vec; 4724 // TAMU 4725 if (Policy == RISCVII::TAIL_AGNOSTIC) 4726 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4727 AVL); 4728 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4729 // It's fine because vmerge does not care mask policy. 4730 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4731 AVL); 4732 } 4733 } 4734 4735 // We need to convert the scalar to a splat vector. 4736 SDValue VL = getVLOperand(Op); 4737 assert(VL.getValueType() == XLenVT); 4738 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4739 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4740 } 4741 4742 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4743 SelectionDAG &DAG) const { 4744 unsigned IntNo = Op.getConstantOperandVal(0); 4745 SDLoc DL(Op); 4746 MVT XLenVT = Subtarget.getXLenVT(); 4747 4748 switch (IntNo) { 4749 default: 4750 break; // Don't custom lower most intrinsics. 4751 case Intrinsic::thread_pointer: { 4752 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4753 return DAG.getRegister(RISCV::X4, PtrVT); 4754 } 4755 case Intrinsic::riscv_orc_b: 4756 case Intrinsic::riscv_brev8: { 4757 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4758 unsigned Opc = 4759 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4760 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4761 DAG.getConstant(7, DL, XLenVT)); 4762 } 4763 case Intrinsic::riscv_grev: 4764 case Intrinsic::riscv_gorc: { 4765 unsigned Opc = 4766 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4767 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4768 } 4769 case Intrinsic::riscv_zip: 4770 case Intrinsic::riscv_unzip: { 4771 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4772 // For i32 the immediate is 15. For i64 the immediate is 31. 4773 unsigned Opc = 4774 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4775 unsigned BitWidth = Op.getValueSizeInBits(); 4776 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4777 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4778 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4779 } 4780 case Intrinsic::riscv_shfl: 4781 case Intrinsic::riscv_unshfl: { 4782 unsigned Opc = 4783 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4784 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4785 } 4786 case Intrinsic::riscv_bcompress: 4787 case Intrinsic::riscv_bdecompress: { 4788 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4789 : RISCVISD::BDECOMPRESS; 4790 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4791 } 4792 case Intrinsic::riscv_bfp: 4793 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4794 Op.getOperand(2)); 4795 case Intrinsic::riscv_fsl: 4796 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4797 Op.getOperand(2), Op.getOperand(3)); 4798 case Intrinsic::riscv_fsr: 4799 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4800 Op.getOperand(2), Op.getOperand(3)); 4801 case Intrinsic::riscv_vmv_x_s: 4802 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4803 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4804 Op.getOperand(1)); 4805 case Intrinsic::riscv_vmv_v_x: 4806 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4807 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4808 Subtarget); 4809 case Intrinsic::riscv_vfmv_v_f: 4810 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4811 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4812 case Intrinsic::riscv_vmv_s_x: { 4813 SDValue Scalar = Op.getOperand(2); 4814 4815 if (Scalar.getValueType().bitsLE(XLenVT)) { 4816 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4817 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4818 Op.getOperand(1), Scalar, Op.getOperand(3)); 4819 } 4820 4821 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4822 4823 // This is an i64 value that lives in two scalar registers. We have to 4824 // insert this in a convoluted way. First we build vXi64 splat containing 4825 // the two values that we assemble using some bit math. Next we'll use 4826 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4827 // to merge element 0 from our splat into the source vector. 4828 // FIXME: This is probably not the best way to do this, but it is 4829 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4830 // point. 4831 // sw lo, (a0) 4832 // sw hi, 4(a0) 4833 // vlse vX, (a0) 4834 // 4835 // vid.v vVid 4836 // vmseq.vx mMask, vVid, 0 4837 // vmerge.vvm vDest, vSrc, vVal, mMask 4838 MVT VT = Op.getSimpleValueType(); 4839 SDValue Vec = Op.getOperand(1); 4840 SDValue VL = getVLOperand(Op); 4841 4842 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4843 if (Op.getOperand(1).isUndef()) 4844 return SplattedVal; 4845 SDValue SplattedIdx = 4846 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4847 DAG.getConstant(0, DL, MVT::i32), VL); 4848 4849 MVT MaskVT = getMaskTypeFor(VT); 4850 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4851 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4852 SDValue SelectCond = 4853 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4854 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4855 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4856 Vec, VL); 4857 } 4858 } 4859 4860 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4861 } 4862 4863 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4864 SelectionDAG &DAG) const { 4865 unsigned IntNo = Op.getConstantOperandVal(1); 4866 switch (IntNo) { 4867 default: 4868 break; 4869 case Intrinsic::riscv_masked_strided_load: { 4870 SDLoc DL(Op); 4871 MVT XLenVT = Subtarget.getXLenVT(); 4872 4873 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4874 // the selection of the masked intrinsics doesn't do this for us. 4875 SDValue Mask = Op.getOperand(5); 4876 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4877 4878 MVT VT = Op->getSimpleValueType(0); 4879 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4880 4881 SDValue PassThru = Op.getOperand(2); 4882 if (!IsUnmasked) { 4883 MVT MaskVT = getMaskTypeFor(ContainerVT); 4884 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4885 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4886 } 4887 4888 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4889 4890 SDValue IntID = DAG.getTargetConstant( 4891 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4892 XLenVT); 4893 4894 auto *Load = cast<MemIntrinsicSDNode>(Op); 4895 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4896 if (IsUnmasked) 4897 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4898 else 4899 Ops.push_back(PassThru); 4900 Ops.push_back(Op.getOperand(3)); // Ptr 4901 Ops.push_back(Op.getOperand(4)); // Stride 4902 if (!IsUnmasked) 4903 Ops.push_back(Mask); 4904 Ops.push_back(VL); 4905 if (!IsUnmasked) { 4906 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4907 Ops.push_back(Policy); 4908 } 4909 4910 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4911 SDValue Result = 4912 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4913 Load->getMemoryVT(), Load->getMemOperand()); 4914 SDValue Chain = Result.getValue(1); 4915 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4916 return DAG.getMergeValues({Result, Chain}, DL); 4917 } 4918 case Intrinsic::riscv_seg2_load: 4919 case Intrinsic::riscv_seg3_load: 4920 case Intrinsic::riscv_seg4_load: 4921 case Intrinsic::riscv_seg5_load: 4922 case Intrinsic::riscv_seg6_load: 4923 case Intrinsic::riscv_seg7_load: 4924 case Intrinsic::riscv_seg8_load: { 4925 SDLoc DL(Op); 4926 static const Intrinsic::ID VlsegInts[7] = { 4927 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4928 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4929 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4930 Intrinsic::riscv_vlseg8}; 4931 unsigned NF = Op->getNumValues() - 1; 4932 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4933 MVT XLenVT = Subtarget.getXLenVT(); 4934 MVT VT = Op->getSimpleValueType(0); 4935 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4936 4937 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4938 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4939 auto *Load = cast<MemIntrinsicSDNode>(Op); 4940 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4941 ContainerVTs.push_back(MVT::Other); 4942 SDVTList VTs = DAG.getVTList(ContainerVTs); 4943 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4944 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4945 Ops.push_back(Op.getOperand(2)); 4946 Ops.push_back(VL); 4947 SDValue Result = 4948 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4949 Load->getMemoryVT(), Load->getMemOperand()); 4950 SmallVector<SDValue, 9> Results; 4951 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4952 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4953 DAG, Subtarget)); 4954 Results.push_back(Result.getValue(NF)); 4955 return DAG.getMergeValues(Results, DL); 4956 } 4957 } 4958 4959 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4960 } 4961 4962 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4963 SelectionDAG &DAG) const { 4964 unsigned IntNo = Op.getConstantOperandVal(1); 4965 switch (IntNo) { 4966 default: 4967 break; 4968 case Intrinsic::riscv_masked_strided_store: { 4969 SDLoc DL(Op); 4970 MVT XLenVT = Subtarget.getXLenVT(); 4971 4972 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4973 // the selection of the masked intrinsics doesn't do this for us. 4974 SDValue Mask = Op.getOperand(5); 4975 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4976 4977 SDValue Val = Op.getOperand(2); 4978 MVT VT = Val.getSimpleValueType(); 4979 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4980 4981 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4982 if (!IsUnmasked) { 4983 MVT MaskVT = getMaskTypeFor(ContainerVT); 4984 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4985 } 4986 4987 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4988 4989 SDValue IntID = DAG.getTargetConstant( 4990 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4991 XLenVT); 4992 4993 auto *Store = cast<MemIntrinsicSDNode>(Op); 4994 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4995 Ops.push_back(Val); 4996 Ops.push_back(Op.getOperand(3)); // Ptr 4997 Ops.push_back(Op.getOperand(4)); // Stride 4998 if (!IsUnmasked) 4999 Ops.push_back(Mask); 5000 Ops.push_back(VL); 5001 5002 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5003 Ops, Store->getMemoryVT(), 5004 Store->getMemOperand()); 5005 } 5006 } 5007 5008 return SDValue(); 5009 } 5010 5011 static MVT getLMUL1VT(MVT VT) { 5012 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5013 "Unexpected vector MVT"); 5014 return MVT::getScalableVectorVT( 5015 VT.getVectorElementType(), 5016 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5017 } 5018 5019 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5020 switch (ISDOpcode) { 5021 default: 5022 llvm_unreachable("Unhandled reduction"); 5023 case ISD::VECREDUCE_ADD: 5024 return RISCVISD::VECREDUCE_ADD_VL; 5025 case ISD::VECREDUCE_UMAX: 5026 return RISCVISD::VECREDUCE_UMAX_VL; 5027 case ISD::VECREDUCE_SMAX: 5028 return RISCVISD::VECREDUCE_SMAX_VL; 5029 case ISD::VECREDUCE_UMIN: 5030 return RISCVISD::VECREDUCE_UMIN_VL; 5031 case ISD::VECREDUCE_SMIN: 5032 return RISCVISD::VECREDUCE_SMIN_VL; 5033 case ISD::VECREDUCE_AND: 5034 return RISCVISD::VECREDUCE_AND_VL; 5035 case ISD::VECREDUCE_OR: 5036 return RISCVISD::VECREDUCE_OR_VL; 5037 case ISD::VECREDUCE_XOR: 5038 return RISCVISD::VECREDUCE_XOR_VL; 5039 } 5040 } 5041 5042 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5043 SelectionDAG &DAG, 5044 bool IsVP) const { 5045 SDLoc DL(Op); 5046 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5047 MVT VecVT = Vec.getSimpleValueType(); 5048 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5049 Op.getOpcode() == ISD::VECREDUCE_OR || 5050 Op.getOpcode() == ISD::VECREDUCE_XOR || 5051 Op.getOpcode() == ISD::VP_REDUCE_AND || 5052 Op.getOpcode() == ISD::VP_REDUCE_OR || 5053 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5054 "Unexpected reduction lowering"); 5055 5056 MVT XLenVT = Subtarget.getXLenVT(); 5057 assert(Op.getValueType() == XLenVT && 5058 "Expected reduction output to be legalized to XLenVT"); 5059 5060 MVT ContainerVT = VecVT; 5061 if (VecVT.isFixedLengthVector()) { 5062 ContainerVT = getContainerForFixedLengthVector(VecVT); 5063 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5064 } 5065 5066 SDValue Mask, VL; 5067 if (IsVP) { 5068 Mask = Op.getOperand(2); 5069 VL = Op.getOperand(3); 5070 } else { 5071 std::tie(Mask, VL) = 5072 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5073 } 5074 5075 unsigned BaseOpc; 5076 ISD::CondCode CC; 5077 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5078 5079 switch (Op.getOpcode()) { 5080 default: 5081 llvm_unreachable("Unhandled reduction"); 5082 case ISD::VECREDUCE_AND: 5083 case ISD::VP_REDUCE_AND: { 5084 // vcpop ~x == 0 5085 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5086 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5087 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5088 CC = ISD::SETEQ; 5089 BaseOpc = ISD::AND; 5090 break; 5091 } 5092 case ISD::VECREDUCE_OR: 5093 case ISD::VP_REDUCE_OR: 5094 // vcpop x != 0 5095 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5096 CC = ISD::SETNE; 5097 BaseOpc = ISD::OR; 5098 break; 5099 case ISD::VECREDUCE_XOR: 5100 case ISD::VP_REDUCE_XOR: { 5101 // ((vcpop x) & 1) != 0 5102 SDValue One = DAG.getConstant(1, DL, XLenVT); 5103 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5104 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5105 CC = ISD::SETNE; 5106 BaseOpc = ISD::XOR; 5107 break; 5108 } 5109 } 5110 5111 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5112 5113 if (!IsVP) 5114 return SetCC; 5115 5116 // Now include the start value in the operation. 5117 // Note that we must return the start value when no elements are operated 5118 // upon. The vcpop instructions we've emitted in each case above will return 5119 // 0 for an inactive vector, and so we've already received the neutral value: 5120 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5121 // can simply include the start value. 5122 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5123 } 5124 5125 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5126 SelectionDAG &DAG) const { 5127 SDLoc DL(Op); 5128 SDValue Vec = Op.getOperand(0); 5129 EVT VecEVT = Vec.getValueType(); 5130 5131 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5132 5133 // Due to ordering in legalize types we may have a vector type that needs to 5134 // be split. Do that manually so we can get down to a legal type. 5135 while (getTypeAction(*DAG.getContext(), VecEVT) == 5136 TargetLowering::TypeSplitVector) { 5137 SDValue Lo, Hi; 5138 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5139 VecEVT = Lo.getValueType(); 5140 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5141 } 5142 5143 // TODO: The type may need to be widened rather than split. Or widened before 5144 // it can be split. 5145 if (!isTypeLegal(VecEVT)) 5146 return SDValue(); 5147 5148 MVT VecVT = VecEVT.getSimpleVT(); 5149 MVT VecEltVT = VecVT.getVectorElementType(); 5150 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5151 5152 MVT ContainerVT = VecVT; 5153 if (VecVT.isFixedLengthVector()) { 5154 ContainerVT = getContainerForFixedLengthVector(VecVT); 5155 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5156 } 5157 5158 MVT M1VT = getLMUL1VT(ContainerVT); 5159 MVT XLenVT = Subtarget.getXLenVT(); 5160 5161 SDValue Mask, VL; 5162 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5163 5164 SDValue NeutralElem = 5165 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5166 SDValue IdentitySplat = 5167 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5168 M1VT, DL, DAG, Subtarget); 5169 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5170 IdentitySplat, Mask, VL); 5171 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5172 DAG.getConstant(0, DL, XLenVT)); 5173 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5174 } 5175 5176 // Given a reduction op, this function returns the matching reduction opcode, 5177 // the vector SDValue and the scalar SDValue required to lower this to a 5178 // RISCVISD node. 5179 static std::tuple<unsigned, SDValue, SDValue> 5180 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5181 SDLoc DL(Op); 5182 auto Flags = Op->getFlags(); 5183 unsigned Opcode = Op.getOpcode(); 5184 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5185 switch (Opcode) { 5186 default: 5187 llvm_unreachable("Unhandled reduction"); 5188 case ISD::VECREDUCE_FADD: { 5189 // Use positive zero if we can. It is cheaper to materialize. 5190 SDValue Zero = 5191 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5192 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5193 } 5194 case ISD::VECREDUCE_SEQ_FADD: 5195 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5196 Op.getOperand(0)); 5197 case ISD::VECREDUCE_FMIN: 5198 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5199 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5200 case ISD::VECREDUCE_FMAX: 5201 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5202 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5203 } 5204 } 5205 5206 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5207 SelectionDAG &DAG) const { 5208 SDLoc DL(Op); 5209 MVT VecEltVT = Op.getSimpleValueType(); 5210 5211 unsigned RVVOpcode; 5212 SDValue VectorVal, ScalarVal; 5213 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5214 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5215 MVT VecVT = VectorVal.getSimpleValueType(); 5216 5217 MVT ContainerVT = VecVT; 5218 if (VecVT.isFixedLengthVector()) { 5219 ContainerVT = getContainerForFixedLengthVector(VecVT); 5220 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5221 } 5222 5223 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5224 MVT XLenVT = Subtarget.getXLenVT(); 5225 5226 SDValue Mask, VL; 5227 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5228 5229 SDValue ScalarSplat = 5230 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5231 M1VT, DL, DAG, Subtarget); 5232 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5233 VectorVal, ScalarSplat, Mask, VL); 5234 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5235 DAG.getConstant(0, DL, XLenVT)); 5236 } 5237 5238 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5239 switch (ISDOpcode) { 5240 default: 5241 llvm_unreachable("Unhandled reduction"); 5242 case ISD::VP_REDUCE_ADD: 5243 return RISCVISD::VECREDUCE_ADD_VL; 5244 case ISD::VP_REDUCE_UMAX: 5245 return RISCVISD::VECREDUCE_UMAX_VL; 5246 case ISD::VP_REDUCE_SMAX: 5247 return RISCVISD::VECREDUCE_SMAX_VL; 5248 case ISD::VP_REDUCE_UMIN: 5249 return RISCVISD::VECREDUCE_UMIN_VL; 5250 case ISD::VP_REDUCE_SMIN: 5251 return RISCVISD::VECREDUCE_SMIN_VL; 5252 case ISD::VP_REDUCE_AND: 5253 return RISCVISD::VECREDUCE_AND_VL; 5254 case ISD::VP_REDUCE_OR: 5255 return RISCVISD::VECREDUCE_OR_VL; 5256 case ISD::VP_REDUCE_XOR: 5257 return RISCVISD::VECREDUCE_XOR_VL; 5258 case ISD::VP_REDUCE_FADD: 5259 return RISCVISD::VECREDUCE_FADD_VL; 5260 case ISD::VP_REDUCE_SEQ_FADD: 5261 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5262 case ISD::VP_REDUCE_FMAX: 5263 return RISCVISD::VECREDUCE_FMAX_VL; 5264 case ISD::VP_REDUCE_FMIN: 5265 return RISCVISD::VECREDUCE_FMIN_VL; 5266 } 5267 } 5268 5269 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5270 SelectionDAG &DAG) const { 5271 SDLoc DL(Op); 5272 SDValue Vec = Op.getOperand(1); 5273 EVT VecEVT = Vec.getValueType(); 5274 5275 // TODO: The type may need to be widened rather than split. Or widened before 5276 // it can be split. 5277 if (!isTypeLegal(VecEVT)) 5278 return SDValue(); 5279 5280 MVT VecVT = VecEVT.getSimpleVT(); 5281 MVT VecEltVT = VecVT.getVectorElementType(); 5282 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5283 5284 MVT ContainerVT = VecVT; 5285 if (VecVT.isFixedLengthVector()) { 5286 ContainerVT = getContainerForFixedLengthVector(VecVT); 5287 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5288 } 5289 5290 SDValue VL = Op.getOperand(3); 5291 SDValue Mask = Op.getOperand(2); 5292 5293 MVT M1VT = getLMUL1VT(ContainerVT); 5294 MVT XLenVT = Subtarget.getXLenVT(); 5295 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5296 5297 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5298 DAG.getConstant(1, DL, XLenVT), M1VT, 5299 DL, DAG, Subtarget); 5300 SDValue Reduction = 5301 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5302 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5303 DAG.getConstant(0, DL, XLenVT)); 5304 if (!VecVT.isInteger()) 5305 return Elt0; 5306 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5307 } 5308 5309 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5310 SelectionDAG &DAG) const { 5311 SDValue Vec = Op.getOperand(0); 5312 SDValue SubVec = Op.getOperand(1); 5313 MVT VecVT = Vec.getSimpleValueType(); 5314 MVT SubVecVT = SubVec.getSimpleValueType(); 5315 5316 SDLoc DL(Op); 5317 MVT XLenVT = Subtarget.getXLenVT(); 5318 unsigned OrigIdx = Op.getConstantOperandVal(2); 5319 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5320 5321 // We don't have the ability to slide mask vectors up indexed by their i1 5322 // elements; the smallest we can do is i8. Often we are able to bitcast to 5323 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5324 // into a scalable one, we might not necessarily have enough scalable 5325 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5326 if (SubVecVT.getVectorElementType() == MVT::i1 && 5327 (OrigIdx != 0 || !Vec.isUndef())) { 5328 if (VecVT.getVectorMinNumElements() >= 8 && 5329 SubVecVT.getVectorMinNumElements() >= 8) { 5330 assert(OrigIdx % 8 == 0 && "Invalid index"); 5331 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5332 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5333 "Unexpected mask vector lowering"); 5334 OrigIdx /= 8; 5335 SubVecVT = 5336 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5337 SubVecVT.isScalableVector()); 5338 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5339 VecVT.isScalableVector()); 5340 Vec = DAG.getBitcast(VecVT, Vec); 5341 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5342 } else { 5343 // We can't slide this mask vector up indexed by its i1 elements. 5344 // This poses a problem when we wish to insert a scalable vector which 5345 // can't be re-expressed as a larger type. Just choose the slow path and 5346 // extend to a larger type, then truncate back down. 5347 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5348 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5349 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5350 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5351 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5352 Op.getOperand(2)); 5353 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5354 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5355 } 5356 } 5357 5358 // If the subvector vector is a fixed-length type, we cannot use subregister 5359 // manipulation to simplify the codegen; we don't know which register of a 5360 // LMUL group contains the specific subvector as we only know the minimum 5361 // register size. Therefore we must slide the vector group up the full 5362 // amount. 5363 if (SubVecVT.isFixedLengthVector()) { 5364 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5365 return Op; 5366 MVT ContainerVT = VecVT; 5367 if (VecVT.isFixedLengthVector()) { 5368 ContainerVT = getContainerForFixedLengthVector(VecVT); 5369 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5370 } 5371 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5372 DAG.getUNDEF(ContainerVT), SubVec, 5373 DAG.getConstant(0, DL, XLenVT)); 5374 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5375 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5376 return DAG.getBitcast(Op.getValueType(), SubVec); 5377 } 5378 SDValue Mask = 5379 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5380 // Set the vector length to only the number of elements we care about. Note 5381 // that for slideup this includes the offset. 5382 SDValue VL = 5383 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5384 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5385 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5386 SubVec, SlideupAmt, Mask, VL); 5387 if (VecVT.isFixedLengthVector()) 5388 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5389 return DAG.getBitcast(Op.getValueType(), Slideup); 5390 } 5391 5392 unsigned SubRegIdx, RemIdx; 5393 std::tie(SubRegIdx, RemIdx) = 5394 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5395 VecVT, SubVecVT, OrigIdx, TRI); 5396 5397 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5398 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5399 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5400 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5401 5402 // 1. If the Idx has been completely eliminated and this subvector's size is 5403 // a vector register or a multiple thereof, or the surrounding elements are 5404 // undef, then this is a subvector insert which naturally aligns to a vector 5405 // register. These can easily be handled using subregister manipulation. 5406 // 2. If the subvector is smaller than a vector register, then the insertion 5407 // must preserve the undisturbed elements of the register. We do this by 5408 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5409 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5410 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5411 // LMUL=1 type back into the larger vector (resolving to another subregister 5412 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5413 // to avoid allocating a large register group to hold our subvector. 5414 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5415 return Op; 5416 5417 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5418 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5419 // (in our case undisturbed). This means we can set up a subvector insertion 5420 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5421 // size of the subvector. 5422 MVT InterSubVT = VecVT; 5423 SDValue AlignedExtract = Vec; 5424 unsigned AlignedIdx = OrigIdx - RemIdx; 5425 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5426 InterSubVT = getLMUL1VT(VecVT); 5427 // Extract a subvector equal to the nearest full vector register type. This 5428 // should resolve to a EXTRACT_SUBREG instruction. 5429 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5430 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5431 } 5432 5433 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5434 // For scalable vectors this must be further multiplied by vscale. 5435 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5436 5437 SDValue Mask, VL; 5438 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5439 5440 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5441 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5442 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5443 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5444 5445 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5446 DAG.getUNDEF(InterSubVT), SubVec, 5447 DAG.getConstant(0, DL, XLenVT)); 5448 5449 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5450 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5451 5452 // If required, insert this subvector back into the correct vector register. 5453 // This should resolve to an INSERT_SUBREG instruction. 5454 if (VecVT.bitsGT(InterSubVT)) 5455 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5456 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5457 5458 // We might have bitcast from a mask type: cast back to the original type if 5459 // required. 5460 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5461 } 5462 5463 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5464 SelectionDAG &DAG) const { 5465 SDValue Vec = Op.getOperand(0); 5466 MVT SubVecVT = Op.getSimpleValueType(); 5467 MVT VecVT = Vec.getSimpleValueType(); 5468 5469 SDLoc DL(Op); 5470 MVT XLenVT = Subtarget.getXLenVT(); 5471 unsigned OrigIdx = Op.getConstantOperandVal(1); 5472 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5473 5474 // We don't have the ability to slide mask vectors down indexed by their i1 5475 // elements; the smallest we can do is i8. Often we are able to bitcast to 5476 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5477 // from a scalable one, we might not necessarily have enough scalable 5478 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5479 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5480 if (VecVT.getVectorMinNumElements() >= 8 && 5481 SubVecVT.getVectorMinNumElements() >= 8) { 5482 assert(OrigIdx % 8 == 0 && "Invalid index"); 5483 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5484 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5485 "Unexpected mask vector lowering"); 5486 OrigIdx /= 8; 5487 SubVecVT = 5488 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5489 SubVecVT.isScalableVector()); 5490 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5491 VecVT.isScalableVector()); 5492 Vec = DAG.getBitcast(VecVT, Vec); 5493 } else { 5494 // We can't slide this mask vector down, indexed by its i1 elements. 5495 // This poses a problem when we wish to extract a scalable vector which 5496 // can't be re-expressed as a larger type. Just choose the slow path and 5497 // extend to a larger type, then truncate back down. 5498 // TODO: We could probably improve this when extracting certain fixed 5499 // from fixed, where we can extract as i8 and shift the correct element 5500 // right to reach the desired subvector? 5501 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5502 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5503 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5504 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5505 Op.getOperand(1)); 5506 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5507 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5508 } 5509 } 5510 5511 // If the subvector vector is a fixed-length type, we cannot use subregister 5512 // manipulation to simplify the codegen; we don't know which register of a 5513 // LMUL group contains the specific subvector as we only know the minimum 5514 // register size. Therefore we must slide the vector group down the full 5515 // amount. 5516 if (SubVecVT.isFixedLengthVector()) { 5517 // With an index of 0 this is a cast-like subvector, which can be performed 5518 // with subregister operations. 5519 if (OrigIdx == 0) 5520 return Op; 5521 MVT ContainerVT = VecVT; 5522 if (VecVT.isFixedLengthVector()) { 5523 ContainerVT = getContainerForFixedLengthVector(VecVT); 5524 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5525 } 5526 SDValue Mask = 5527 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5528 // Set the vector length to only the number of elements we care about. This 5529 // avoids sliding down elements we're going to discard straight away. 5530 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5531 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5532 SDValue Slidedown = 5533 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5534 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5535 // Now we can use a cast-like subvector extract to get the result. 5536 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5537 DAG.getConstant(0, DL, XLenVT)); 5538 return DAG.getBitcast(Op.getValueType(), Slidedown); 5539 } 5540 5541 unsigned SubRegIdx, RemIdx; 5542 std::tie(SubRegIdx, RemIdx) = 5543 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5544 VecVT, SubVecVT, OrigIdx, TRI); 5545 5546 // If the Idx has been completely eliminated then this is a subvector extract 5547 // which naturally aligns to a vector register. These can easily be handled 5548 // using subregister manipulation. 5549 if (RemIdx == 0) 5550 return Op; 5551 5552 // Else we must shift our vector register directly to extract the subvector. 5553 // Do this using VSLIDEDOWN. 5554 5555 // If the vector type is an LMUL-group type, extract a subvector equal to the 5556 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5557 // instruction. 5558 MVT InterSubVT = VecVT; 5559 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5560 InterSubVT = getLMUL1VT(VecVT); 5561 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5562 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5563 } 5564 5565 // Slide this vector register down by the desired number of elements in order 5566 // to place the desired subvector starting at element 0. 5567 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5568 // For scalable vectors this must be further multiplied by vscale. 5569 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5570 5571 SDValue Mask, VL; 5572 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5573 SDValue Slidedown = 5574 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5575 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5576 5577 // Now the vector is in the right position, extract our final subvector. This 5578 // should resolve to a COPY. 5579 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5580 DAG.getConstant(0, DL, XLenVT)); 5581 5582 // We might have bitcast from a mask type: cast back to the original type if 5583 // required. 5584 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5585 } 5586 5587 // Lower step_vector to the vid instruction. Any non-identity step value must 5588 // be accounted for my manual expansion. 5589 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5590 SelectionDAG &DAG) const { 5591 SDLoc DL(Op); 5592 MVT VT = Op.getSimpleValueType(); 5593 MVT XLenVT = Subtarget.getXLenVT(); 5594 SDValue Mask, VL; 5595 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5596 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5597 uint64_t StepValImm = Op.getConstantOperandVal(0); 5598 if (StepValImm != 1) { 5599 if (isPowerOf2_64(StepValImm)) { 5600 SDValue StepVal = 5601 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5602 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5603 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5604 } else { 5605 SDValue StepVal = lowerScalarSplat( 5606 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5607 VL, VT, DL, DAG, Subtarget); 5608 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5609 } 5610 } 5611 return StepVec; 5612 } 5613 5614 // Implement vector_reverse using vrgather.vv with indices determined by 5615 // subtracting the id of each element from (VLMAX-1). This will convert 5616 // the indices like so: 5617 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5618 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5619 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5620 SelectionDAG &DAG) const { 5621 SDLoc DL(Op); 5622 MVT VecVT = Op.getSimpleValueType(); 5623 unsigned EltSize = VecVT.getScalarSizeInBits(); 5624 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5625 5626 unsigned MaxVLMAX = 0; 5627 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5628 if (VectorBitsMax != 0) 5629 MaxVLMAX = 5630 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5631 5632 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5633 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5634 5635 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5636 // to use vrgatherei16.vv. 5637 // TODO: It's also possible to use vrgatherei16.vv for other types to 5638 // decrease register width for the index calculation. 5639 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5640 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5641 // Reverse each half, then reassemble them in reverse order. 5642 // NOTE: It's also possible that after splitting that VLMAX no longer 5643 // requires vrgatherei16.vv. 5644 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5645 SDValue Lo, Hi; 5646 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5647 EVT LoVT, HiVT; 5648 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5649 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5650 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5651 // Reassemble the low and high pieces reversed. 5652 // FIXME: This is a CONCAT_VECTORS. 5653 SDValue Res = 5654 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5655 DAG.getIntPtrConstant(0, DL)); 5656 return DAG.getNode( 5657 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5658 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5659 } 5660 5661 // Just promote the int type to i16 which will double the LMUL. 5662 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5663 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5664 } 5665 5666 MVT XLenVT = Subtarget.getXLenVT(); 5667 SDValue Mask, VL; 5668 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5669 5670 // Calculate VLMAX-1 for the desired SEW. 5671 unsigned MinElts = VecVT.getVectorMinNumElements(); 5672 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5673 DAG.getConstant(MinElts, DL, XLenVT)); 5674 SDValue VLMinus1 = 5675 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5676 5677 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5678 bool IsRV32E64 = 5679 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5680 SDValue SplatVL; 5681 if (!IsRV32E64) 5682 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5683 else 5684 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5685 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5686 5687 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5688 SDValue Indices = 5689 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5690 5691 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5692 } 5693 5694 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5695 SelectionDAG &DAG) const { 5696 SDLoc DL(Op); 5697 SDValue V1 = Op.getOperand(0); 5698 SDValue V2 = Op.getOperand(1); 5699 MVT XLenVT = Subtarget.getXLenVT(); 5700 MVT VecVT = Op.getSimpleValueType(); 5701 5702 unsigned MinElts = VecVT.getVectorMinNumElements(); 5703 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5704 DAG.getConstant(MinElts, DL, XLenVT)); 5705 5706 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5707 SDValue DownOffset, UpOffset; 5708 if (ImmValue >= 0) { 5709 // The operand is a TargetConstant, we need to rebuild it as a regular 5710 // constant. 5711 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5712 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5713 } else { 5714 // The operand is a TargetConstant, we need to rebuild it as a regular 5715 // constant rather than negating the original operand. 5716 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5717 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5718 } 5719 5720 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5721 5722 SDValue SlideDown = 5723 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5724 DownOffset, TrueMask, UpOffset); 5725 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5726 TrueMask, 5727 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5728 } 5729 5730 SDValue 5731 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5732 SelectionDAG &DAG) const { 5733 SDLoc DL(Op); 5734 auto *Load = cast<LoadSDNode>(Op); 5735 5736 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5737 Load->getMemoryVT(), 5738 *Load->getMemOperand()) && 5739 "Expecting a correctly-aligned load"); 5740 5741 MVT VT = Op.getSimpleValueType(); 5742 MVT XLenVT = Subtarget.getXLenVT(); 5743 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5744 5745 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5746 5747 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5748 SDValue IntID = DAG.getTargetConstant( 5749 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5750 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5751 if (!IsMaskOp) 5752 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5753 Ops.push_back(Load->getBasePtr()); 5754 Ops.push_back(VL); 5755 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5756 SDValue NewLoad = 5757 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5758 Load->getMemoryVT(), Load->getMemOperand()); 5759 5760 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5761 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5762 } 5763 5764 SDValue 5765 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5766 SelectionDAG &DAG) const { 5767 SDLoc DL(Op); 5768 auto *Store = cast<StoreSDNode>(Op); 5769 5770 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5771 Store->getMemoryVT(), 5772 *Store->getMemOperand()) && 5773 "Expecting a correctly-aligned store"); 5774 5775 SDValue StoreVal = Store->getValue(); 5776 MVT VT = StoreVal.getSimpleValueType(); 5777 MVT XLenVT = Subtarget.getXLenVT(); 5778 5779 // If the size less than a byte, we need to pad with zeros to make a byte. 5780 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5781 VT = MVT::v8i1; 5782 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5783 DAG.getConstant(0, DL, VT), StoreVal, 5784 DAG.getIntPtrConstant(0, DL)); 5785 } 5786 5787 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5788 5789 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5790 5791 SDValue NewValue = 5792 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5793 5794 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5795 SDValue IntID = DAG.getTargetConstant( 5796 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5797 return DAG.getMemIntrinsicNode( 5798 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5799 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5800 Store->getMemoryVT(), Store->getMemOperand()); 5801 } 5802 5803 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5804 SelectionDAG &DAG) const { 5805 SDLoc DL(Op); 5806 MVT VT = Op.getSimpleValueType(); 5807 5808 const auto *MemSD = cast<MemSDNode>(Op); 5809 EVT MemVT = MemSD->getMemoryVT(); 5810 MachineMemOperand *MMO = MemSD->getMemOperand(); 5811 SDValue Chain = MemSD->getChain(); 5812 SDValue BasePtr = MemSD->getBasePtr(); 5813 5814 SDValue Mask, PassThru, VL; 5815 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5816 Mask = VPLoad->getMask(); 5817 PassThru = DAG.getUNDEF(VT); 5818 VL = VPLoad->getVectorLength(); 5819 } else { 5820 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5821 Mask = MLoad->getMask(); 5822 PassThru = MLoad->getPassThru(); 5823 } 5824 5825 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5826 5827 MVT XLenVT = Subtarget.getXLenVT(); 5828 5829 MVT ContainerVT = VT; 5830 if (VT.isFixedLengthVector()) { 5831 ContainerVT = getContainerForFixedLengthVector(VT); 5832 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5833 if (!IsUnmasked) { 5834 MVT MaskVT = getMaskTypeFor(ContainerVT); 5835 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5836 } 5837 } 5838 5839 if (!VL) 5840 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5841 5842 unsigned IntID = 5843 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5844 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5845 if (IsUnmasked) 5846 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5847 else 5848 Ops.push_back(PassThru); 5849 Ops.push_back(BasePtr); 5850 if (!IsUnmasked) 5851 Ops.push_back(Mask); 5852 Ops.push_back(VL); 5853 if (!IsUnmasked) 5854 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5855 5856 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5857 5858 SDValue Result = 5859 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5860 Chain = Result.getValue(1); 5861 5862 if (VT.isFixedLengthVector()) 5863 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5864 5865 return DAG.getMergeValues({Result, Chain}, DL); 5866 } 5867 5868 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5869 SelectionDAG &DAG) const { 5870 SDLoc DL(Op); 5871 5872 const auto *MemSD = cast<MemSDNode>(Op); 5873 EVT MemVT = MemSD->getMemoryVT(); 5874 MachineMemOperand *MMO = MemSD->getMemOperand(); 5875 SDValue Chain = MemSD->getChain(); 5876 SDValue BasePtr = MemSD->getBasePtr(); 5877 SDValue Val, Mask, VL; 5878 5879 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5880 Val = VPStore->getValue(); 5881 Mask = VPStore->getMask(); 5882 VL = VPStore->getVectorLength(); 5883 } else { 5884 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5885 Val = MStore->getValue(); 5886 Mask = MStore->getMask(); 5887 } 5888 5889 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5890 5891 MVT VT = Val.getSimpleValueType(); 5892 MVT XLenVT = Subtarget.getXLenVT(); 5893 5894 MVT ContainerVT = VT; 5895 if (VT.isFixedLengthVector()) { 5896 ContainerVT = getContainerForFixedLengthVector(VT); 5897 5898 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5899 if (!IsUnmasked) { 5900 MVT MaskVT = getMaskTypeFor(ContainerVT); 5901 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5902 } 5903 } 5904 5905 if (!VL) 5906 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5907 5908 unsigned IntID = 5909 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5910 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5911 Ops.push_back(Val); 5912 Ops.push_back(BasePtr); 5913 if (!IsUnmasked) 5914 Ops.push_back(Mask); 5915 Ops.push_back(VL); 5916 5917 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5918 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5919 } 5920 5921 SDValue 5922 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5923 SelectionDAG &DAG) const { 5924 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5925 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5926 5927 MVT VT = Op.getSimpleValueType(); 5928 5929 SDValue Op1 = 5930 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5931 SDValue Op2 = 5932 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5933 5934 SDLoc DL(Op); 5935 SDValue VL = 5936 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5937 5938 MVT MaskVT = getMaskTypeFor(ContainerVT); 5939 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5940 5941 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5942 Op.getOperand(2), Mask, VL); 5943 5944 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5945 } 5946 5947 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5948 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5949 MVT VT = Op.getSimpleValueType(); 5950 5951 if (VT.getVectorElementType() == MVT::i1) 5952 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5953 5954 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5955 } 5956 5957 SDValue 5958 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5959 SelectionDAG &DAG) const { 5960 unsigned Opc; 5961 switch (Op.getOpcode()) { 5962 default: llvm_unreachable("Unexpected opcode!"); 5963 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5964 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5965 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5966 } 5967 5968 return lowerToScalableOp(Op, DAG, Opc); 5969 } 5970 5971 // Lower vector ABS to smax(X, sub(0, X)). 5972 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5973 SDLoc DL(Op); 5974 MVT VT = Op.getSimpleValueType(); 5975 SDValue X = Op.getOperand(0); 5976 5977 assert(VT.isFixedLengthVector() && "Unexpected type"); 5978 5979 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5980 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5981 5982 SDValue Mask, VL; 5983 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5984 5985 SDValue SplatZero = DAG.getNode( 5986 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5987 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5988 SDValue NegX = 5989 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5990 SDValue Max = 5991 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5992 5993 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5994 } 5995 5996 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5997 SDValue Op, SelectionDAG &DAG) const { 5998 SDLoc DL(Op); 5999 MVT VT = Op.getSimpleValueType(); 6000 SDValue Mag = Op.getOperand(0); 6001 SDValue Sign = Op.getOperand(1); 6002 assert(Mag.getValueType() == Sign.getValueType() && 6003 "Can only handle COPYSIGN with matching types."); 6004 6005 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6006 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6007 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6008 6009 SDValue Mask, VL; 6010 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6011 6012 SDValue CopySign = 6013 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6014 6015 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6016 } 6017 6018 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6019 SDValue Op, SelectionDAG &DAG) const { 6020 MVT VT = Op.getSimpleValueType(); 6021 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6022 6023 MVT I1ContainerVT = 6024 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6025 6026 SDValue CC = 6027 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6028 SDValue Op1 = 6029 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6030 SDValue Op2 = 6031 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6032 6033 SDLoc DL(Op); 6034 SDValue Mask, VL; 6035 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6036 6037 SDValue Select = 6038 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6039 6040 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6041 } 6042 6043 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6044 unsigned NewOpc, 6045 bool HasMask) const { 6046 MVT VT = Op.getSimpleValueType(); 6047 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6048 6049 // Create list of operands by converting existing ones to scalable types. 6050 SmallVector<SDValue, 6> Ops; 6051 for (const SDValue &V : Op->op_values()) { 6052 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6053 6054 // Pass through non-vector operands. 6055 if (!V.getValueType().isVector()) { 6056 Ops.push_back(V); 6057 continue; 6058 } 6059 6060 // "cast" fixed length vector to a scalable vector. 6061 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6062 "Only fixed length vectors are supported!"); 6063 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6064 } 6065 6066 SDLoc DL(Op); 6067 SDValue Mask, VL; 6068 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6069 if (HasMask) 6070 Ops.push_back(Mask); 6071 Ops.push_back(VL); 6072 6073 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6074 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6075 } 6076 6077 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6078 // * Operands of each node are assumed to be in the same order. 6079 // * The EVL operand is promoted from i32 to i64 on RV64. 6080 // * Fixed-length vectors are converted to their scalable-vector container 6081 // types. 6082 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6083 unsigned RISCVISDOpc) const { 6084 SDLoc DL(Op); 6085 MVT VT = Op.getSimpleValueType(); 6086 SmallVector<SDValue, 4> Ops; 6087 6088 for (const auto &OpIdx : enumerate(Op->ops())) { 6089 SDValue V = OpIdx.value(); 6090 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6091 // Pass through operands which aren't fixed-length vectors. 6092 if (!V.getValueType().isFixedLengthVector()) { 6093 Ops.push_back(V); 6094 continue; 6095 } 6096 // "cast" fixed length vector to a scalable vector. 6097 MVT OpVT = V.getSimpleValueType(); 6098 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6099 assert(useRVVForFixedLengthVectorVT(OpVT) && 6100 "Only fixed length vectors are supported!"); 6101 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6102 } 6103 6104 if (!VT.isFixedLengthVector()) 6105 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6106 6107 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6108 6109 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6110 6111 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6112 } 6113 6114 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6115 SelectionDAG &DAG) const { 6116 SDLoc DL(Op); 6117 MVT VT = Op.getSimpleValueType(); 6118 6119 SDValue Src = Op.getOperand(0); 6120 // NOTE: Mask is dropped. 6121 SDValue VL = Op.getOperand(2); 6122 6123 MVT ContainerVT = VT; 6124 if (VT.isFixedLengthVector()) { 6125 ContainerVT = getContainerForFixedLengthVector(VT); 6126 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6127 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6128 } 6129 6130 MVT XLenVT = Subtarget.getXLenVT(); 6131 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6132 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6133 DAG.getUNDEF(ContainerVT), Zero, VL); 6134 6135 SDValue SplatValue = DAG.getConstant( 6136 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6137 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6138 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6139 6140 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6141 Splat, ZeroSplat, VL); 6142 if (!VT.isFixedLengthVector()) 6143 return Result; 6144 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6145 } 6146 6147 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6148 SelectionDAG &DAG) const { 6149 SDLoc DL(Op); 6150 MVT VT = Op.getSimpleValueType(); 6151 6152 SDValue Op1 = Op.getOperand(0); 6153 SDValue Op2 = Op.getOperand(1); 6154 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6155 // NOTE: Mask is dropped. 6156 SDValue VL = Op.getOperand(4); 6157 6158 MVT ContainerVT = VT; 6159 if (VT.isFixedLengthVector()) { 6160 ContainerVT = getContainerForFixedLengthVector(VT); 6161 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6162 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6163 } 6164 6165 SDValue Result; 6166 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6167 6168 switch (Condition) { 6169 default: 6170 break; 6171 // X != Y --> (X^Y) 6172 case ISD::SETNE: 6173 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6174 break; 6175 // X == Y --> ~(X^Y) 6176 case ISD::SETEQ: { 6177 SDValue Temp = 6178 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6179 Result = 6180 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6181 break; 6182 } 6183 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6184 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6185 case ISD::SETGT: 6186 case ISD::SETULT: { 6187 SDValue Temp = 6188 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6189 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6190 break; 6191 } 6192 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6193 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6194 case ISD::SETLT: 6195 case ISD::SETUGT: { 6196 SDValue Temp = 6197 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6198 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6199 break; 6200 } 6201 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6202 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6203 case ISD::SETGE: 6204 case ISD::SETULE: { 6205 SDValue Temp = 6206 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6207 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6208 break; 6209 } 6210 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6211 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6212 case ISD::SETLE: 6213 case ISD::SETUGE: { 6214 SDValue Temp = 6215 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6216 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6217 break; 6218 } 6219 } 6220 6221 if (!VT.isFixedLengthVector()) 6222 return Result; 6223 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6224 } 6225 6226 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6227 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6228 unsigned RISCVISDOpc) const { 6229 SDLoc DL(Op); 6230 6231 SDValue Src = Op.getOperand(0); 6232 SDValue Mask = Op.getOperand(1); 6233 SDValue VL = Op.getOperand(2); 6234 6235 MVT DstVT = Op.getSimpleValueType(); 6236 MVT SrcVT = Src.getSimpleValueType(); 6237 if (DstVT.isFixedLengthVector()) { 6238 DstVT = getContainerForFixedLengthVector(DstVT); 6239 SrcVT = getContainerForFixedLengthVector(SrcVT); 6240 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6241 MVT MaskVT = getMaskTypeFor(DstVT); 6242 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6243 } 6244 6245 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6246 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6247 ? RISCVISD::VSEXT_VL 6248 : RISCVISD::VZEXT_VL; 6249 6250 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6251 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6252 6253 SDValue Result; 6254 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6255 if (SrcVT.isInteger()) { 6256 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6257 6258 // Do we need to do any pre-widening before converting? 6259 if (SrcEltSize == 1) { 6260 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6261 MVT XLenVT = Subtarget.getXLenVT(); 6262 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6263 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6264 DAG.getUNDEF(IntVT), Zero, VL); 6265 SDValue One = DAG.getConstant( 6266 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6267 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6268 DAG.getUNDEF(IntVT), One, VL); 6269 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6270 ZeroSplat, VL); 6271 } else if (DstEltSize > (2 * SrcEltSize)) { 6272 // Widen before converting. 6273 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6274 DstVT.getVectorElementCount()); 6275 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6276 } 6277 6278 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6279 } else { 6280 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6281 "Wrong input/output vector types"); 6282 6283 // Convert f16 to f32 then convert f32 to i64. 6284 if (DstEltSize > (2 * SrcEltSize)) { 6285 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6286 MVT InterimFVT = 6287 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6288 Src = 6289 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6290 } 6291 6292 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6293 } 6294 } else { // Narrowing + Conversion 6295 if (SrcVT.isInteger()) { 6296 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6297 // First do a narrowing convert to an FP type half the size, then round 6298 // the FP type to a small FP type if needed. 6299 6300 MVT InterimFVT = DstVT; 6301 if (SrcEltSize > (2 * DstEltSize)) { 6302 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6303 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6304 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6305 } 6306 6307 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6308 6309 if (InterimFVT != DstVT) { 6310 Src = Result; 6311 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6312 } 6313 } else { 6314 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6315 "Wrong input/output vector types"); 6316 // First do a narrowing conversion to an integer half the size, then 6317 // truncate if needed. 6318 6319 if (DstEltSize == 1) { 6320 // First convert to the same size integer, then convert to mask using 6321 // setcc. 6322 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6323 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6324 DstVT.getVectorElementCount()); 6325 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6326 6327 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6328 // otherwise the conversion was undefined. 6329 MVT XLenVT = Subtarget.getXLenVT(); 6330 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6331 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6332 DAG.getUNDEF(InterimIVT), SplatZero); 6333 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6334 DAG.getCondCode(ISD::SETNE), Mask, VL); 6335 } else { 6336 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6337 DstVT.getVectorElementCount()); 6338 6339 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6340 6341 while (InterimIVT != DstVT) { 6342 SrcEltSize /= 2; 6343 Src = Result; 6344 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6345 DstVT.getVectorElementCount()); 6346 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6347 Src, Mask, VL); 6348 } 6349 } 6350 } 6351 } 6352 6353 MVT VT = Op.getSimpleValueType(); 6354 if (!VT.isFixedLengthVector()) 6355 return Result; 6356 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6357 } 6358 6359 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6360 unsigned MaskOpc, 6361 unsigned VecOpc) const { 6362 MVT VT = Op.getSimpleValueType(); 6363 if (VT.getVectorElementType() != MVT::i1) 6364 return lowerVPOp(Op, DAG, VecOpc); 6365 6366 // It is safe to drop mask parameter as masked-off elements are undef. 6367 SDValue Op1 = Op->getOperand(0); 6368 SDValue Op2 = Op->getOperand(1); 6369 SDValue VL = Op->getOperand(3); 6370 6371 MVT ContainerVT = VT; 6372 const bool IsFixed = VT.isFixedLengthVector(); 6373 if (IsFixed) { 6374 ContainerVT = getContainerForFixedLengthVector(VT); 6375 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6376 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6377 } 6378 6379 SDLoc DL(Op); 6380 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6381 if (!IsFixed) 6382 return Val; 6383 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6384 } 6385 6386 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6387 // matched to a RVV indexed load. The RVV indexed load instructions only 6388 // support the "unsigned unscaled" addressing mode; indices are implicitly 6389 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6390 // signed or scaled indexing is extended to the XLEN value type and scaled 6391 // accordingly. 6392 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6393 SelectionDAG &DAG) const { 6394 SDLoc DL(Op); 6395 MVT VT = Op.getSimpleValueType(); 6396 6397 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6398 EVT MemVT = MemSD->getMemoryVT(); 6399 MachineMemOperand *MMO = MemSD->getMemOperand(); 6400 SDValue Chain = MemSD->getChain(); 6401 SDValue BasePtr = MemSD->getBasePtr(); 6402 6403 ISD::LoadExtType LoadExtType; 6404 SDValue Index, Mask, PassThru, VL; 6405 6406 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6407 Index = VPGN->getIndex(); 6408 Mask = VPGN->getMask(); 6409 PassThru = DAG.getUNDEF(VT); 6410 VL = VPGN->getVectorLength(); 6411 // VP doesn't support extending loads. 6412 LoadExtType = ISD::NON_EXTLOAD; 6413 } else { 6414 // Else it must be a MGATHER. 6415 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6416 Index = MGN->getIndex(); 6417 Mask = MGN->getMask(); 6418 PassThru = MGN->getPassThru(); 6419 LoadExtType = MGN->getExtensionType(); 6420 } 6421 6422 MVT IndexVT = Index.getSimpleValueType(); 6423 MVT XLenVT = Subtarget.getXLenVT(); 6424 6425 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6426 "Unexpected VTs!"); 6427 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6428 // Targets have to explicitly opt-in for extending vector loads. 6429 assert(LoadExtType == ISD::NON_EXTLOAD && 6430 "Unexpected extending MGATHER/VP_GATHER"); 6431 (void)LoadExtType; 6432 6433 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6434 // the selection of the masked intrinsics doesn't do this for us. 6435 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6436 6437 MVT ContainerVT = VT; 6438 if (VT.isFixedLengthVector()) { 6439 ContainerVT = getContainerForFixedLengthVector(VT); 6440 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6441 ContainerVT.getVectorElementCount()); 6442 6443 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6444 6445 if (!IsUnmasked) { 6446 MVT MaskVT = getMaskTypeFor(ContainerVT); 6447 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6448 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6449 } 6450 } 6451 6452 if (!VL) 6453 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6454 6455 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6456 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6457 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6458 VL); 6459 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6460 TrueMask, VL); 6461 } 6462 6463 unsigned IntID = 6464 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6465 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6466 if (IsUnmasked) 6467 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6468 else 6469 Ops.push_back(PassThru); 6470 Ops.push_back(BasePtr); 6471 Ops.push_back(Index); 6472 if (!IsUnmasked) 6473 Ops.push_back(Mask); 6474 Ops.push_back(VL); 6475 if (!IsUnmasked) 6476 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6477 6478 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6479 SDValue Result = 6480 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6481 Chain = Result.getValue(1); 6482 6483 if (VT.isFixedLengthVector()) 6484 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6485 6486 return DAG.getMergeValues({Result, Chain}, DL); 6487 } 6488 6489 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6490 // matched to a RVV indexed store. The RVV indexed store instructions only 6491 // support the "unsigned unscaled" addressing mode; indices are implicitly 6492 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6493 // signed or scaled indexing is extended to the XLEN value type and scaled 6494 // accordingly. 6495 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6496 SelectionDAG &DAG) const { 6497 SDLoc DL(Op); 6498 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6499 EVT MemVT = MemSD->getMemoryVT(); 6500 MachineMemOperand *MMO = MemSD->getMemOperand(); 6501 SDValue Chain = MemSD->getChain(); 6502 SDValue BasePtr = MemSD->getBasePtr(); 6503 6504 bool IsTruncatingStore = false; 6505 SDValue Index, Mask, Val, VL; 6506 6507 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6508 Index = VPSN->getIndex(); 6509 Mask = VPSN->getMask(); 6510 Val = VPSN->getValue(); 6511 VL = VPSN->getVectorLength(); 6512 // VP doesn't support truncating stores. 6513 IsTruncatingStore = false; 6514 } else { 6515 // Else it must be a MSCATTER. 6516 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6517 Index = MSN->getIndex(); 6518 Mask = MSN->getMask(); 6519 Val = MSN->getValue(); 6520 IsTruncatingStore = MSN->isTruncatingStore(); 6521 } 6522 6523 MVT VT = Val.getSimpleValueType(); 6524 MVT IndexVT = Index.getSimpleValueType(); 6525 MVT XLenVT = Subtarget.getXLenVT(); 6526 6527 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6528 "Unexpected VTs!"); 6529 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6530 // Targets have to explicitly opt-in for extending vector loads and 6531 // truncating vector stores. 6532 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6533 (void)IsTruncatingStore; 6534 6535 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6536 // the selection of the masked intrinsics doesn't do this for us. 6537 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6538 6539 MVT ContainerVT = VT; 6540 if (VT.isFixedLengthVector()) { 6541 ContainerVT = getContainerForFixedLengthVector(VT); 6542 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6543 ContainerVT.getVectorElementCount()); 6544 6545 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6546 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6547 6548 if (!IsUnmasked) { 6549 MVT MaskVT = getMaskTypeFor(ContainerVT); 6550 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6551 } 6552 } 6553 6554 if (!VL) 6555 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6556 6557 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6558 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6559 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6560 VL); 6561 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6562 TrueMask, VL); 6563 } 6564 6565 unsigned IntID = 6566 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6567 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6568 Ops.push_back(Val); 6569 Ops.push_back(BasePtr); 6570 Ops.push_back(Index); 6571 if (!IsUnmasked) 6572 Ops.push_back(Mask); 6573 Ops.push_back(VL); 6574 6575 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6576 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6577 } 6578 6579 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6580 SelectionDAG &DAG) const { 6581 const MVT XLenVT = Subtarget.getXLenVT(); 6582 SDLoc DL(Op); 6583 SDValue Chain = Op->getOperand(0); 6584 SDValue SysRegNo = DAG.getTargetConstant( 6585 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6586 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6587 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6588 6589 // Encoding used for rounding mode in RISCV differs from that used in 6590 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6591 // table, which consists of a sequence of 4-bit fields, each representing 6592 // corresponding FLT_ROUNDS mode. 6593 static const int Table = 6594 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6595 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6596 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6597 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6598 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6599 6600 SDValue Shift = 6601 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6602 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6603 DAG.getConstant(Table, DL, XLenVT), Shift); 6604 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6605 DAG.getConstant(7, DL, XLenVT)); 6606 6607 return DAG.getMergeValues({Masked, Chain}, DL); 6608 } 6609 6610 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6611 SelectionDAG &DAG) const { 6612 const MVT XLenVT = Subtarget.getXLenVT(); 6613 SDLoc DL(Op); 6614 SDValue Chain = Op->getOperand(0); 6615 SDValue RMValue = Op->getOperand(1); 6616 SDValue SysRegNo = DAG.getTargetConstant( 6617 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6618 6619 // Encoding used for rounding mode in RISCV differs from that used in 6620 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6621 // a table, which consists of a sequence of 4-bit fields, each representing 6622 // corresponding RISCV mode. 6623 static const unsigned Table = 6624 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6625 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6626 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6627 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6628 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6629 6630 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6631 DAG.getConstant(2, DL, XLenVT)); 6632 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6633 DAG.getConstant(Table, DL, XLenVT), Shift); 6634 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6635 DAG.getConstant(0x7, DL, XLenVT)); 6636 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6637 RMValue); 6638 } 6639 6640 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6641 SelectionDAG &DAG) const { 6642 MachineFunction &MF = DAG.getMachineFunction(); 6643 6644 bool isRISCV64 = Subtarget.is64Bit(); 6645 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6646 6647 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6648 return DAG.getFrameIndex(FI, PtrVT); 6649 } 6650 6651 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6652 switch (IntNo) { 6653 default: 6654 llvm_unreachable("Unexpected Intrinsic"); 6655 case Intrinsic::riscv_bcompress: 6656 return RISCVISD::BCOMPRESSW; 6657 case Intrinsic::riscv_bdecompress: 6658 return RISCVISD::BDECOMPRESSW; 6659 case Intrinsic::riscv_bfp: 6660 return RISCVISD::BFPW; 6661 case Intrinsic::riscv_fsl: 6662 return RISCVISD::FSLW; 6663 case Intrinsic::riscv_fsr: 6664 return RISCVISD::FSRW; 6665 } 6666 } 6667 6668 // Converts the given intrinsic to a i64 operation with any extension. 6669 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6670 unsigned IntNo) { 6671 SDLoc DL(N); 6672 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6673 // Deal with the Instruction Operands 6674 SmallVector<SDValue, 3> NewOps; 6675 for (SDValue Op : drop_begin(N->ops())) 6676 // Promote the operand to i64 type 6677 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6678 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6679 // ReplaceNodeResults requires we maintain the same type for the return value. 6680 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6681 } 6682 6683 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6684 // form of the given Opcode. 6685 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6686 switch (Opcode) { 6687 default: 6688 llvm_unreachable("Unexpected opcode"); 6689 case ISD::SHL: 6690 return RISCVISD::SLLW; 6691 case ISD::SRA: 6692 return RISCVISD::SRAW; 6693 case ISD::SRL: 6694 return RISCVISD::SRLW; 6695 case ISD::SDIV: 6696 return RISCVISD::DIVW; 6697 case ISD::UDIV: 6698 return RISCVISD::DIVUW; 6699 case ISD::UREM: 6700 return RISCVISD::REMUW; 6701 case ISD::ROTL: 6702 return RISCVISD::ROLW; 6703 case ISD::ROTR: 6704 return RISCVISD::RORW; 6705 } 6706 } 6707 6708 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6709 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6710 // otherwise be promoted to i64, making it difficult to select the 6711 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6712 // type i8/i16/i32 is lost. 6713 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6714 unsigned ExtOpc = ISD::ANY_EXTEND) { 6715 SDLoc DL(N); 6716 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6717 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6718 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6719 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6720 // ReplaceNodeResults requires we maintain the same type for the return value. 6721 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6722 } 6723 6724 // Converts the given 32-bit operation to a i64 operation with signed extension 6725 // semantic to reduce the signed extension instructions. 6726 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6727 SDLoc DL(N); 6728 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6729 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6730 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6731 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6732 DAG.getValueType(MVT::i32)); 6733 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6734 } 6735 6736 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6737 SmallVectorImpl<SDValue> &Results, 6738 SelectionDAG &DAG) const { 6739 SDLoc DL(N); 6740 switch (N->getOpcode()) { 6741 default: 6742 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6743 case ISD::STRICT_FP_TO_SINT: 6744 case ISD::STRICT_FP_TO_UINT: 6745 case ISD::FP_TO_SINT: 6746 case ISD::FP_TO_UINT: { 6747 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6748 "Unexpected custom legalisation"); 6749 bool IsStrict = N->isStrictFPOpcode(); 6750 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6751 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6752 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6753 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6754 TargetLowering::TypeSoftenFloat) { 6755 if (!isTypeLegal(Op0.getValueType())) 6756 return; 6757 if (IsStrict) { 6758 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6759 : RISCVISD::STRICT_FCVT_WU_RV64; 6760 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6761 SDValue Res = DAG.getNode( 6762 Opc, DL, VTs, N->getOperand(0), Op0, 6763 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6764 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6765 Results.push_back(Res.getValue(1)); 6766 return; 6767 } 6768 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6769 SDValue Res = 6770 DAG.getNode(Opc, DL, MVT::i64, Op0, 6771 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6772 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6773 return; 6774 } 6775 // If the FP type needs to be softened, emit a library call using the 'si' 6776 // version. If we left it to default legalization we'd end up with 'di'. If 6777 // the FP type doesn't need to be softened just let generic type 6778 // legalization promote the result type. 6779 RTLIB::Libcall LC; 6780 if (IsSigned) 6781 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6782 else 6783 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6784 MakeLibCallOptions CallOptions; 6785 EVT OpVT = Op0.getValueType(); 6786 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6787 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6788 SDValue Result; 6789 std::tie(Result, Chain) = 6790 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6791 Results.push_back(Result); 6792 if (IsStrict) 6793 Results.push_back(Chain); 6794 break; 6795 } 6796 case ISD::READCYCLECOUNTER: { 6797 assert(!Subtarget.is64Bit() && 6798 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6799 6800 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6801 SDValue RCW = 6802 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6803 6804 Results.push_back( 6805 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6806 Results.push_back(RCW.getValue(2)); 6807 break; 6808 } 6809 case ISD::MUL: { 6810 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6811 unsigned XLen = Subtarget.getXLen(); 6812 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6813 if (Size > XLen) { 6814 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6815 SDValue LHS = N->getOperand(0); 6816 SDValue RHS = N->getOperand(1); 6817 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6818 6819 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6820 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6821 // We need exactly one side to be unsigned. 6822 if (LHSIsU == RHSIsU) 6823 return; 6824 6825 auto MakeMULPair = [&](SDValue S, SDValue U) { 6826 MVT XLenVT = Subtarget.getXLenVT(); 6827 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6828 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6829 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6830 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6831 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6832 }; 6833 6834 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6835 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6836 6837 // The other operand should be signed, but still prefer MULH when 6838 // possible. 6839 if (RHSIsU && LHSIsS && !RHSIsS) 6840 Results.push_back(MakeMULPair(LHS, RHS)); 6841 else if (LHSIsU && RHSIsS && !LHSIsS) 6842 Results.push_back(MakeMULPair(RHS, LHS)); 6843 6844 return; 6845 } 6846 LLVM_FALLTHROUGH; 6847 } 6848 case ISD::ADD: 6849 case ISD::SUB: 6850 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6851 "Unexpected custom legalisation"); 6852 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6853 break; 6854 case ISD::SHL: 6855 case ISD::SRA: 6856 case ISD::SRL: 6857 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6858 "Unexpected custom legalisation"); 6859 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6860 // If we can use a BSET instruction, allow default promotion to apply. 6861 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6862 isOneConstant(N->getOperand(0))) 6863 break; 6864 Results.push_back(customLegalizeToWOp(N, DAG)); 6865 break; 6866 } 6867 6868 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6869 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6870 // shift amount. 6871 if (N->getOpcode() == ISD::SHL) { 6872 SDLoc DL(N); 6873 SDValue NewOp0 = 6874 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6875 SDValue NewOp1 = 6876 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6877 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6878 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6879 DAG.getValueType(MVT::i32)); 6880 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6881 } 6882 6883 break; 6884 case ISD::ROTL: 6885 case ISD::ROTR: 6886 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6887 "Unexpected custom legalisation"); 6888 Results.push_back(customLegalizeToWOp(N, DAG)); 6889 break; 6890 case ISD::CTTZ: 6891 case ISD::CTTZ_ZERO_UNDEF: 6892 case ISD::CTLZ: 6893 case ISD::CTLZ_ZERO_UNDEF: { 6894 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6895 "Unexpected custom legalisation"); 6896 6897 SDValue NewOp0 = 6898 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6899 bool IsCTZ = 6900 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6901 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6902 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6903 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6904 return; 6905 } 6906 case ISD::SDIV: 6907 case ISD::UDIV: 6908 case ISD::UREM: { 6909 MVT VT = N->getSimpleValueType(0); 6910 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6911 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6912 "Unexpected custom legalisation"); 6913 // Don't promote division/remainder by constant since we should expand those 6914 // to multiply by magic constant. 6915 // FIXME: What if the expansion is disabled for minsize. 6916 if (N->getOperand(1).getOpcode() == ISD::Constant) 6917 return; 6918 6919 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6920 // the upper 32 bits. For other types we need to sign or zero extend 6921 // based on the opcode. 6922 unsigned ExtOpc = ISD::ANY_EXTEND; 6923 if (VT != MVT::i32) 6924 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6925 : ISD::ZERO_EXTEND; 6926 6927 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6928 break; 6929 } 6930 case ISD::UADDO: 6931 case ISD::USUBO: { 6932 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6933 "Unexpected custom legalisation"); 6934 bool IsAdd = N->getOpcode() == ISD::UADDO; 6935 // Create an ADDW or SUBW. 6936 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6937 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6938 SDValue Res = 6939 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6940 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6941 DAG.getValueType(MVT::i32)); 6942 6943 SDValue Overflow; 6944 if (IsAdd && isOneConstant(RHS)) { 6945 // Special case uaddo X, 1 overflowed if the addition result is 0. 6946 // The general case (X + C) < C is not necessarily beneficial. Although we 6947 // reduce the live range of X, we may introduce the materialization of 6948 // constant C, especially when the setcc result is used by branch. We have 6949 // no compare with constant and branch instructions. 6950 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6951 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6952 } else { 6953 // Sign extend the LHS and perform an unsigned compare with the ADDW 6954 // result. Since the inputs are sign extended from i32, this is equivalent 6955 // to comparing the lower 32 bits. 6956 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6957 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6958 IsAdd ? ISD::SETULT : ISD::SETUGT); 6959 } 6960 6961 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6962 Results.push_back(Overflow); 6963 return; 6964 } 6965 case ISD::UADDSAT: 6966 case ISD::USUBSAT: { 6967 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6968 "Unexpected custom legalisation"); 6969 if (Subtarget.hasStdExtZbb()) { 6970 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6971 // sign extend allows overflow of the lower 32 bits to be detected on 6972 // the promoted size. 6973 SDValue LHS = 6974 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6975 SDValue RHS = 6976 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6977 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6978 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6979 return; 6980 } 6981 6982 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6983 // promotion for UADDO/USUBO. 6984 Results.push_back(expandAddSubSat(N, DAG)); 6985 return; 6986 } 6987 case ISD::ABS: { 6988 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6989 "Unexpected custom legalisation"); 6990 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6991 6992 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6993 6994 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6995 6996 // Freeze the source so we can increase it's use count. 6997 Src = DAG.getFreeze(Src); 6998 6999 // Copy sign bit to all bits using the sraiw pattern. 7000 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7001 DAG.getValueType(MVT::i32)); 7002 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7003 DAG.getConstant(31, DL, MVT::i64)); 7004 7005 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7006 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7007 7008 // NOTE: The result is only required to be anyextended, but sext is 7009 // consistent with type legalization of sub. 7010 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7011 DAG.getValueType(MVT::i32)); 7012 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7013 return; 7014 } 7015 case ISD::BITCAST: { 7016 EVT VT = N->getValueType(0); 7017 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7018 SDValue Op0 = N->getOperand(0); 7019 EVT Op0VT = Op0.getValueType(); 7020 MVT XLenVT = Subtarget.getXLenVT(); 7021 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7022 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7023 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7024 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7025 Subtarget.hasStdExtF()) { 7026 SDValue FPConv = 7027 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7028 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7029 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7030 isTypeLegal(Op0VT)) { 7031 // Custom-legalize bitcasts from fixed-length vector types to illegal 7032 // scalar types in order to improve codegen. Bitcast the vector to a 7033 // one-element vector type whose element type is the same as the result 7034 // type, and extract the first element. 7035 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7036 if (isTypeLegal(BVT)) { 7037 SDValue BVec = DAG.getBitcast(BVT, Op0); 7038 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7039 DAG.getConstant(0, DL, XLenVT))); 7040 } 7041 } 7042 break; 7043 } 7044 case RISCVISD::GREV: 7045 case RISCVISD::GORC: 7046 case RISCVISD::SHFL: { 7047 MVT VT = N->getSimpleValueType(0); 7048 MVT XLenVT = Subtarget.getXLenVT(); 7049 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7050 "Unexpected custom legalisation"); 7051 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7052 assert((Subtarget.hasStdExtZbp() || 7053 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7054 N->getConstantOperandVal(1) == 7)) && 7055 "Unexpected extension"); 7056 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7057 SDValue NewOp1 = 7058 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7059 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7060 // ReplaceNodeResults requires we maintain the same type for the return 7061 // value. 7062 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7063 break; 7064 } 7065 case ISD::BSWAP: 7066 case ISD::BITREVERSE: { 7067 MVT VT = N->getSimpleValueType(0); 7068 MVT XLenVT = Subtarget.getXLenVT(); 7069 assert((VT == MVT::i8 || VT == MVT::i16 || 7070 (VT == MVT::i32 && Subtarget.is64Bit())) && 7071 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7072 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7073 unsigned Imm = VT.getSizeInBits() - 1; 7074 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7075 if (N->getOpcode() == ISD::BSWAP) 7076 Imm &= ~0x7U; 7077 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7078 DAG.getConstant(Imm, DL, XLenVT)); 7079 // ReplaceNodeResults requires we maintain the same type for the return 7080 // value. 7081 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7082 break; 7083 } 7084 case ISD::FSHL: 7085 case ISD::FSHR: { 7086 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7087 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7088 SDValue NewOp0 = 7089 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7090 SDValue NewOp1 = 7091 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7092 SDValue NewShAmt = 7093 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7094 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7095 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7096 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7097 DAG.getConstant(0x1f, DL, MVT::i64)); 7098 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7099 // instruction use different orders. fshl will return its first operand for 7100 // shift of zero, fshr will return its second operand. fsl and fsr both 7101 // return rs1 so the ISD nodes need to have different operand orders. 7102 // Shift amount is in rs2. 7103 unsigned Opc = RISCVISD::FSLW; 7104 if (N->getOpcode() == ISD::FSHR) { 7105 std::swap(NewOp0, NewOp1); 7106 Opc = RISCVISD::FSRW; 7107 } 7108 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7109 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7110 break; 7111 } 7112 case ISD::EXTRACT_VECTOR_ELT: { 7113 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7114 // type is illegal (currently only vXi64 RV32). 7115 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7116 // transferred to the destination register. We issue two of these from the 7117 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7118 // first element. 7119 SDValue Vec = N->getOperand(0); 7120 SDValue Idx = N->getOperand(1); 7121 7122 // The vector type hasn't been legalized yet so we can't issue target 7123 // specific nodes if it needs legalization. 7124 // FIXME: We would manually legalize if it's important. 7125 if (!isTypeLegal(Vec.getValueType())) 7126 return; 7127 7128 MVT VecVT = Vec.getSimpleValueType(); 7129 7130 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7131 VecVT.getVectorElementType() == MVT::i64 && 7132 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7133 7134 // If this is a fixed vector, we need to convert it to a scalable vector. 7135 MVT ContainerVT = VecVT; 7136 if (VecVT.isFixedLengthVector()) { 7137 ContainerVT = getContainerForFixedLengthVector(VecVT); 7138 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7139 } 7140 7141 MVT XLenVT = Subtarget.getXLenVT(); 7142 7143 // Use a VL of 1 to avoid processing more elements than we need. 7144 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7145 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7146 7147 // Unless the index is known to be 0, we must slide the vector down to get 7148 // the desired element into index 0. 7149 if (!isNullConstant(Idx)) { 7150 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7151 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7152 } 7153 7154 // Extract the lower XLEN bits of the correct vector element. 7155 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7156 7157 // To extract the upper XLEN bits of the vector element, shift the first 7158 // element right by 32 bits and re-extract the lower XLEN bits. 7159 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7160 DAG.getUNDEF(ContainerVT), 7161 DAG.getConstant(32, DL, XLenVT), VL); 7162 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7163 ThirtyTwoV, Mask, VL); 7164 7165 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7166 7167 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7168 break; 7169 } 7170 case ISD::INTRINSIC_WO_CHAIN: { 7171 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7172 switch (IntNo) { 7173 default: 7174 llvm_unreachable( 7175 "Don't know how to custom type legalize this intrinsic!"); 7176 case Intrinsic::riscv_grev: 7177 case Intrinsic::riscv_gorc: { 7178 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7179 "Unexpected custom legalisation"); 7180 SDValue NewOp1 = 7181 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7182 SDValue NewOp2 = 7183 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7184 unsigned Opc = 7185 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7186 // If the control is a constant, promote the node by clearing any extra 7187 // bits bits in the control. isel will form greviw/gorciw if the result is 7188 // sign extended. 7189 if (isa<ConstantSDNode>(NewOp2)) { 7190 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7191 DAG.getConstant(0x1f, DL, MVT::i64)); 7192 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7193 } 7194 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7195 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7196 break; 7197 } 7198 case Intrinsic::riscv_bcompress: 7199 case Intrinsic::riscv_bdecompress: 7200 case Intrinsic::riscv_bfp: 7201 case Intrinsic::riscv_fsl: 7202 case Intrinsic::riscv_fsr: { 7203 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7204 "Unexpected custom legalisation"); 7205 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7206 break; 7207 } 7208 case Intrinsic::riscv_orc_b: { 7209 // Lower to the GORCI encoding for orc.b with the operand extended. 7210 SDValue NewOp = 7211 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7212 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7213 DAG.getConstant(7, DL, MVT::i64)); 7214 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7215 return; 7216 } 7217 case Intrinsic::riscv_shfl: 7218 case Intrinsic::riscv_unshfl: { 7219 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7220 "Unexpected custom legalisation"); 7221 SDValue NewOp1 = 7222 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7223 SDValue NewOp2 = 7224 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7225 unsigned Opc = 7226 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7227 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7228 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7229 // will be shuffled the same way as the lower 32 bit half, but the two 7230 // halves won't cross. 7231 if (isa<ConstantSDNode>(NewOp2)) { 7232 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7233 DAG.getConstant(0xf, DL, MVT::i64)); 7234 Opc = 7235 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7236 } 7237 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7238 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7239 break; 7240 } 7241 case Intrinsic::riscv_vmv_x_s: { 7242 EVT VT = N->getValueType(0); 7243 MVT XLenVT = Subtarget.getXLenVT(); 7244 if (VT.bitsLT(XLenVT)) { 7245 // Simple case just extract using vmv.x.s and truncate. 7246 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7247 Subtarget.getXLenVT(), N->getOperand(1)); 7248 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7249 return; 7250 } 7251 7252 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7253 "Unexpected custom legalization"); 7254 7255 // We need to do the move in two steps. 7256 SDValue Vec = N->getOperand(1); 7257 MVT VecVT = Vec.getSimpleValueType(); 7258 7259 // First extract the lower XLEN bits of the element. 7260 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7261 7262 // To extract the upper XLEN bits of the vector element, shift the first 7263 // element right by 32 bits and re-extract the lower XLEN bits. 7264 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7265 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7266 7267 SDValue ThirtyTwoV = 7268 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7269 DAG.getConstant(32, DL, XLenVT), VL); 7270 SDValue LShr32 = 7271 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7272 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7273 7274 Results.push_back( 7275 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7276 break; 7277 } 7278 } 7279 break; 7280 } 7281 case ISD::VECREDUCE_ADD: 7282 case ISD::VECREDUCE_AND: 7283 case ISD::VECREDUCE_OR: 7284 case ISD::VECREDUCE_XOR: 7285 case ISD::VECREDUCE_SMAX: 7286 case ISD::VECREDUCE_UMAX: 7287 case ISD::VECREDUCE_SMIN: 7288 case ISD::VECREDUCE_UMIN: 7289 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7290 Results.push_back(V); 7291 break; 7292 case ISD::VP_REDUCE_ADD: 7293 case ISD::VP_REDUCE_AND: 7294 case ISD::VP_REDUCE_OR: 7295 case ISD::VP_REDUCE_XOR: 7296 case ISD::VP_REDUCE_SMAX: 7297 case ISD::VP_REDUCE_UMAX: 7298 case ISD::VP_REDUCE_SMIN: 7299 case ISD::VP_REDUCE_UMIN: 7300 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7301 Results.push_back(V); 7302 break; 7303 case ISD::FLT_ROUNDS_: { 7304 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7305 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7306 Results.push_back(Res.getValue(0)); 7307 Results.push_back(Res.getValue(1)); 7308 break; 7309 } 7310 } 7311 } 7312 7313 // A structure to hold one of the bit-manipulation patterns below. Together, a 7314 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7315 // (or (and (shl x, 1), 0xAAAAAAAA), 7316 // (and (srl x, 1), 0x55555555)) 7317 struct RISCVBitmanipPat { 7318 SDValue Op; 7319 unsigned ShAmt; 7320 bool IsSHL; 7321 7322 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7323 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7324 } 7325 }; 7326 7327 // Matches patterns of the form 7328 // (and (shl x, C2), (C1 << C2)) 7329 // (and (srl x, C2), C1) 7330 // (shl (and x, C1), C2) 7331 // (srl (and x, (C1 << C2)), C2) 7332 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7333 // The expected masks for each shift amount are specified in BitmanipMasks where 7334 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7335 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7336 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7337 // XLen is 64. 7338 static Optional<RISCVBitmanipPat> 7339 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7340 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7341 "Unexpected number of masks"); 7342 Optional<uint64_t> Mask; 7343 // Optionally consume a mask around the shift operation. 7344 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7345 Mask = Op.getConstantOperandVal(1); 7346 Op = Op.getOperand(0); 7347 } 7348 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7349 return None; 7350 bool IsSHL = Op.getOpcode() == ISD::SHL; 7351 7352 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7353 return None; 7354 uint64_t ShAmt = Op.getConstantOperandVal(1); 7355 7356 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7357 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7358 return None; 7359 // If we don't have enough masks for 64 bit, then we must be trying to 7360 // match SHFL so we're only allowed to shift 1/4 of the width. 7361 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7362 return None; 7363 7364 SDValue Src = Op.getOperand(0); 7365 7366 // The expected mask is shifted left when the AND is found around SHL 7367 // patterns. 7368 // ((x >> 1) & 0x55555555) 7369 // ((x << 1) & 0xAAAAAAAA) 7370 bool SHLExpMask = IsSHL; 7371 7372 if (!Mask) { 7373 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7374 // the mask is all ones: consume that now. 7375 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7376 Mask = Src.getConstantOperandVal(1); 7377 Src = Src.getOperand(0); 7378 // The expected mask is now in fact shifted left for SRL, so reverse the 7379 // decision. 7380 // ((x & 0xAAAAAAAA) >> 1) 7381 // ((x & 0x55555555) << 1) 7382 SHLExpMask = !SHLExpMask; 7383 } else { 7384 // Use a default shifted mask of all-ones if there's no AND, truncated 7385 // down to the expected width. This simplifies the logic later on. 7386 Mask = maskTrailingOnes<uint64_t>(Width); 7387 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7388 } 7389 } 7390 7391 unsigned MaskIdx = Log2_32(ShAmt); 7392 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7393 7394 if (SHLExpMask) 7395 ExpMask <<= ShAmt; 7396 7397 if (Mask != ExpMask) 7398 return None; 7399 7400 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7401 } 7402 7403 // Matches any of the following bit-manipulation patterns: 7404 // (and (shl x, 1), (0x55555555 << 1)) 7405 // (and (srl x, 1), 0x55555555) 7406 // (shl (and x, 0x55555555), 1) 7407 // (srl (and x, (0x55555555 << 1)), 1) 7408 // where the shift amount and mask may vary thus: 7409 // [1] = 0x55555555 / 0xAAAAAAAA 7410 // [2] = 0x33333333 / 0xCCCCCCCC 7411 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7412 // [8] = 0x00FF00FF / 0xFF00FF00 7413 // [16] = 0x0000FFFF / 0xFFFFFFFF 7414 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7415 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7416 // These are the unshifted masks which we use to match bit-manipulation 7417 // patterns. They may be shifted left in certain circumstances. 7418 static const uint64_t BitmanipMasks[] = { 7419 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7420 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7421 7422 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7423 } 7424 7425 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7426 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7427 auto BinOpToRVVReduce = [](unsigned Opc) { 7428 switch (Opc) { 7429 default: 7430 llvm_unreachable("Unhandled binary to transfrom reduction"); 7431 case ISD::ADD: 7432 return RISCVISD::VECREDUCE_ADD_VL; 7433 case ISD::UMAX: 7434 return RISCVISD::VECREDUCE_UMAX_VL; 7435 case ISD::SMAX: 7436 return RISCVISD::VECREDUCE_SMAX_VL; 7437 case ISD::UMIN: 7438 return RISCVISD::VECREDUCE_UMIN_VL; 7439 case ISD::SMIN: 7440 return RISCVISD::VECREDUCE_SMIN_VL; 7441 case ISD::AND: 7442 return RISCVISD::VECREDUCE_AND_VL; 7443 case ISD::OR: 7444 return RISCVISD::VECREDUCE_OR_VL; 7445 case ISD::XOR: 7446 return RISCVISD::VECREDUCE_XOR_VL; 7447 case ISD::FADD: 7448 return RISCVISD::VECREDUCE_FADD_VL; 7449 case ISD::FMAXNUM: 7450 return RISCVISD::VECREDUCE_FMAX_VL; 7451 case ISD::FMINNUM: 7452 return RISCVISD::VECREDUCE_FMIN_VL; 7453 } 7454 }; 7455 7456 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7457 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7458 isNullConstant(V.getOperand(1)) && 7459 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7460 }; 7461 7462 unsigned Opc = N->getOpcode(); 7463 unsigned ReduceIdx; 7464 if (IsReduction(N->getOperand(0), Opc)) 7465 ReduceIdx = 0; 7466 else if (IsReduction(N->getOperand(1), Opc)) 7467 ReduceIdx = 1; 7468 else 7469 return SDValue(); 7470 7471 // Skip if FADD disallows reassociation but the combiner needs. 7472 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7473 return SDValue(); 7474 7475 SDValue Extract = N->getOperand(ReduceIdx); 7476 SDValue Reduce = Extract.getOperand(0); 7477 if (!Reduce.hasOneUse()) 7478 return SDValue(); 7479 7480 SDValue ScalarV = Reduce.getOperand(2); 7481 7482 // Make sure that ScalarV is a splat with VL=1. 7483 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7484 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7485 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7486 return SDValue(); 7487 7488 if (!isOneConstant(ScalarV.getOperand(2))) 7489 return SDValue(); 7490 7491 // TODO: Deal with value other than neutral element. 7492 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7493 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7494 isNullFPConstant(V)) 7495 return true; 7496 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7497 N->getFlags()) == V; 7498 }; 7499 7500 // Check the scalar of ScalarV is neutral element 7501 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7502 return SDValue(); 7503 7504 if (!ScalarV.hasOneUse()) 7505 return SDValue(); 7506 7507 EVT SplatVT = ScalarV.getValueType(); 7508 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7509 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7510 if (SplatVT.isInteger()) { 7511 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7512 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7513 SplatOpc = RISCVISD::VMV_S_X_VL; 7514 else 7515 SplatOpc = RISCVISD::VMV_V_X_VL; 7516 } 7517 7518 SDValue NewScalarV = 7519 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7520 ScalarV.getOperand(2)); 7521 SDValue NewReduce = 7522 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7523 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7524 Reduce.getOperand(3), Reduce.getOperand(4)); 7525 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7526 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7527 } 7528 7529 // Match the following pattern as a GREVI(W) operation 7530 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7531 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7532 const RISCVSubtarget &Subtarget) { 7533 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7534 EVT VT = Op.getValueType(); 7535 7536 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7537 auto LHS = matchGREVIPat(Op.getOperand(0)); 7538 auto RHS = matchGREVIPat(Op.getOperand(1)); 7539 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7540 SDLoc DL(Op); 7541 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7542 DAG.getConstant(LHS->ShAmt, DL, VT)); 7543 } 7544 } 7545 return SDValue(); 7546 } 7547 7548 // Matches any the following pattern as a GORCI(W) operation 7549 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7550 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7551 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7552 // Note that with the variant of 3., 7553 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7554 // the inner pattern will first be matched as GREVI and then the outer 7555 // pattern will be matched to GORC via the first rule above. 7556 // 4. (or (rotl/rotr x, bitwidth/2), x) 7557 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7558 const RISCVSubtarget &Subtarget) { 7559 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7560 EVT VT = Op.getValueType(); 7561 7562 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7563 SDLoc DL(Op); 7564 SDValue Op0 = Op.getOperand(0); 7565 SDValue Op1 = Op.getOperand(1); 7566 7567 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7568 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7569 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7570 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7571 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7572 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7573 if ((Reverse.getOpcode() == ISD::ROTL || 7574 Reverse.getOpcode() == ISD::ROTR) && 7575 Reverse.getOperand(0) == X && 7576 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7577 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7578 if (RotAmt == (VT.getSizeInBits() / 2)) 7579 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7580 DAG.getConstant(RotAmt, DL, VT)); 7581 } 7582 return SDValue(); 7583 }; 7584 7585 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7586 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7587 return V; 7588 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7589 return V; 7590 7591 // OR is commutable so canonicalize its OR operand to the left 7592 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7593 std::swap(Op0, Op1); 7594 if (Op0.getOpcode() != ISD::OR) 7595 return SDValue(); 7596 SDValue OrOp0 = Op0.getOperand(0); 7597 SDValue OrOp1 = Op0.getOperand(1); 7598 auto LHS = matchGREVIPat(OrOp0); 7599 // OR is commutable so swap the operands and try again: x might have been 7600 // on the left 7601 if (!LHS) { 7602 std::swap(OrOp0, OrOp1); 7603 LHS = matchGREVIPat(OrOp0); 7604 } 7605 auto RHS = matchGREVIPat(Op1); 7606 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7607 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7608 DAG.getConstant(LHS->ShAmt, DL, VT)); 7609 } 7610 } 7611 return SDValue(); 7612 } 7613 7614 // Matches any of the following bit-manipulation patterns: 7615 // (and (shl x, 1), (0x22222222 << 1)) 7616 // (and (srl x, 1), 0x22222222) 7617 // (shl (and x, 0x22222222), 1) 7618 // (srl (and x, (0x22222222 << 1)), 1) 7619 // where the shift amount and mask may vary thus: 7620 // [1] = 0x22222222 / 0x44444444 7621 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7622 // [4] = 0x00F000F0 / 0x0F000F00 7623 // [8] = 0x0000FF00 / 0x00FF0000 7624 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7625 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7626 // These are the unshifted masks which we use to match bit-manipulation 7627 // patterns. They may be shifted left in certain circumstances. 7628 static const uint64_t BitmanipMasks[] = { 7629 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7630 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7631 7632 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7633 } 7634 7635 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7636 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7637 const RISCVSubtarget &Subtarget) { 7638 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7639 EVT VT = Op.getValueType(); 7640 7641 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7642 return SDValue(); 7643 7644 SDValue Op0 = Op.getOperand(0); 7645 SDValue Op1 = Op.getOperand(1); 7646 7647 // Or is commutable so canonicalize the second OR to the LHS. 7648 if (Op0.getOpcode() != ISD::OR) 7649 std::swap(Op0, Op1); 7650 if (Op0.getOpcode() != ISD::OR) 7651 return SDValue(); 7652 7653 // We found an inner OR, so our operands are the operands of the inner OR 7654 // and the other operand of the outer OR. 7655 SDValue A = Op0.getOperand(0); 7656 SDValue B = Op0.getOperand(1); 7657 SDValue C = Op1; 7658 7659 auto Match1 = matchSHFLPat(A); 7660 auto Match2 = matchSHFLPat(B); 7661 7662 // If neither matched, we failed. 7663 if (!Match1 && !Match2) 7664 return SDValue(); 7665 7666 // We had at least one match. if one failed, try the remaining C operand. 7667 if (!Match1) { 7668 std::swap(A, C); 7669 Match1 = matchSHFLPat(A); 7670 if (!Match1) 7671 return SDValue(); 7672 } else if (!Match2) { 7673 std::swap(B, C); 7674 Match2 = matchSHFLPat(B); 7675 if (!Match2) 7676 return SDValue(); 7677 } 7678 assert(Match1 && Match2); 7679 7680 // Make sure our matches pair up. 7681 if (!Match1->formsPairWith(*Match2)) 7682 return SDValue(); 7683 7684 // All the remains is to make sure C is an AND with the same input, that masks 7685 // out the bits that are being shuffled. 7686 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7687 C.getOperand(0) != Match1->Op) 7688 return SDValue(); 7689 7690 uint64_t Mask = C.getConstantOperandVal(1); 7691 7692 static const uint64_t BitmanipMasks[] = { 7693 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7694 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7695 }; 7696 7697 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7698 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7699 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7700 7701 if (Mask != ExpMask) 7702 return SDValue(); 7703 7704 SDLoc DL(Op); 7705 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7706 DAG.getConstant(Match1->ShAmt, DL, VT)); 7707 } 7708 7709 // Optimize (add (shl x, c0), (shl y, c1)) -> 7710 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7711 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7712 const RISCVSubtarget &Subtarget) { 7713 // Perform this optimization only in the zba extension. 7714 if (!Subtarget.hasStdExtZba()) 7715 return SDValue(); 7716 7717 // Skip for vector types and larger types. 7718 EVT VT = N->getValueType(0); 7719 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7720 return SDValue(); 7721 7722 // The two operand nodes must be SHL and have no other use. 7723 SDValue N0 = N->getOperand(0); 7724 SDValue N1 = N->getOperand(1); 7725 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7726 !N0->hasOneUse() || !N1->hasOneUse()) 7727 return SDValue(); 7728 7729 // Check c0 and c1. 7730 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7731 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7732 if (!N0C || !N1C) 7733 return SDValue(); 7734 int64_t C0 = N0C->getSExtValue(); 7735 int64_t C1 = N1C->getSExtValue(); 7736 if (C0 <= 0 || C1 <= 0) 7737 return SDValue(); 7738 7739 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7740 int64_t Bits = std::min(C0, C1); 7741 int64_t Diff = std::abs(C0 - C1); 7742 if (Diff != 1 && Diff != 2 && Diff != 3) 7743 return SDValue(); 7744 7745 // Build nodes. 7746 SDLoc DL(N); 7747 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7748 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7749 SDValue NA0 = 7750 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7751 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7752 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7753 } 7754 7755 // Combine 7756 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7757 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7758 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7759 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7760 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7761 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7762 // The grev patterns represents BSWAP. 7763 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7764 // off the grev. 7765 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7766 const RISCVSubtarget &Subtarget) { 7767 bool IsWInstruction = 7768 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7769 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7770 IsWInstruction) && 7771 "Unexpected opcode!"); 7772 SDValue Src = N->getOperand(0); 7773 EVT VT = N->getValueType(0); 7774 SDLoc DL(N); 7775 7776 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7777 return SDValue(); 7778 7779 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7780 !isa<ConstantSDNode>(Src.getOperand(1))) 7781 return SDValue(); 7782 7783 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7784 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7785 7786 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7787 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7788 unsigned ShAmt1 = N->getConstantOperandVal(1); 7789 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7790 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7791 return SDValue(); 7792 7793 Src = Src.getOperand(0); 7794 7795 // Toggle bit the MSB of the shift. 7796 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7797 if (CombinedShAmt == 0) 7798 return Src; 7799 7800 SDValue Res = DAG.getNode( 7801 RISCVISD::GREV, DL, VT, Src, 7802 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7803 if (!IsWInstruction) 7804 return Res; 7805 7806 // Sign extend the result to match the behavior of the rotate. This will be 7807 // selected to GREVIW in isel. 7808 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7809 DAG.getValueType(MVT::i32)); 7810 } 7811 7812 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7813 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7814 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7815 // not undo itself, but they are redundant. 7816 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7817 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7818 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7819 SDValue Src = N->getOperand(0); 7820 7821 if (Src.getOpcode() != N->getOpcode()) 7822 return SDValue(); 7823 7824 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7825 !isa<ConstantSDNode>(Src.getOperand(1))) 7826 return SDValue(); 7827 7828 unsigned ShAmt1 = N->getConstantOperandVal(1); 7829 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7830 Src = Src.getOperand(0); 7831 7832 unsigned CombinedShAmt; 7833 if (IsGORC) 7834 CombinedShAmt = ShAmt1 | ShAmt2; 7835 else 7836 CombinedShAmt = ShAmt1 ^ ShAmt2; 7837 7838 if (CombinedShAmt == 0) 7839 return Src; 7840 7841 SDLoc DL(N); 7842 return DAG.getNode( 7843 N->getOpcode(), DL, N->getValueType(0), Src, 7844 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7845 } 7846 7847 // Combine a constant select operand into its use: 7848 // 7849 // (and (select cond, -1, c), x) 7850 // -> (select cond, x, (and x, c)) [AllOnes=1] 7851 // (or (select cond, 0, c), x) 7852 // -> (select cond, x, (or x, c)) [AllOnes=0] 7853 // (xor (select cond, 0, c), x) 7854 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7855 // (add (select cond, 0, c), x) 7856 // -> (select cond, x, (add x, c)) [AllOnes=0] 7857 // (sub x, (select cond, 0, c)) 7858 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7859 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7860 SelectionDAG &DAG, bool AllOnes) { 7861 EVT VT = N->getValueType(0); 7862 7863 // Skip vectors. 7864 if (VT.isVector()) 7865 return SDValue(); 7866 7867 if ((Slct.getOpcode() != ISD::SELECT && 7868 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7869 !Slct.hasOneUse()) 7870 return SDValue(); 7871 7872 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7873 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7874 }; 7875 7876 bool SwapSelectOps; 7877 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7878 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7879 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7880 SDValue NonConstantVal; 7881 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7882 SwapSelectOps = false; 7883 NonConstantVal = FalseVal; 7884 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7885 SwapSelectOps = true; 7886 NonConstantVal = TrueVal; 7887 } else 7888 return SDValue(); 7889 7890 // Slct is now know to be the desired identity constant when CC is true. 7891 TrueVal = OtherOp; 7892 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7893 // Unless SwapSelectOps says the condition should be false. 7894 if (SwapSelectOps) 7895 std::swap(TrueVal, FalseVal); 7896 7897 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7898 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7899 {Slct.getOperand(0), Slct.getOperand(1), 7900 Slct.getOperand(2), TrueVal, FalseVal}); 7901 7902 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7903 {Slct.getOperand(0), TrueVal, FalseVal}); 7904 } 7905 7906 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7907 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7908 bool AllOnes) { 7909 SDValue N0 = N->getOperand(0); 7910 SDValue N1 = N->getOperand(1); 7911 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7912 return Result; 7913 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7914 return Result; 7915 return SDValue(); 7916 } 7917 7918 // Transform (add (mul x, c0), c1) -> 7919 // (add (mul (add x, c1/c0), c0), c1%c0). 7920 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7921 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7922 // to an infinite loop in DAGCombine if transformed. 7923 // Or transform (add (mul x, c0), c1) -> 7924 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7925 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7926 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7927 // lead to an infinite loop in DAGCombine if transformed. 7928 // Or transform (add (mul x, c0), c1) -> 7929 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7930 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7931 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7932 // lead to an infinite loop in DAGCombine if transformed. 7933 // Or transform (add (mul x, c0), c1) -> 7934 // (mul (add x, c1/c0), c0). 7935 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7936 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7937 const RISCVSubtarget &Subtarget) { 7938 // Skip for vector types and larger types. 7939 EVT VT = N->getValueType(0); 7940 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7941 return SDValue(); 7942 // The first operand node must be a MUL and has no other use. 7943 SDValue N0 = N->getOperand(0); 7944 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7945 return SDValue(); 7946 // Check if c0 and c1 match above conditions. 7947 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7948 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7949 if (!N0C || !N1C) 7950 return SDValue(); 7951 // If N0C has multiple uses it's possible one of the cases in 7952 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7953 // in an infinite loop. 7954 if (!N0C->hasOneUse()) 7955 return SDValue(); 7956 int64_t C0 = N0C->getSExtValue(); 7957 int64_t C1 = N1C->getSExtValue(); 7958 int64_t CA, CB; 7959 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7960 return SDValue(); 7961 // Search for proper CA (non-zero) and CB that both are simm12. 7962 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7963 !isInt<12>(C0 * (C1 / C0))) { 7964 CA = C1 / C0; 7965 CB = C1 % C0; 7966 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7967 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7968 CA = C1 / C0 + 1; 7969 CB = C1 % C0 - C0; 7970 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7971 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7972 CA = C1 / C0 - 1; 7973 CB = C1 % C0 + C0; 7974 } else 7975 return SDValue(); 7976 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7977 SDLoc DL(N); 7978 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7979 DAG.getConstant(CA, DL, VT)); 7980 SDValue New1 = 7981 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7982 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7983 } 7984 7985 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7986 const RISCVSubtarget &Subtarget) { 7987 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7988 return V; 7989 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7990 return V; 7991 if (SDValue V = combineBinOpToReduce(N, DAG)) 7992 return V; 7993 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7994 // (select lhs, rhs, cc, x, (add x, y)) 7995 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7996 } 7997 7998 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7999 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8000 // (select lhs, rhs, cc, x, (sub x, y)) 8001 SDValue N0 = N->getOperand(0); 8002 SDValue N1 = N->getOperand(1); 8003 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8004 } 8005 8006 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8007 const RISCVSubtarget &Subtarget) { 8008 SDValue N0 = N->getOperand(0); 8009 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8010 // extending X. This is safe since we only need the LSB after the shift and 8011 // shift amounts larger than 31 would produce poison. If we wait until 8012 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8013 // to use a BEXT instruction. 8014 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8015 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8016 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8017 N0.hasOneUse()) { 8018 SDLoc DL(N); 8019 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8020 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8021 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8022 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8023 DAG.getConstant(1, DL, MVT::i64)); 8024 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8025 } 8026 8027 if (SDValue V = combineBinOpToReduce(N, DAG)) 8028 return V; 8029 8030 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8031 // (select lhs, rhs, cc, x, (and x, y)) 8032 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8033 } 8034 8035 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8036 const RISCVSubtarget &Subtarget) { 8037 if (Subtarget.hasStdExtZbp()) { 8038 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8039 return GREV; 8040 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8041 return GORC; 8042 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8043 return SHFL; 8044 } 8045 8046 if (SDValue V = combineBinOpToReduce(N, DAG)) 8047 return V; 8048 // fold (or (select cond, 0, y), x) -> 8049 // (select cond, x, (or x, y)) 8050 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8051 } 8052 8053 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8054 SDValue N0 = N->getOperand(0); 8055 SDValue N1 = N->getOperand(1); 8056 8057 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8058 // NOTE: Assumes ROL being legal means ROLW is legal. 8059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8060 if (N0.getOpcode() == RISCVISD::SLLW && 8061 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8062 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8063 SDLoc DL(N); 8064 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8065 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8066 } 8067 8068 if (SDValue V = combineBinOpToReduce(N, DAG)) 8069 return V; 8070 // fold (xor (select cond, 0, y), x) -> 8071 // (select cond, x, (xor x, y)) 8072 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8073 } 8074 8075 static SDValue 8076 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8077 const RISCVSubtarget &Subtarget) { 8078 SDValue Src = N->getOperand(0); 8079 EVT VT = N->getValueType(0); 8080 8081 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8082 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8083 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8084 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8085 Src.getOperand(0)); 8086 8087 // Fold (i64 (sext_inreg (abs X), i32)) -> 8088 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8089 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8090 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8091 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8092 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8093 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8094 // may get combined into an earlier operation so we need to use 8095 // ComputeNumSignBits. 8096 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8097 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8098 // we can't assume that X has 33 sign bits. We must check. 8099 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8100 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8101 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8102 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8103 SDLoc DL(N); 8104 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8105 SDValue Neg = 8106 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8107 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8108 DAG.getValueType(MVT::i32)); 8109 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8110 } 8111 8112 return SDValue(); 8113 } 8114 8115 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8116 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8117 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8118 bool Commute = false) { 8119 assert((N->getOpcode() == RISCVISD::ADD_VL || 8120 N->getOpcode() == RISCVISD::SUB_VL) && 8121 "Unexpected opcode"); 8122 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8123 SDValue Op0 = N->getOperand(0); 8124 SDValue Op1 = N->getOperand(1); 8125 if (Commute) 8126 std::swap(Op0, Op1); 8127 8128 MVT VT = N->getSimpleValueType(0); 8129 8130 // Determine the narrow size for a widening add/sub. 8131 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8132 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8133 VT.getVectorElementCount()); 8134 8135 SDValue Mask = N->getOperand(2); 8136 SDValue VL = N->getOperand(3); 8137 8138 SDLoc DL(N); 8139 8140 // If the RHS is a sext or zext, we can form a widening op. 8141 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8142 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8143 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8144 unsigned ExtOpc = Op1.getOpcode(); 8145 Op1 = Op1.getOperand(0); 8146 // Re-introduce narrower extends if needed. 8147 if (Op1.getValueType() != NarrowVT) 8148 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8149 8150 unsigned WOpc; 8151 if (ExtOpc == RISCVISD::VSEXT_VL) 8152 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8153 else 8154 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8155 8156 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8157 } 8158 8159 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8160 // sext/zext? 8161 8162 return SDValue(); 8163 } 8164 8165 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8166 // vwsub(u).vv/vx. 8167 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8168 SDValue Op0 = N->getOperand(0); 8169 SDValue Op1 = N->getOperand(1); 8170 SDValue Mask = N->getOperand(2); 8171 SDValue VL = N->getOperand(3); 8172 8173 MVT VT = N->getSimpleValueType(0); 8174 MVT NarrowVT = Op1.getSimpleValueType(); 8175 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8176 8177 unsigned VOpc; 8178 switch (N->getOpcode()) { 8179 default: llvm_unreachable("Unexpected opcode"); 8180 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8181 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8182 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8183 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8184 } 8185 8186 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8187 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8188 8189 SDLoc DL(N); 8190 8191 // If the LHS is a sext or zext, we can narrow this op to the same size as 8192 // the RHS. 8193 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8194 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8195 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8196 unsigned ExtOpc = Op0.getOpcode(); 8197 Op0 = Op0.getOperand(0); 8198 // Re-introduce narrower extends if needed. 8199 if (Op0.getValueType() != NarrowVT) 8200 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8201 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8202 } 8203 8204 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8205 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8206 8207 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8208 // to commute and use a vwadd(u).vx instead. 8209 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8210 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8211 Op0 = Op0.getOperand(1); 8212 8213 // See if have enough sign bits or zero bits in the scalar to use a 8214 // widening add/sub by splatting to smaller element size. 8215 unsigned EltBits = VT.getScalarSizeInBits(); 8216 unsigned ScalarBits = Op0.getValueSizeInBits(); 8217 // Make sure we're getting all element bits from the scalar register. 8218 // FIXME: Support implicit sign extension of vmv.v.x? 8219 if (ScalarBits < EltBits) 8220 return SDValue(); 8221 8222 if (IsSigned) { 8223 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8224 return SDValue(); 8225 } else { 8226 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8227 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8228 return SDValue(); 8229 } 8230 8231 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8232 DAG.getUNDEF(NarrowVT), Op0, VL); 8233 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8234 } 8235 8236 return SDValue(); 8237 } 8238 8239 // Try to form VWMUL, VWMULU or VWMULSU. 8240 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8241 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8242 bool Commute) { 8243 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8244 SDValue Op0 = N->getOperand(0); 8245 SDValue Op1 = N->getOperand(1); 8246 if (Commute) 8247 std::swap(Op0, Op1); 8248 8249 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8250 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8251 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8252 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8253 return SDValue(); 8254 8255 SDValue Mask = N->getOperand(2); 8256 SDValue VL = N->getOperand(3); 8257 8258 // Make sure the mask and VL match. 8259 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8260 return SDValue(); 8261 8262 MVT VT = N->getSimpleValueType(0); 8263 8264 // Determine the narrow size for a widening multiply. 8265 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8266 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8267 VT.getVectorElementCount()); 8268 8269 SDLoc DL(N); 8270 8271 // See if the other operand is the same opcode. 8272 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8273 if (!Op1.hasOneUse()) 8274 return SDValue(); 8275 8276 // Make sure the mask and VL match. 8277 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8278 return SDValue(); 8279 8280 Op1 = Op1.getOperand(0); 8281 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8282 // The operand is a splat of a scalar. 8283 8284 // The pasthru must be undef for tail agnostic 8285 if (!Op1.getOperand(0).isUndef()) 8286 return SDValue(); 8287 // The VL must be the same. 8288 if (Op1.getOperand(2) != VL) 8289 return SDValue(); 8290 8291 // Get the scalar value. 8292 Op1 = Op1.getOperand(1); 8293 8294 // See if have enough sign bits or zero bits in the scalar to use a 8295 // widening multiply by splatting to smaller element size. 8296 unsigned EltBits = VT.getScalarSizeInBits(); 8297 unsigned ScalarBits = Op1.getValueSizeInBits(); 8298 // Make sure we're getting all element bits from the scalar register. 8299 // FIXME: Support implicit sign extension of vmv.v.x? 8300 if (ScalarBits < EltBits) 8301 return SDValue(); 8302 8303 // If the LHS is a sign extend, try to use vwmul. 8304 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8305 // Can use vwmul. 8306 } else { 8307 // Otherwise try to use vwmulu or vwmulsu. 8308 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8309 if (DAG.MaskedValueIsZero(Op1, Mask)) 8310 IsVWMULSU = IsSignExt; 8311 else 8312 return SDValue(); 8313 } 8314 8315 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8316 DAG.getUNDEF(NarrowVT), Op1, VL); 8317 } else 8318 return SDValue(); 8319 8320 Op0 = Op0.getOperand(0); 8321 8322 // Re-introduce narrower extends if needed. 8323 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8324 if (Op0.getValueType() != NarrowVT) 8325 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8326 // vwmulsu requires second operand to be zero extended. 8327 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8328 if (Op1.getValueType() != NarrowVT) 8329 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8330 8331 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8332 if (!IsVWMULSU) 8333 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8334 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8335 } 8336 8337 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8338 switch (Op.getOpcode()) { 8339 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8340 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8341 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8342 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8343 case ISD::FROUND: return RISCVFPRndMode::RMM; 8344 } 8345 8346 return RISCVFPRndMode::Invalid; 8347 } 8348 8349 // Fold 8350 // (fp_to_int (froundeven X)) -> fcvt X, rne 8351 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8352 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8353 // (fp_to_int (fceil X)) -> fcvt X, rup 8354 // (fp_to_int (fround X)) -> fcvt X, rmm 8355 static SDValue performFP_TO_INTCombine(SDNode *N, 8356 TargetLowering::DAGCombinerInfo &DCI, 8357 const RISCVSubtarget &Subtarget) { 8358 SelectionDAG &DAG = DCI.DAG; 8359 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8360 MVT XLenVT = Subtarget.getXLenVT(); 8361 8362 // Only handle XLen or i32 types. Other types narrower than XLen will 8363 // eventually be legalized to XLenVT. 8364 EVT VT = N->getValueType(0); 8365 if (VT != MVT::i32 && VT != XLenVT) 8366 return SDValue(); 8367 8368 SDValue Src = N->getOperand(0); 8369 8370 // Ensure the FP type is also legal. 8371 if (!TLI.isTypeLegal(Src.getValueType())) 8372 return SDValue(); 8373 8374 // Don't do this for f16 with Zfhmin and not Zfh. 8375 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8376 return SDValue(); 8377 8378 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8379 if (FRM == RISCVFPRndMode::Invalid) 8380 return SDValue(); 8381 8382 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8383 8384 unsigned Opc; 8385 if (VT == XLenVT) 8386 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8387 else 8388 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8389 8390 SDLoc DL(N); 8391 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8392 DAG.getTargetConstant(FRM, DL, XLenVT)); 8393 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8394 } 8395 8396 // Fold 8397 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8398 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8399 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8400 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8401 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8402 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8403 TargetLowering::DAGCombinerInfo &DCI, 8404 const RISCVSubtarget &Subtarget) { 8405 SelectionDAG &DAG = DCI.DAG; 8406 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8407 MVT XLenVT = Subtarget.getXLenVT(); 8408 8409 // Only handle XLen types. Other types narrower than XLen will eventually be 8410 // legalized to XLenVT. 8411 EVT DstVT = N->getValueType(0); 8412 if (DstVT != XLenVT) 8413 return SDValue(); 8414 8415 SDValue Src = N->getOperand(0); 8416 8417 // Ensure the FP type is also legal. 8418 if (!TLI.isTypeLegal(Src.getValueType())) 8419 return SDValue(); 8420 8421 // Don't do this for f16 with Zfhmin and not Zfh. 8422 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8423 return SDValue(); 8424 8425 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8426 8427 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8428 if (FRM == RISCVFPRndMode::Invalid) 8429 return SDValue(); 8430 8431 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8432 8433 unsigned Opc; 8434 if (SatVT == DstVT) 8435 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8436 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8437 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8438 else 8439 return SDValue(); 8440 // FIXME: Support other SatVTs by clamping before or after the conversion. 8441 8442 Src = Src.getOperand(0); 8443 8444 SDLoc DL(N); 8445 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8446 DAG.getTargetConstant(FRM, DL, XLenVT)); 8447 8448 // RISCV FP-to-int conversions saturate to the destination register size, but 8449 // don't produce 0 for nan. 8450 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8451 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8452 } 8453 8454 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8455 // smaller than XLenVT. 8456 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8457 const RISCVSubtarget &Subtarget) { 8458 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8459 8460 SDValue Src = N->getOperand(0); 8461 if (Src.getOpcode() != ISD::BSWAP) 8462 return SDValue(); 8463 8464 EVT VT = N->getValueType(0); 8465 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8466 !isPowerOf2_32(VT.getSizeInBits())) 8467 return SDValue(); 8468 8469 SDLoc DL(N); 8470 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8471 DAG.getConstant(7, DL, VT)); 8472 } 8473 8474 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8475 DAGCombinerInfo &DCI) const { 8476 SelectionDAG &DAG = DCI.DAG; 8477 8478 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8479 // bits are demanded. N will be added to the Worklist if it was not deleted. 8480 // Caller should return SDValue(N, 0) if this returns true. 8481 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8482 SDValue Op = N->getOperand(OpNo); 8483 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8484 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8485 return false; 8486 8487 if (N->getOpcode() != ISD::DELETED_NODE) 8488 DCI.AddToWorklist(N); 8489 return true; 8490 }; 8491 8492 switch (N->getOpcode()) { 8493 default: 8494 break; 8495 case RISCVISD::SplitF64: { 8496 SDValue Op0 = N->getOperand(0); 8497 // If the input to SplitF64 is just BuildPairF64 then the operation is 8498 // redundant. Instead, use BuildPairF64's operands directly. 8499 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8500 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8501 8502 if (Op0->isUndef()) { 8503 SDValue Lo = DAG.getUNDEF(MVT::i32); 8504 SDValue Hi = DAG.getUNDEF(MVT::i32); 8505 return DCI.CombineTo(N, Lo, Hi); 8506 } 8507 8508 SDLoc DL(N); 8509 8510 // It's cheaper to materialise two 32-bit integers than to load a double 8511 // from the constant pool and transfer it to integer registers through the 8512 // stack. 8513 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8514 APInt V = C->getValueAPF().bitcastToAPInt(); 8515 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8516 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8517 return DCI.CombineTo(N, Lo, Hi); 8518 } 8519 8520 // This is a target-specific version of a DAGCombine performed in 8521 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8522 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8523 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8524 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8525 !Op0.getNode()->hasOneUse()) 8526 break; 8527 SDValue NewSplitF64 = 8528 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8529 Op0.getOperand(0)); 8530 SDValue Lo = NewSplitF64.getValue(0); 8531 SDValue Hi = NewSplitF64.getValue(1); 8532 APInt SignBit = APInt::getSignMask(32); 8533 if (Op0.getOpcode() == ISD::FNEG) { 8534 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8535 DAG.getConstant(SignBit, DL, MVT::i32)); 8536 return DCI.CombineTo(N, Lo, NewHi); 8537 } 8538 assert(Op0.getOpcode() == ISD::FABS); 8539 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8540 DAG.getConstant(~SignBit, DL, MVT::i32)); 8541 return DCI.CombineTo(N, Lo, NewHi); 8542 } 8543 case RISCVISD::SLLW: 8544 case RISCVISD::SRAW: 8545 case RISCVISD::SRLW: { 8546 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8547 if (SimplifyDemandedLowBitsHelper(0, 32) || 8548 SimplifyDemandedLowBitsHelper(1, 5)) 8549 return SDValue(N, 0); 8550 8551 break; 8552 } 8553 case ISD::ROTR: 8554 case ISD::ROTL: 8555 case RISCVISD::RORW: 8556 case RISCVISD::ROLW: { 8557 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8558 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8559 if (SimplifyDemandedLowBitsHelper(0, 32) || 8560 SimplifyDemandedLowBitsHelper(1, 5)) 8561 return SDValue(N, 0); 8562 } 8563 8564 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8565 } 8566 case RISCVISD::CLZW: 8567 case RISCVISD::CTZW: { 8568 // Only the lower 32 bits of the first operand are read 8569 if (SimplifyDemandedLowBitsHelper(0, 32)) 8570 return SDValue(N, 0); 8571 break; 8572 } 8573 case RISCVISD::GREV: 8574 case RISCVISD::GORC: { 8575 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8576 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8577 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8578 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8579 return SDValue(N, 0); 8580 8581 return combineGREVI_GORCI(N, DAG); 8582 } 8583 case RISCVISD::GREVW: 8584 case RISCVISD::GORCW: { 8585 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8586 if (SimplifyDemandedLowBitsHelper(0, 32) || 8587 SimplifyDemandedLowBitsHelper(1, 5)) 8588 return SDValue(N, 0); 8589 8590 break; 8591 } 8592 case RISCVISD::SHFL: 8593 case RISCVISD::UNSHFL: { 8594 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8595 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8596 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8597 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8598 return SDValue(N, 0); 8599 8600 break; 8601 } 8602 case RISCVISD::SHFLW: 8603 case RISCVISD::UNSHFLW: { 8604 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8605 if (SimplifyDemandedLowBitsHelper(0, 32) || 8606 SimplifyDemandedLowBitsHelper(1, 4)) 8607 return SDValue(N, 0); 8608 8609 break; 8610 } 8611 case RISCVISD::BCOMPRESSW: 8612 case RISCVISD::BDECOMPRESSW: { 8613 // Only the lower 32 bits of LHS and RHS are read. 8614 if (SimplifyDemandedLowBitsHelper(0, 32) || 8615 SimplifyDemandedLowBitsHelper(1, 32)) 8616 return SDValue(N, 0); 8617 8618 break; 8619 } 8620 case RISCVISD::FSR: 8621 case RISCVISD::FSL: 8622 case RISCVISD::FSRW: 8623 case RISCVISD::FSLW: { 8624 bool IsWInstruction = 8625 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8626 unsigned BitWidth = 8627 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8628 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8629 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8630 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8631 return SDValue(N, 0); 8632 8633 break; 8634 } 8635 case RISCVISD::FMV_X_ANYEXTH: 8636 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8637 SDLoc DL(N); 8638 SDValue Op0 = N->getOperand(0); 8639 MVT VT = N->getSimpleValueType(0); 8640 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8641 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8642 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8643 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8644 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8645 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8646 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8647 assert(Op0.getOperand(0).getValueType() == VT && 8648 "Unexpected value type!"); 8649 return Op0.getOperand(0); 8650 } 8651 8652 // This is a target-specific version of a DAGCombine performed in 8653 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8654 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8655 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8656 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8657 !Op0.getNode()->hasOneUse()) 8658 break; 8659 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8660 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8661 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8662 if (Op0.getOpcode() == ISD::FNEG) 8663 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8664 DAG.getConstant(SignBit, DL, VT)); 8665 8666 assert(Op0.getOpcode() == ISD::FABS); 8667 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8668 DAG.getConstant(~SignBit, DL, VT)); 8669 } 8670 case ISD::ADD: 8671 return performADDCombine(N, DAG, Subtarget); 8672 case ISD::SUB: 8673 return performSUBCombine(N, DAG); 8674 case ISD::AND: 8675 return performANDCombine(N, DAG, Subtarget); 8676 case ISD::OR: 8677 return performORCombine(N, DAG, Subtarget); 8678 case ISD::XOR: 8679 return performXORCombine(N, DAG); 8680 case ISD::FADD: 8681 case ISD::UMAX: 8682 case ISD::UMIN: 8683 case ISD::SMAX: 8684 case ISD::SMIN: 8685 case ISD::FMAXNUM: 8686 case ISD::FMINNUM: 8687 return combineBinOpToReduce(N, DAG); 8688 case ISD::SIGN_EXTEND_INREG: 8689 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8690 case ISD::ZERO_EXTEND: 8691 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8692 // type legalization. This is safe because fp_to_uint produces poison if 8693 // it overflows. 8694 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8695 SDValue Src = N->getOperand(0); 8696 if (Src.getOpcode() == ISD::FP_TO_UINT && 8697 isTypeLegal(Src.getOperand(0).getValueType())) 8698 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8699 Src.getOperand(0)); 8700 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8701 isTypeLegal(Src.getOperand(1).getValueType())) { 8702 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8703 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8704 Src.getOperand(0), Src.getOperand(1)); 8705 DCI.CombineTo(N, Res); 8706 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8707 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8708 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8709 } 8710 } 8711 return SDValue(); 8712 case RISCVISD::SELECT_CC: { 8713 // Transform 8714 SDValue LHS = N->getOperand(0); 8715 SDValue RHS = N->getOperand(1); 8716 SDValue TrueV = N->getOperand(3); 8717 SDValue FalseV = N->getOperand(4); 8718 8719 // If the True and False values are the same, we don't need a select_cc. 8720 if (TrueV == FalseV) 8721 return TrueV; 8722 8723 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8724 if (!ISD::isIntEqualitySetCC(CCVal)) 8725 break; 8726 8727 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8728 // (select_cc X, Y, lt, trueV, falseV) 8729 // Sometimes the setcc is introduced after select_cc has been formed. 8730 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8731 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8732 // If we're looking for eq 0 instead of ne 0, we need to invert the 8733 // condition. 8734 bool Invert = CCVal == ISD::SETEQ; 8735 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8736 if (Invert) 8737 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8738 8739 SDLoc DL(N); 8740 RHS = LHS.getOperand(1); 8741 LHS = LHS.getOperand(0); 8742 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8743 8744 SDValue TargetCC = DAG.getCondCode(CCVal); 8745 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8746 {LHS, RHS, TargetCC, TrueV, FalseV}); 8747 } 8748 8749 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8750 // (select_cc X, Y, eq/ne, trueV, falseV) 8751 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8752 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8753 {LHS.getOperand(0), LHS.getOperand(1), 8754 N->getOperand(2), TrueV, FalseV}); 8755 // (select_cc X, 1, setne, trueV, falseV) -> 8756 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8757 // This can occur when legalizing some floating point comparisons. 8758 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8759 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8760 SDLoc DL(N); 8761 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8762 SDValue TargetCC = DAG.getCondCode(CCVal); 8763 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8764 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8765 {LHS, RHS, TargetCC, TrueV, FalseV}); 8766 } 8767 8768 break; 8769 } 8770 case RISCVISD::BR_CC: { 8771 SDValue LHS = N->getOperand(1); 8772 SDValue RHS = N->getOperand(2); 8773 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8774 if (!ISD::isIntEqualitySetCC(CCVal)) 8775 break; 8776 8777 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8778 // (br_cc X, Y, lt, dest) 8779 // Sometimes the setcc is introduced after br_cc has been formed. 8780 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8781 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8782 // If we're looking for eq 0 instead of ne 0, we need to invert the 8783 // condition. 8784 bool Invert = CCVal == ISD::SETEQ; 8785 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8786 if (Invert) 8787 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8788 8789 SDLoc DL(N); 8790 RHS = LHS.getOperand(1); 8791 LHS = LHS.getOperand(0); 8792 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8793 8794 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8795 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8796 N->getOperand(4)); 8797 } 8798 8799 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8800 // (br_cc X, Y, eq/ne, trueV, falseV) 8801 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8802 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8803 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8804 N->getOperand(3), N->getOperand(4)); 8805 8806 // (br_cc X, 1, setne, br_cc) -> 8807 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8808 // This can occur when legalizing some floating point comparisons. 8809 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8810 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8811 SDLoc DL(N); 8812 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8813 SDValue TargetCC = DAG.getCondCode(CCVal); 8814 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8815 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8816 N->getOperand(0), LHS, RHS, TargetCC, 8817 N->getOperand(4)); 8818 } 8819 break; 8820 } 8821 case ISD::BITREVERSE: 8822 return performBITREVERSECombine(N, DAG, Subtarget); 8823 case ISD::FP_TO_SINT: 8824 case ISD::FP_TO_UINT: 8825 return performFP_TO_INTCombine(N, DCI, Subtarget); 8826 case ISD::FP_TO_SINT_SAT: 8827 case ISD::FP_TO_UINT_SAT: 8828 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8829 case ISD::FCOPYSIGN: { 8830 EVT VT = N->getValueType(0); 8831 if (!VT.isVector()) 8832 break; 8833 // There is a form of VFSGNJ which injects the negated sign of its second 8834 // operand. Try and bubble any FNEG up after the extend/round to produce 8835 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8836 // TRUNC=1. 8837 SDValue In2 = N->getOperand(1); 8838 // Avoid cases where the extend/round has multiple uses, as duplicating 8839 // those is typically more expensive than removing a fneg. 8840 if (!In2.hasOneUse()) 8841 break; 8842 if (In2.getOpcode() != ISD::FP_EXTEND && 8843 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8844 break; 8845 In2 = In2.getOperand(0); 8846 if (In2.getOpcode() != ISD::FNEG) 8847 break; 8848 SDLoc DL(N); 8849 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8850 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8851 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8852 } 8853 case ISD::MGATHER: 8854 case ISD::MSCATTER: 8855 case ISD::VP_GATHER: 8856 case ISD::VP_SCATTER: { 8857 if (!DCI.isBeforeLegalize()) 8858 break; 8859 SDValue Index, ScaleOp; 8860 bool IsIndexScaled = false; 8861 bool IsIndexSigned = false; 8862 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8863 Index = VPGSN->getIndex(); 8864 ScaleOp = VPGSN->getScale(); 8865 IsIndexScaled = VPGSN->isIndexScaled(); 8866 IsIndexSigned = VPGSN->isIndexSigned(); 8867 } else { 8868 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8869 Index = MGSN->getIndex(); 8870 ScaleOp = MGSN->getScale(); 8871 IsIndexScaled = MGSN->isIndexScaled(); 8872 IsIndexSigned = MGSN->isIndexSigned(); 8873 } 8874 EVT IndexVT = Index.getValueType(); 8875 MVT XLenVT = Subtarget.getXLenVT(); 8876 // RISCV indexed loads only support the "unsigned unscaled" addressing 8877 // mode, so anything else must be manually legalized. 8878 bool NeedsIdxLegalization = 8879 IsIndexScaled || 8880 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8881 if (!NeedsIdxLegalization) 8882 break; 8883 8884 SDLoc DL(N); 8885 8886 // Any index legalization should first promote to XLenVT, so we don't lose 8887 // bits when scaling. This may create an illegal index type so we let 8888 // LLVM's legalization take care of the splitting. 8889 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8890 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8891 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8892 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8893 DL, IndexVT, Index); 8894 } 8895 8896 if (IsIndexScaled) { 8897 // Manually scale the indices. 8898 // TODO: Sanitize the scale operand here? 8899 // TODO: For VP nodes, should we use VP_SHL here? 8900 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8901 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8902 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8903 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8904 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 8905 } 8906 8907 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 8908 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8909 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8910 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8911 ScaleOp, VPGN->getMask(), 8912 VPGN->getVectorLength()}, 8913 VPGN->getMemOperand(), NewIndexTy); 8914 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8915 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8916 {VPSN->getChain(), VPSN->getValue(), 8917 VPSN->getBasePtr(), Index, ScaleOp, 8918 VPSN->getMask(), VPSN->getVectorLength()}, 8919 VPSN->getMemOperand(), NewIndexTy); 8920 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8921 return DAG.getMaskedGather( 8922 N->getVTList(), MGN->getMemoryVT(), DL, 8923 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8924 MGN->getBasePtr(), Index, ScaleOp}, 8925 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8926 const auto *MSN = cast<MaskedScatterSDNode>(N); 8927 return DAG.getMaskedScatter( 8928 N->getVTList(), MSN->getMemoryVT(), DL, 8929 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8930 Index, ScaleOp}, 8931 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8932 } 8933 case RISCVISD::SRA_VL: 8934 case RISCVISD::SRL_VL: 8935 case RISCVISD::SHL_VL: { 8936 SDValue ShAmt = N->getOperand(1); 8937 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8938 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8939 SDLoc DL(N); 8940 SDValue VL = N->getOperand(3); 8941 EVT VT = N->getValueType(0); 8942 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8943 ShAmt.getOperand(1), VL); 8944 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8945 N->getOperand(2), N->getOperand(3)); 8946 } 8947 break; 8948 } 8949 case ISD::SRA: 8950 case ISD::SRL: 8951 case ISD::SHL: { 8952 SDValue ShAmt = N->getOperand(1); 8953 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8954 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8955 SDLoc DL(N); 8956 EVT VT = N->getValueType(0); 8957 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8958 ShAmt.getOperand(1), 8959 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8960 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8961 } 8962 break; 8963 } 8964 case RISCVISD::ADD_VL: 8965 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8966 return V; 8967 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8968 case RISCVISD::SUB_VL: 8969 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8970 case RISCVISD::VWADD_W_VL: 8971 case RISCVISD::VWADDU_W_VL: 8972 case RISCVISD::VWSUB_W_VL: 8973 case RISCVISD::VWSUBU_W_VL: 8974 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8975 case RISCVISD::MUL_VL: 8976 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8977 return V; 8978 // Mul is commutative. 8979 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8980 case ISD::STORE: { 8981 auto *Store = cast<StoreSDNode>(N); 8982 SDValue Val = Store->getValue(); 8983 // Combine store of vmv.x.s to vse with VL of 1. 8984 // FIXME: Support FP. 8985 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8986 SDValue Src = Val.getOperand(0); 8987 EVT VecVT = Src.getValueType(); 8988 EVT MemVT = Store->getMemoryVT(); 8989 // The memory VT and the element type must match. 8990 if (VecVT.getVectorElementType() == MemVT) { 8991 SDLoc DL(N); 8992 MVT MaskVT = getMaskTypeFor(VecVT); 8993 return DAG.getStoreVP( 8994 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8995 DAG.getConstant(1, DL, MaskVT), 8996 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8997 Store->getMemOperand(), Store->getAddressingMode(), 8998 Store->isTruncatingStore(), /*IsCompress*/ false); 8999 } 9000 } 9001 9002 break; 9003 } 9004 case ISD::SPLAT_VECTOR: { 9005 EVT VT = N->getValueType(0); 9006 // Only perform this combine on legal MVT types. 9007 if (!isTypeLegal(VT)) 9008 break; 9009 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9010 DAG, Subtarget)) 9011 return Gather; 9012 break; 9013 } 9014 case RISCVISD::VMV_V_X_VL: { 9015 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9016 // scalar input. 9017 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9018 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9019 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9020 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9021 return SDValue(N, 0); 9022 9023 break; 9024 } 9025 case ISD::INTRINSIC_WO_CHAIN: { 9026 unsigned IntNo = N->getConstantOperandVal(0); 9027 switch (IntNo) { 9028 // By default we do not combine any intrinsic. 9029 default: 9030 return SDValue(); 9031 case Intrinsic::riscv_vcpop: 9032 case Intrinsic::riscv_vcpop_mask: 9033 case Intrinsic::riscv_vfirst: 9034 case Intrinsic::riscv_vfirst_mask: { 9035 SDValue VL = N->getOperand(2); 9036 if (IntNo == Intrinsic::riscv_vcpop_mask || 9037 IntNo == Intrinsic::riscv_vfirst_mask) 9038 VL = N->getOperand(3); 9039 if (!isNullConstant(VL)) 9040 return SDValue(); 9041 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9042 SDLoc DL(N); 9043 EVT VT = N->getValueType(0); 9044 if (IntNo == Intrinsic::riscv_vfirst || 9045 IntNo == Intrinsic::riscv_vfirst_mask) 9046 return DAG.getConstant(-1, DL, VT); 9047 return DAG.getConstant(0, DL, VT); 9048 } 9049 } 9050 } 9051 } 9052 9053 return SDValue(); 9054 } 9055 9056 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9057 const SDNode *N, CombineLevel Level) const { 9058 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9059 // materialised in fewer instructions than `(OP _, c1)`: 9060 // 9061 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9062 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9063 SDValue N0 = N->getOperand(0); 9064 EVT Ty = N0.getValueType(); 9065 if (Ty.isScalarInteger() && 9066 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9067 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9068 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9069 if (C1 && C2) { 9070 const APInt &C1Int = C1->getAPIntValue(); 9071 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9072 9073 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9074 // and the combine should happen, to potentially allow further combines 9075 // later. 9076 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9077 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9078 return true; 9079 9080 // We can materialise `c1` in an add immediate, so it's "free", and the 9081 // combine should be prevented. 9082 if (C1Int.getMinSignedBits() <= 64 && 9083 isLegalAddImmediate(C1Int.getSExtValue())) 9084 return false; 9085 9086 // Neither constant will fit into an immediate, so find materialisation 9087 // costs. 9088 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9089 Subtarget.getFeatureBits(), 9090 /*CompressionCost*/true); 9091 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9092 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9093 /*CompressionCost*/true); 9094 9095 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9096 // combine should be prevented. 9097 if (C1Cost < ShiftedC1Cost) 9098 return false; 9099 } 9100 } 9101 return true; 9102 } 9103 9104 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9105 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9106 TargetLoweringOpt &TLO) const { 9107 // Delay this optimization as late as possible. 9108 if (!TLO.LegalOps) 9109 return false; 9110 9111 EVT VT = Op.getValueType(); 9112 if (VT.isVector()) 9113 return false; 9114 9115 // Only handle AND for now. 9116 if (Op.getOpcode() != ISD::AND) 9117 return false; 9118 9119 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9120 if (!C) 9121 return false; 9122 9123 const APInt &Mask = C->getAPIntValue(); 9124 9125 // Clear all non-demanded bits initially. 9126 APInt ShrunkMask = Mask & DemandedBits; 9127 9128 // Try to make a smaller immediate by setting undemanded bits. 9129 9130 APInt ExpandedMask = Mask | ~DemandedBits; 9131 9132 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9133 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9134 }; 9135 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9136 if (NewMask == Mask) 9137 return true; 9138 SDLoc DL(Op); 9139 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9140 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9141 return TLO.CombineTo(Op, NewOp); 9142 }; 9143 9144 // If the shrunk mask fits in sign extended 12 bits, let the target 9145 // independent code apply it. 9146 if (ShrunkMask.isSignedIntN(12)) 9147 return false; 9148 9149 // Preserve (and X, 0xffff) when zext.h is supported. 9150 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9151 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9152 if (IsLegalMask(NewMask)) 9153 return UseMask(NewMask); 9154 } 9155 9156 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9157 if (VT == MVT::i64) { 9158 APInt NewMask = APInt(64, 0xffffffff); 9159 if (IsLegalMask(NewMask)) 9160 return UseMask(NewMask); 9161 } 9162 9163 // For the remaining optimizations, we need to be able to make a negative 9164 // number through a combination of mask and undemanded bits. 9165 if (!ExpandedMask.isNegative()) 9166 return false; 9167 9168 // What is the fewest number of bits we need to represent the negative number. 9169 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9170 9171 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9172 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9173 APInt NewMask = ShrunkMask; 9174 if (MinSignedBits <= 12) 9175 NewMask.setBitsFrom(11); 9176 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9177 NewMask.setBitsFrom(31); 9178 else 9179 return false; 9180 9181 // Check that our new mask is a subset of the demanded mask. 9182 assert(IsLegalMask(NewMask)); 9183 return UseMask(NewMask); 9184 } 9185 9186 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9187 static const uint64_t GREVMasks[] = { 9188 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9189 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9190 9191 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9192 unsigned Shift = 1 << Stage; 9193 if (ShAmt & Shift) { 9194 uint64_t Mask = GREVMasks[Stage]; 9195 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9196 if (IsGORC) 9197 Res |= x; 9198 x = Res; 9199 } 9200 } 9201 9202 return x; 9203 } 9204 9205 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9206 KnownBits &Known, 9207 const APInt &DemandedElts, 9208 const SelectionDAG &DAG, 9209 unsigned Depth) const { 9210 unsigned BitWidth = Known.getBitWidth(); 9211 unsigned Opc = Op.getOpcode(); 9212 assert((Opc >= ISD::BUILTIN_OP_END || 9213 Opc == ISD::INTRINSIC_WO_CHAIN || 9214 Opc == ISD::INTRINSIC_W_CHAIN || 9215 Opc == ISD::INTRINSIC_VOID) && 9216 "Should use MaskedValueIsZero if you don't know whether Op" 9217 " is a target node!"); 9218 9219 Known.resetAll(); 9220 switch (Opc) { 9221 default: break; 9222 case RISCVISD::SELECT_CC: { 9223 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9224 // If we don't know any bits, early out. 9225 if (Known.isUnknown()) 9226 break; 9227 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9228 9229 // Only known if known in both the LHS and RHS. 9230 Known = KnownBits::commonBits(Known, Known2); 9231 break; 9232 } 9233 case RISCVISD::REMUW: { 9234 KnownBits Known2; 9235 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9236 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9237 // We only care about the lower 32 bits. 9238 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9239 // Restore the original width by sign extending. 9240 Known = Known.sext(BitWidth); 9241 break; 9242 } 9243 case RISCVISD::DIVUW: { 9244 KnownBits Known2; 9245 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9246 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9247 // We only care about the lower 32 bits. 9248 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9249 // Restore the original width by sign extending. 9250 Known = Known.sext(BitWidth); 9251 break; 9252 } 9253 case RISCVISD::CTZW: { 9254 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9255 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9256 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9257 Known.Zero.setBitsFrom(LowBits); 9258 break; 9259 } 9260 case RISCVISD::CLZW: { 9261 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9262 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9263 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9264 Known.Zero.setBitsFrom(LowBits); 9265 break; 9266 } 9267 case RISCVISD::GREV: 9268 case RISCVISD::GORC: { 9269 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9270 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9271 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9272 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9273 // To compute zeros, we need to invert the value and invert it back after. 9274 Known.Zero = 9275 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9276 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9277 } 9278 break; 9279 } 9280 case RISCVISD::READ_VLENB: { 9281 // If we know the minimum VLen from Zvl extensions, we can use that to 9282 // determine the trailing zeros of VLENB. 9283 // FIXME: Limit to 128 bit vectors until we have more testing. 9284 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9285 if (MinVLenB > 0) 9286 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9287 // We assume VLENB is no more than 65536 / 8 bytes. 9288 Known.Zero.setBitsFrom(14); 9289 break; 9290 } 9291 case ISD::INTRINSIC_W_CHAIN: 9292 case ISD::INTRINSIC_WO_CHAIN: { 9293 unsigned IntNo = 9294 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9295 switch (IntNo) { 9296 default: 9297 // We can't do anything for most intrinsics. 9298 break; 9299 case Intrinsic::riscv_vsetvli: 9300 case Intrinsic::riscv_vsetvlimax: 9301 case Intrinsic::riscv_vsetvli_opt: 9302 case Intrinsic::riscv_vsetvlimax_opt: 9303 // Assume that VL output is positive and would fit in an int32_t. 9304 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9305 if (BitWidth >= 32) 9306 Known.Zero.setBitsFrom(31); 9307 break; 9308 } 9309 break; 9310 } 9311 } 9312 } 9313 9314 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9315 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9316 unsigned Depth) const { 9317 switch (Op.getOpcode()) { 9318 default: 9319 break; 9320 case RISCVISD::SELECT_CC: { 9321 unsigned Tmp = 9322 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9323 if (Tmp == 1) return 1; // Early out. 9324 unsigned Tmp2 = 9325 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9326 return std::min(Tmp, Tmp2); 9327 } 9328 case RISCVISD::SLLW: 9329 case RISCVISD::SRAW: 9330 case RISCVISD::SRLW: 9331 case RISCVISD::DIVW: 9332 case RISCVISD::DIVUW: 9333 case RISCVISD::REMUW: 9334 case RISCVISD::ROLW: 9335 case RISCVISD::RORW: 9336 case RISCVISD::GREVW: 9337 case RISCVISD::GORCW: 9338 case RISCVISD::FSLW: 9339 case RISCVISD::FSRW: 9340 case RISCVISD::SHFLW: 9341 case RISCVISD::UNSHFLW: 9342 case RISCVISD::BCOMPRESSW: 9343 case RISCVISD::BDECOMPRESSW: 9344 case RISCVISD::BFPW: 9345 case RISCVISD::FCVT_W_RV64: 9346 case RISCVISD::FCVT_WU_RV64: 9347 case RISCVISD::STRICT_FCVT_W_RV64: 9348 case RISCVISD::STRICT_FCVT_WU_RV64: 9349 // TODO: As the result is sign-extended, this is conservatively correct. A 9350 // more precise answer could be calculated for SRAW depending on known 9351 // bits in the shift amount. 9352 return 33; 9353 case RISCVISD::SHFL: 9354 case RISCVISD::UNSHFL: { 9355 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9356 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9357 // will stay within the upper 32 bits. If there were more than 32 sign bits 9358 // before there will be at least 33 sign bits after. 9359 if (Op.getValueType() == MVT::i64 && 9360 isa<ConstantSDNode>(Op.getOperand(1)) && 9361 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9362 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9363 if (Tmp > 32) 9364 return 33; 9365 } 9366 break; 9367 } 9368 case RISCVISD::VMV_X_S: { 9369 // The number of sign bits of the scalar result is computed by obtaining the 9370 // element type of the input vector operand, subtracting its width from the 9371 // XLEN, and then adding one (sign bit within the element type). If the 9372 // element type is wider than XLen, the least-significant XLEN bits are 9373 // taken. 9374 unsigned XLen = Subtarget.getXLen(); 9375 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9376 if (EltBits <= XLen) 9377 return XLen - EltBits + 1; 9378 break; 9379 } 9380 } 9381 9382 return 1; 9383 } 9384 9385 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9386 MachineBasicBlock *BB) { 9387 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9388 9389 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9390 // Should the count have wrapped while it was being read, we need to try 9391 // again. 9392 // ... 9393 // read: 9394 // rdcycleh x3 # load high word of cycle 9395 // rdcycle x2 # load low word of cycle 9396 // rdcycleh x4 # load high word of cycle 9397 // bne x3, x4, read # check if high word reads match, otherwise try again 9398 // ... 9399 9400 MachineFunction &MF = *BB->getParent(); 9401 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9402 MachineFunction::iterator It = ++BB->getIterator(); 9403 9404 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9405 MF.insert(It, LoopMBB); 9406 9407 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9408 MF.insert(It, DoneMBB); 9409 9410 // Transfer the remainder of BB and its successor edges to DoneMBB. 9411 DoneMBB->splice(DoneMBB->begin(), BB, 9412 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9413 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9414 9415 BB->addSuccessor(LoopMBB); 9416 9417 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9418 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9419 Register LoReg = MI.getOperand(0).getReg(); 9420 Register HiReg = MI.getOperand(1).getReg(); 9421 DebugLoc DL = MI.getDebugLoc(); 9422 9423 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9424 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9425 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9426 .addReg(RISCV::X0); 9427 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9428 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9429 .addReg(RISCV::X0); 9430 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9431 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9432 .addReg(RISCV::X0); 9433 9434 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9435 .addReg(HiReg) 9436 .addReg(ReadAgainReg) 9437 .addMBB(LoopMBB); 9438 9439 LoopMBB->addSuccessor(LoopMBB); 9440 LoopMBB->addSuccessor(DoneMBB); 9441 9442 MI.eraseFromParent(); 9443 9444 return DoneMBB; 9445 } 9446 9447 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9448 MachineBasicBlock *BB) { 9449 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9450 9451 MachineFunction &MF = *BB->getParent(); 9452 DebugLoc DL = MI.getDebugLoc(); 9453 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9454 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9455 Register LoReg = MI.getOperand(0).getReg(); 9456 Register HiReg = MI.getOperand(1).getReg(); 9457 Register SrcReg = MI.getOperand(2).getReg(); 9458 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9459 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9460 9461 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9462 RI); 9463 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9464 MachineMemOperand *MMOLo = 9465 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9466 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9467 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9468 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9469 .addFrameIndex(FI) 9470 .addImm(0) 9471 .addMemOperand(MMOLo); 9472 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9473 .addFrameIndex(FI) 9474 .addImm(4) 9475 .addMemOperand(MMOHi); 9476 MI.eraseFromParent(); // The pseudo instruction is gone now. 9477 return BB; 9478 } 9479 9480 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9481 MachineBasicBlock *BB) { 9482 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9483 "Unexpected instruction"); 9484 9485 MachineFunction &MF = *BB->getParent(); 9486 DebugLoc DL = MI.getDebugLoc(); 9487 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9488 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9489 Register DstReg = MI.getOperand(0).getReg(); 9490 Register LoReg = MI.getOperand(1).getReg(); 9491 Register HiReg = MI.getOperand(2).getReg(); 9492 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9493 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9494 9495 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9496 MachineMemOperand *MMOLo = 9497 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9498 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9499 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9500 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9501 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9502 .addFrameIndex(FI) 9503 .addImm(0) 9504 .addMemOperand(MMOLo); 9505 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9506 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9507 .addFrameIndex(FI) 9508 .addImm(4) 9509 .addMemOperand(MMOHi); 9510 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9511 MI.eraseFromParent(); // The pseudo instruction is gone now. 9512 return BB; 9513 } 9514 9515 static bool isSelectPseudo(MachineInstr &MI) { 9516 switch (MI.getOpcode()) { 9517 default: 9518 return false; 9519 case RISCV::Select_GPR_Using_CC_GPR: 9520 case RISCV::Select_FPR16_Using_CC_GPR: 9521 case RISCV::Select_FPR32_Using_CC_GPR: 9522 case RISCV::Select_FPR64_Using_CC_GPR: 9523 return true; 9524 } 9525 } 9526 9527 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9528 unsigned RelOpcode, unsigned EqOpcode, 9529 const RISCVSubtarget &Subtarget) { 9530 DebugLoc DL = MI.getDebugLoc(); 9531 Register DstReg = MI.getOperand(0).getReg(); 9532 Register Src1Reg = MI.getOperand(1).getReg(); 9533 Register Src2Reg = MI.getOperand(2).getReg(); 9534 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9535 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9536 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9537 9538 // Save the current FFLAGS. 9539 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9540 9541 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9542 .addReg(Src1Reg) 9543 .addReg(Src2Reg); 9544 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9545 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9546 9547 // Restore the FFLAGS. 9548 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9549 .addReg(SavedFFlags, RegState::Kill); 9550 9551 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9552 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9553 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9554 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9555 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9556 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9557 9558 // Erase the pseudoinstruction. 9559 MI.eraseFromParent(); 9560 return BB; 9561 } 9562 9563 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9564 MachineBasicBlock *BB, 9565 const RISCVSubtarget &Subtarget) { 9566 // To "insert" Select_* instructions, we actually have to insert the triangle 9567 // control-flow pattern. The incoming instructions know the destination vreg 9568 // to set, the condition code register to branch on, the true/false values to 9569 // select between, and the condcode to use to select the appropriate branch. 9570 // 9571 // We produce the following control flow: 9572 // HeadMBB 9573 // | \ 9574 // | IfFalseMBB 9575 // | / 9576 // TailMBB 9577 // 9578 // When we find a sequence of selects we attempt to optimize their emission 9579 // by sharing the control flow. Currently we only handle cases where we have 9580 // multiple selects with the exact same condition (same LHS, RHS and CC). 9581 // The selects may be interleaved with other instructions if the other 9582 // instructions meet some requirements we deem safe: 9583 // - They are debug instructions. Otherwise, 9584 // - They do not have side-effects, do not access memory and their inputs do 9585 // not depend on the results of the select pseudo-instructions. 9586 // The TrueV/FalseV operands of the selects cannot depend on the result of 9587 // previous selects in the sequence. 9588 // These conditions could be further relaxed. See the X86 target for a 9589 // related approach and more information. 9590 Register LHS = MI.getOperand(1).getReg(); 9591 Register RHS = MI.getOperand(2).getReg(); 9592 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9593 9594 SmallVector<MachineInstr *, 4> SelectDebugValues; 9595 SmallSet<Register, 4> SelectDests; 9596 SelectDests.insert(MI.getOperand(0).getReg()); 9597 9598 MachineInstr *LastSelectPseudo = &MI; 9599 9600 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9601 SequenceMBBI != E; ++SequenceMBBI) { 9602 if (SequenceMBBI->isDebugInstr()) 9603 continue; 9604 if (isSelectPseudo(*SequenceMBBI)) { 9605 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9606 SequenceMBBI->getOperand(2).getReg() != RHS || 9607 SequenceMBBI->getOperand(3).getImm() != CC || 9608 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9609 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9610 break; 9611 LastSelectPseudo = &*SequenceMBBI; 9612 SequenceMBBI->collectDebugValues(SelectDebugValues); 9613 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9614 } else { 9615 if (SequenceMBBI->hasUnmodeledSideEffects() || 9616 SequenceMBBI->mayLoadOrStore()) 9617 break; 9618 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9619 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9620 })) 9621 break; 9622 } 9623 } 9624 9625 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9626 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9627 DebugLoc DL = MI.getDebugLoc(); 9628 MachineFunction::iterator I = ++BB->getIterator(); 9629 9630 MachineBasicBlock *HeadMBB = BB; 9631 MachineFunction *F = BB->getParent(); 9632 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9633 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9634 9635 F->insert(I, IfFalseMBB); 9636 F->insert(I, TailMBB); 9637 9638 // Transfer debug instructions associated with the selects to TailMBB. 9639 for (MachineInstr *DebugInstr : SelectDebugValues) { 9640 TailMBB->push_back(DebugInstr->removeFromParent()); 9641 } 9642 9643 // Move all instructions after the sequence to TailMBB. 9644 TailMBB->splice(TailMBB->end(), HeadMBB, 9645 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9646 // Update machine-CFG edges by transferring all successors of the current 9647 // block to the new block which will contain the Phi nodes for the selects. 9648 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9649 // Set the successors for HeadMBB. 9650 HeadMBB->addSuccessor(IfFalseMBB); 9651 HeadMBB->addSuccessor(TailMBB); 9652 9653 // Insert appropriate branch. 9654 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9655 .addReg(LHS) 9656 .addReg(RHS) 9657 .addMBB(TailMBB); 9658 9659 // IfFalseMBB just falls through to TailMBB. 9660 IfFalseMBB->addSuccessor(TailMBB); 9661 9662 // Create PHIs for all of the select pseudo-instructions. 9663 auto SelectMBBI = MI.getIterator(); 9664 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9665 auto InsertionPoint = TailMBB->begin(); 9666 while (SelectMBBI != SelectEnd) { 9667 auto Next = std::next(SelectMBBI); 9668 if (isSelectPseudo(*SelectMBBI)) { 9669 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9670 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9671 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9672 .addReg(SelectMBBI->getOperand(4).getReg()) 9673 .addMBB(HeadMBB) 9674 .addReg(SelectMBBI->getOperand(5).getReg()) 9675 .addMBB(IfFalseMBB); 9676 SelectMBBI->eraseFromParent(); 9677 } 9678 SelectMBBI = Next; 9679 } 9680 9681 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9682 return TailMBB; 9683 } 9684 9685 MachineBasicBlock * 9686 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9687 MachineBasicBlock *BB) const { 9688 switch (MI.getOpcode()) { 9689 default: 9690 llvm_unreachable("Unexpected instr type to insert"); 9691 case RISCV::ReadCycleWide: 9692 assert(!Subtarget.is64Bit() && 9693 "ReadCycleWrite is only to be used on riscv32"); 9694 return emitReadCycleWidePseudo(MI, BB); 9695 case RISCV::Select_GPR_Using_CC_GPR: 9696 case RISCV::Select_FPR16_Using_CC_GPR: 9697 case RISCV::Select_FPR32_Using_CC_GPR: 9698 case RISCV::Select_FPR64_Using_CC_GPR: 9699 return emitSelectPseudo(MI, BB, Subtarget); 9700 case RISCV::BuildPairF64Pseudo: 9701 return emitBuildPairF64Pseudo(MI, BB); 9702 case RISCV::SplitF64Pseudo: 9703 return emitSplitF64Pseudo(MI, BB); 9704 case RISCV::PseudoQuietFLE_H: 9705 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9706 case RISCV::PseudoQuietFLT_H: 9707 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9708 case RISCV::PseudoQuietFLE_S: 9709 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9710 case RISCV::PseudoQuietFLT_S: 9711 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9712 case RISCV::PseudoQuietFLE_D: 9713 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9714 case RISCV::PseudoQuietFLT_D: 9715 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9716 } 9717 } 9718 9719 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9720 SDNode *Node) const { 9721 // Add FRM dependency to any instructions with dynamic rounding mode. 9722 unsigned Opc = MI.getOpcode(); 9723 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9724 if (Idx < 0) 9725 return; 9726 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9727 return; 9728 // If the instruction already reads FRM, don't add another read. 9729 if (MI.readsRegister(RISCV::FRM)) 9730 return; 9731 MI.addOperand( 9732 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9733 } 9734 9735 // Calling Convention Implementation. 9736 // The expectations for frontend ABI lowering vary from target to target. 9737 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9738 // details, but this is a longer term goal. For now, we simply try to keep the 9739 // role of the frontend as simple and well-defined as possible. The rules can 9740 // be summarised as: 9741 // * Never split up large scalar arguments. We handle them here. 9742 // * If a hardfloat calling convention is being used, and the struct may be 9743 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9744 // available, then pass as two separate arguments. If either the GPRs or FPRs 9745 // are exhausted, then pass according to the rule below. 9746 // * If a struct could never be passed in registers or directly in a stack 9747 // slot (as it is larger than 2*XLEN and the floating point rules don't 9748 // apply), then pass it using a pointer with the byval attribute. 9749 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9750 // word-sized array or a 2*XLEN scalar (depending on alignment). 9751 // * The frontend can determine whether a struct is returned by reference or 9752 // not based on its size and fields. If it will be returned by reference, the 9753 // frontend must modify the prototype so a pointer with the sret annotation is 9754 // passed as the first argument. This is not necessary for large scalar 9755 // returns. 9756 // * Struct return values and varargs should be coerced to structs containing 9757 // register-size fields in the same situations they would be for fixed 9758 // arguments. 9759 9760 static const MCPhysReg ArgGPRs[] = { 9761 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9762 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9763 }; 9764 static const MCPhysReg ArgFPR16s[] = { 9765 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9766 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9767 }; 9768 static const MCPhysReg ArgFPR32s[] = { 9769 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9770 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9771 }; 9772 static const MCPhysReg ArgFPR64s[] = { 9773 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9774 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9775 }; 9776 // This is an interim calling convention and it may be changed in the future. 9777 static const MCPhysReg ArgVRs[] = { 9778 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9779 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9780 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9781 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9782 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9783 RISCV::V20M2, RISCV::V22M2}; 9784 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9785 RISCV::V20M4}; 9786 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9787 9788 // Pass a 2*XLEN argument that has been split into two XLEN values through 9789 // registers or the stack as necessary. 9790 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9791 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9792 MVT ValVT2, MVT LocVT2, 9793 ISD::ArgFlagsTy ArgFlags2) { 9794 unsigned XLenInBytes = XLen / 8; 9795 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9796 // At least one half can be passed via register. 9797 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9798 VA1.getLocVT(), CCValAssign::Full)); 9799 } else { 9800 // Both halves must be passed on the stack, with proper alignment. 9801 Align StackAlign = 9802 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9803 State.addLoc( 9804 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9805 State.AllocateStack(XLenInBytes, StackAlign), 9806 VA1.getLocVT(), CCValAssign::Full)); 9807 State.addLoc(CCValAssign::getMem( 9808 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9809 LocVT2, CCValAssign::Full)); 9810 return false; 9811 } 9812 9813 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9814 // The second half can also be passed via register. 9815 State.addLoc( 9816 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9817 } else { 9818 // The second half is passed via the stack, without additional alignment. 9819 State.addLoc(CCValAssign::getMem( 9820 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9821 LocVT2, CCValAssign::Full)); 9822 } 9823 9824 return false; 9825 } 9826 9827 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9828 Optional<unsigned> FirstMaskArgument, 9829 CCState &State, const RISCVTargetLowering &TLI) { 9830 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9831 if (RC == &RISCV::VRRegClass) { 9832 // Assign the first mask argument to V0. 9833 // This is an interim calling convention and it may be changed in the 9834 // future. 9835 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9836 return State.AllocateReg(RISCV::V0); 9837 return State.AllocateReg(ArgVRs); 9838 } 9839 if (RC == &RISCV::VRM2RegClass) 9840 return State.AllocateReg(ArgVRM2s); 9841 if (RC == &RISCV::VRM4RegClass) 9842 return State.AllocateReg(ArgVRM4s); 9843 if (RC == &RISCV::VRM8RegClass) 9844 return State.AllocateReg(ArgVRM8s); 9845 llvm_unreachable("Unhandled register class for ValueType"); 9846 } 9847 9848 // Implements the RISC-V calling convention. Returns true upon failure. 9849 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9850 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9851 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9852 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9853 Optional<unsigned> FirstMaskArgument) { 9854 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9855 assert(XLen == 32 || XLen == 64); 9856 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9857 9858 // Any return value split in to more than two values can't be returned 9859 // directly. Vectors are returned via the available vector registers. 9860 if (!LocVT.isVector() && IsRet && ValNo > 1) 9861 return true; 9862 9863 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9864 // variadic argument, or if no F16/F32 argument registers are available. 9865 bool UseGPRForF16_F32 = true; 9866 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9867 // variadic argument, or if no F64 argument registers are available. 9868 bool UseGPRForF64 = true; 9869 9870 switch (ABI) { 9871 default: 9872 llvm_unreachable("Unexpected ABI"); 9873 case RISCVABI::ABI_ILP32: 9874 case RISCVABI::ABI_LP64: 9875 break; 9876 case RISCVABI::ABI_ILP32F: 9877 case RISCVABI::ABI_LP64F: 9878 UseGPRForF16_F32 = !IsFixed; 9879 break; 9880 case RISCVABI::ABI_ILP32D: 9881 case RISCVABI::ABI_LP64D: 9882 UseGPRForF16_F32 = !IsFixed; 9883 UseGPRForF64 = !IsFixed; 9884 break; 9885 } 9886 9887 // FPR16, FPR32, and FPR64 alias each other. 9888 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9889 UseGPRForF16_F32 = true; 9890 UseGPRForF64 = true; 9891 } 9892 9893 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9894 // similar local variables rather than directly checking against the target 9895 // ABI. 9896 9897 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9898 LocVT = XLenVT; 9899 LocInfo = CCValAssign::BCvt; 9900 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9901 LocVT = MVT::i64; 9902 LocInfo = CCValAssign::BCvt; 9903 } 9904 9905 // If this is a variadic argument, the RISC-V calling convention requires 9906 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9907 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9908 // be used regardless of whether the original argument was split during 9909 // legalisation or not. The argument will not be passed by registers if the 9910 // original type is larger than 2*XLEN, so the register alignment rule does 9911 // not apply. 9912 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9913 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9914 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9915 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9916 // Skip 'odd' register if necessary. 9917 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9918 State.AllocateReg(ArgGPRs); 9919 } 9920 9921 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9922 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9923 State.getPendingArgFlags(); 9924 9925 assert(PendingLocs.size() == PendingArgFlags.size() && 9926 "PendingLocs and PendingArgFlags out of sync"); 9927 9928 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9929 // registers are exhausted. 9930 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9931 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9932 "Can't lower f64 if it is split"); 9933 // Depending on available argument GPRS, f64 may be passed in a pair of 9934 // GPRs, split between a GPR and the stack, or passed completely on the 9935 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9936 // cases. 9937 Register Reg = State.AllocateReg(ArgGPRs); 9938 LocVT = MVT::i32; 9939 if (!Reg) { 9940 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9941 State.addLoc( 9942 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9943 return false; 9944 } 9945 if (!State.AllocateReg(ArgGPRs)) 9946 State.AllocateStack(4, Align(4)); 9947 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9948 return false; 9949 } 9950 9951 // Fixed-length vectors are located in the corresponding scalable-vector 9952 // container types. 9953 if (ValVT.isFixedLengthVector()) 9954 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9955 9956 // Split arguments might be passed indirectly, so keep track of the pending 9957 // values. Split vectors are passed via a mix of registers and indirectly, so 9958 // treat them as we would any other argument. 9959 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9960 LocVT = XLenVT; 9961 LocInfo = CCValAssign::Indirect; 9962 PendingLocs.push_back( 9963 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9964 PendingArgFlags.push_back(ArgFlags); 9965 if (!ArgFlags.isSplitEnd()) { 9966 return false; 9967 } 9968 } 9969 9970 // If the split argument only had two elements, it should be passed directly 9971 // in registers or on the stack. 9972 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9973 PendingLocs.size() <= 2) { 9974 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9975 // Apply the normal calling convention rules to the first half of the 9976 // split argument. 9977 CCValAssign VA = PendingLocs[0]; 9978 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9979 PendingLocs.clear(); 9980 PendingArgFlags.clear(); 9981 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9982 ArgFlags); 9983 } 9984 9985 // Allocate to a register if possible, or else a stack slot. 9986 Register Reg; 9987 unsigned StoreSizeBytes = XLen / 8; 9988 Align StackAlign = Align(XLen / 8); 9989 9990 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9991 Reg = State.AllocateReg(ArgFPR16s); 9992 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9993 Reg = State.AllocateReg(ArgFPR32s); 9994 else if (ValVT == MVT::f64 && !UseGPRForF64) 9995 Reg = State.AllocateReg(ArgFPR64s); 9996 else if (ValVT.isVector()) { 9997 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9998 if (!Reg) { 9999 // For return values, the vector must be passed fully via registers or 10000 // via the stack. 10001 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10002 // but we're using all of them. 10003 if (IsRet) 10004 return true; 10005 // Try using a GPR to pass the address 10006 if ((Reg = State.AllocateReg(ArgGPRs))) { 10007 LocVT = XLenVT; 10008 LocInfo = CCValAssign::Indirect; 10009 } else if (ValVT.isScalableVector()) { 10010 LocVT = XLenVT; 10011 LocInfo = CCValAssign::Indirect; 10012 } else { 10013 // Pass fixed-length vectors on the stack. 10014 LocVT = ValVT; 10015 StoreSizeBytes = ValVT.getStoreSize(); 10016 // Align vectors to their element sizes, being careful for vXi1 10017 // vectors. 10018 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10019 } 10020 } 10021 } else { 10022 Reg = State.AllocateReg(ArgGPRs); 10023 } 10024 10025 unsigned StackOffset = 10026 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10027 10028 // If we reach this point and PendingLocs is non-empty, we must be at the 10029 // end of a split argument that must be passed indirectly. 10030 if (!PendingLocs.empty()) { 10031 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10032 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10033 10034 for (auto &It : PendingLocs) { 10035 if (Reg) 10036 It.convertToReg(Reg); 10037 else 10038 It.convertToMem(StackOffset); 10039 State.addLoc(It); 10040 } 10041 PendingLocs.clear(); 10042 PendingArgFlags.clear(); 10043 return false; 10044 } 10045 10046 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10047 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10048 "Expected an XLenVT or vector types at this stage"); 10049 10050 if (Reg) { 10051 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10052 return false; 10053 } 10054 10055 // When a floating-point value is passed on the stack, no bit-conversion is 10056 // needed. 10057 if (ValVT.isFloatingPoint()) { 10058 LocVT = ValVT; 10059 LocInfo = CCValAssign::Full; 10060 } 10061 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10062 return false; 10063 } 10064 10065 template <typename ArgTy> 10066 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10067 for (const auto &ArgIdx : enumerate(Args)) { 10068 MVT ArgVT = ArgIdx.value().VT; 10069 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10070 return ArgIdx.index(); 10071 } 10072 return None; 10073 } 10074 10075 void RISCVTargetLowering::analyzeInputArgs( 10076 MachineFunction &MF, CCState &CCInfo, 10077 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10078 RISCVCCAssignFn Fn) const { 10079 unsigned NumArgs = Ins.size(); 10080 FunctionType *FType = MF.getFunction().getFunctionType(); 10081 10082 Optional<unsigned> FirstMaskArgument; 10083 if (Subtarget.hasVInstructions()) 10084 FirstMaskArgument = preAssignMask(Ins); 10085 10086 for (unsigned i = 0; i != NumArgs; ++i) { 10087 MVT ArgVT = Ins[i].VT; 10088 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10089 10090 Type *ArgTy = nullptr; 10091 if (IsRet) 10092 ArgTy = FType->getReturnType(); 10093 else if (Ins[i].isOrigArg()) 10094 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10095 10096 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10097 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10098 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10099 FirstMaskArgument)) { 10100 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10101 << EVT(ArgVT).getEVTString() << '\n'); 10102 llvm_unreachable(nullptr); 10103 } 10104 } 10105 } 10106 10107 void RISCVTargetLowering::analyzeOutputArgs( 10108 MachineFunction &MF, CCState &CCInfo, 10109 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10110 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10111 unsigned NumArgs = Outs.size(); 10112 10113 Optional<unsigned> FirstMaskArgument; 10114 if (Subtarget.hasVInstructions()) 10115 FirstMaskArgument = preAssignMask(Outs); 10116 10117 for (unsigned i = 0; i != NumArgs; i++) { 10118 MVT ArgVT = Outs[i].VT; 10119 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10120 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10121 10122 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10123 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10124 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10125 FirstMaskArgument)) { 10126 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10127 << EVT(ArgVT).getEVTString() << "\n"); 10128 llvm_unreachable(nullptr); 10129 } 10130 } 10131 } 10132 10133 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10134 // values. 10135 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10136 const CCValAssign &VA, const SDLoc &DL, 10137 const RISCVSubtarget &Subtarget) { 10138 switch (VA.getLocInfo()) { 10139 default: 10140 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10141 case CCValAssign::Full: 10142 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10143 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10144 break; 10145 case CCValAssign::BCvt: 10146 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10147 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10148 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10149 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10150 else 10151 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10152 break; 10153 } 10154 return Val; 10155 } 10156 10157 // The caller is responsible for loading the full value if the argument is 10158 // passed with CCValAssign::Indirect. 10159 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10160 const CCValAssign &VA, const SDLoc &DL, 10161 const RISCVTargetLowering &TLI) { 10162 MachineFunction &MF = DAG.getMachineFunction(); 10163 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10164 EVT LocVT = VA.getLocVT(); 10165 SDValue Val; 10166 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10167 Register VReg = RegInfo.createVirtualRegister(RC); 10168 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10169 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10170 10171 if (VA.getLocInfo() == CCValAssign::Indirect) 10172 return Val; 10173 10174 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10175 } 10176 10177 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10178 const CCValAssign &VA, const SDLoc &DL, 10179 const RISCVSubtarget &Subtarget) { 10180 EVT LocVT = VA.getLocVT(); 10181 10182 switch (VA.getLocInfo()) { 10183 default: 10184 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10185 case CCValAssign::Full: 10186 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10187 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10188 break; 10189 case CCValAssign::BCvt: 10190 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10191 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10192 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10193 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10194 else 10195 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10196 break; 10197 } 10198 return Val; 10199 } 10200 10201 // The caller is responsible for loading the full value if the argument is 10202 // passed with CCValAssign::Indirect. 10203 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10204 const CCValAssign &VA, const SDLoc &DL) { 10205 MachineFunction &MF = DAG.getMachineFunction(); 10206 MachineFrameInfo &MFI = MF.getFrameInfo(); 10207 EVT LocVT = VA.getLocVT(); 10208 EVT ValVT = VA.getValVT(); 10209 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10210 if (ValVT.isScalableVector()) { 10211 // When the value is a scalable vector, we save the pointer which points to 10212 // the scalable vector value in the stack. The ValVT will be the pointer 10213 // type, instead of the scalable vector type. 10214 ValVT = LocVT; 10215 } 10216 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10217 /*IsImmutable=*/true); 10218 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10219 SDValue Val; 10220 10221 ISD::LoadExtType ExtType; 10222 switch (VA.getLocInfo()) { 10223 default: 10224 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10225 case CCValAssign::Full: 10226 case CCValAssign::Indirect: 10227 case CCValAssign::BCvt: 10228 ExtType = ISD::NON_EXTLOAD; 10229 break; 10230 } 10231 Val = DAG.getExtLoad( 10232 ExtType, DL, LocVT, Chain, FIN, 10233 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10234 return Val; 10235 } 10236 10237 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10238 const CCValAssign &VA, const SDLoc &DL) { 10239 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10240 "Unexpected VA"); 10241 MachineFunction &MF = DAG.getMachineFunction(); 10242 MachineFrameInfo &MFI = MF.getFrameInfo(); 10243 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10244 10245 if (VA.isMemLoc()) { 10246 // f64 is passed on the stack. 10247 int FI = 10248 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10249 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10250 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10251 MachinePointerInfo::getFixedStack(MF, FI)); 10252 } 10253 10254 assert(VA.isRegLoc() && "Expected register VA assignment"); 10255 10256 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10257 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10258 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10259 SDValue Hi; 10260 if (VA.getLocReg() == RISCV::X17) { 10261 // Second half of f64 is passed on the stack. 10262 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10263 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10264 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10265 MachinePointerInfo::getFixedStack(MF, FI)); 10266 } else { 10267 // Second half of f64 is passed in another GPR. 10268 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10269 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10270 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10271 } 10272 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10273 } 10274 10275 // FastCC has less than 1% performance improvement for some particular 10276 // benchmark. But theoretically, it may has benenfit for some cases. 10277 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10278 unsigned ValNo, MVT ValVT, MVT LocVT, 10279 CCValAssign::LocInfo LocInfo, 10280 ISD::ArgFlagsTy ArgFlags, CCState &State, 10281 bool IsFixed, bool IsRet, Type *OrigTy, 10282 const RISCVTargetLowering &TLI, 10283 Optional<unsigned> FirstMaskArgument) { 10284 10285 // X5 and X6 might be used for save-restore libcall. 10286 static const MCPhysReg GPRList[] = { 10287 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10288 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10289 RISCV::X29, RISCV::X30, RISCV::X31}; 10290 10291 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10292 if (unsigned Reg = State.AllocateReg(GPRList)) { 10293 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10294 return false; 10295 } 10296 } 10297 10298 if (LocVT == MVT::f16) { 10299 static const MCPhysReg FPR16List[] = { 10300 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10301 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10302 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10303 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10304 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10305 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10306 return false; 10307 } 10308 } 10309 10310 if (LocVT == MVT::f32) { 10311 static const MCPhysReg FPR32List[] = { 10312 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10313 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10314 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10315 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10316 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10317 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10318 return false; 10319 } 10320 } 10321 10322 if (LocVT == MVT::f64) { 10323 static const MCPhysReg FPR64List[] = { 10324 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10325 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10326 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10327 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10328 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10329 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10330 return false; 10331 } 10332 } 10333 10334 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10335 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10336 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10337 return false; 10338 } 10339 10340 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10341 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10342 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10343 return false; 10344 } 10345 10346 if (LocVT.isVector()) { 10347 if (unsigned Reg = 10348 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10349 // Fixed-length vectors are located in the corresponding scalable-vector 10350 // container types. 10351 if (ValVT.isFixedLengthVector()) 10352 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10353 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10354 } else { 10355 // Try and pass the address via a "fast" GPR. 10356 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10357 LocInfo = CCValAssign::Indirect; 10358 LocVT = TLI.getSubtarget().getXLenVT(); 10359 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10360 } else if (ValVT.isFixedLengthVector()) { 10361 auto StackAlign = 10362 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10363 unsigned StackOffset = 10364 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10365 State.addLoc( 10366 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10367 } else { 10368 // Can't pass scalable vectors on the stack. 10369 return true; 10370 } 10371 } 10372 10373 return false; 10374 } 10375 10376 return true; // CC didn't match. 10377 } 10378 10379 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10380 CCValAssign::LocInfo LocInfo, 10381 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10382 10383 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10384 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10385 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10386 static const MCPhysReg GPRList[] = { 10387 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10388 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10389 if (unsigned Reg = State.AllocateReg(GPRList)) { 10390 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10391 return false; 10392 } 10393 } 10394 10395 if (LocVT == MVT::f32) { 10396 // Pass in STG registers: F1, ..., F6 10397 // fs0 ... fs5 10398 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10399 RISCV::F18_F, RISCV::F19_F, 10400 RISCV::F20_F, RISCV::F21_F}; 10401 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10402 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10403 return false; 10404 } 10405 } 10406 10407 if (LocVT == MVT::f64) { 10408 // Pass in STG registers: D1, ..., D6 10409 // fs6 ... fs11 10410 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10411 RISCV::F24_D, RISCV::F25_D, 10412 RISCV::F26_D, RISCV::F27_D}; 10413 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10414 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10415 return false; 10416 } 10417 } 10418 10419 report_fatal_error("No registers left in GHC calling convention"); 10420 return true; 10421 } 10422 10423 // Transform physical registers into virtual registers. 10424 SDValue RISCVTargetLowering::LowerFormalArguments( 10425 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10426 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10427 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10428 10429 MachineFunction &MF = DAG.getMachineFunction(); 10430 10431 switch (CallConv) { 10432 default: 10433 report_fatal_error("Unsupported calling convention"); 10434 case CallingConv::C: 10435 case CallingConv::Fast: 10436 break; 10437 case CallingConv::GHC: 10438 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10439 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10440 report_fatal_error( 10441 "GHC calling convention requires the F and D instruction set extensions"); 10442 } 10443 10444 const Function &Func = MF.getFunction(); 10445 if (Func.hasFnAttribute("interrupt")) { 10446 if (!Func.arg_empty()) 10447 report_fatal_error( 10448 "Functions with the interrupt attribute cannot have arguments!"); 10449 10450 StringRef Kind = 10451 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10452 10453 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10454 report_fatal_error( 10455 "Function interrupt attribute argument not supported!"); 10456 } 10457 10458 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10459 MVT XLenVT = Subtarget.getXLenVT(); 10460 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10461 // Used with vargs to acumulate store chains. 10462 std::vector<SDValue> OutChains; 10463 10464 // Assign locations to all of the incoming arguments. 10465 SmallVector<CCValAssign, 16> ArgLocs; 10466 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10467 10468 if (CallConv == CallingConv::GHC) 10469 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10470 else 10471 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10472 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10473 : CC_RISCV); 10474 10475 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10476 CCValAssign &VA = ArgLocs[i]; 10477 SDValue ArgValue; 10478 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10479 // case. 10480 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10481 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10482 else if (VA.isRegLoc()) 10483 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10484 else 10485 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10486 10487 if (VA.getLocInfo() == CCValAssign::Indirect) { 10488 // If the original argument was split and passed by reference (e.g. i128 10489 // on RV32), we need to load all parts of it here (using the same 10490 // address). Vectors may be partly split to registers and partly to the 10491 // stack, in which case the base address is partly offset and subsequent 10492 // stores are relative to that. 10493 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10494 MachinePointerInfo())); 10495 unsigned ArgIndex = Ins[i].OrigArgIndex; 10496 unsigned ArgPartOffset = Ins[i].PartOffset; 10497 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10498 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10499 CCValAssign &PartVA = ArgLocs[i + 1]; 10500 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10501 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10502 if (PartVA.getValVT().isScalableVector()) 10503 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10504 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10505 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10506 MachinePointerInfo())); 10507 ++i; 10508 } 10509 continue; 10510 } 10511 InVals.push_back(ArgValue); 10512 } 10513 10514 if (IsVarArg) { 10515 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10516 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10517 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10518 MachineFrameInfo &MFI = MF.getFrameInfo(); 10519 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10520 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10521 10522 // Offset of the first variable argument from stack pointer, and size of 10523 // the vararg save area. For now, the varargs save area is either zero or 10524 // large enough to hold a0-a7. 10525 int VaArgOffset, VarArgsSaveSize; 10526 10527 // If all registers are allocated, then all varargs must be passed on the 10528 // stack and we don't need to save any argregs. 10529 if (ArgRegs.size() == Idx) { 10530 VaArgOffset = CCInfo.getNextStackOffset(); 10531 VarArgsSaveSize = 0; 10532 } else { 10533 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10534 VaArgOffset = -VarArgsSaveSize; 10535 } 10536 10537 // Record the frame index of the first variable argument 10538 // which is a value necessary to VASTART. 10539 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10540 RVFI->setVarArgsFrameIndex(FI); 10541 10542 // If saving an odd number of registers then create an extra stack slot to 10543 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10544 // offsets to even-numbered registered remain 2*XLEN-aligned. 10545 if (Idx % 2) { 10546 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10547 VarArgsSaveSize += XLenInBytes; 10548 } 10549 10550 // Copy the integer registers that may have been used for passing varargs 10551 // to the vararg save area. 10552 for (unsigned I = Idx; I < ArgRegs.size(); 10553 ++I, VaArgOffset += XLenInBytes) { 10554 const Register Reg = RegInfo.createVirtualRegister(RC); 10555 RegInfo.addLiveIn(ArgRegs[I], Reg); 10556 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10557 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10558 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10559 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10560 MachinePointerInfo::getFixedStack(MF, FI)); 10561 cast<StoreSDNode>(Store.getNode()) 10562 ->getMemOperand() 10563 ->setValue((Value *)nullptr); 10564 OutChains.push_back(Store); 10565 } 10566 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10567 } 10568 10569 // All stores are grouped in one node to allow the matching between 10570 // the size of Ins and InVals. This only happens for vararg functions. 10571 if (!OutChains.empty()) { 10572 OutChains.push_back(Chain); 10573 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10574 } 10575 10576 return Chain; 10577 } 10578 10579 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10580 /// for tail call optimization. 10581 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10582 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10583 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10584 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10585 10586 auto &Callee = CLI.Callee; 10587 auto CalleeCC = CLI.CallConv; 10588 auto &Outs = CLI.Outs; 10589 auto &Caller = MF.getFunction(); 10590 auto CallerCC = Caller.getCallingConv(); 10591 10592 // Exception-handling functions need a special set of instructions to 10593 // indicate a return to the hardware. Tail-calling another function would 10594 // probably break this. 10595 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10596 // should be expanded as new function attributes are introduced. 10597 if (Caller.hasFnAttribute("interrupt")) 10598 return false; 10599 10600 // Do not tail call opt if the stack is used to pass parameters. 10601 if (CCInfo.getNextStackOffset() != 0) 10602 return false; 10603 10604 // Do not tail call opt if any parameters need to be passed indirectly. 10605 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10606 // passed indirectly. So the address of the value will be passed in a 10607 // register, or if not available, then the address is put on the stack. In 10608 // order to pass indirectly, space on the stack often needs to be allocated 10609 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10610 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10611 // are passed CCValAssign::Indirect. 10612 for (auto &VA : ArgLocs) 10613 if (VA.getLocInfo() == CCValAssign::Indirect) 10614 return false; 10615 10616 // Do not tail call opt if either caller or callee uses struct return 10617 // semantics. 10618 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10619 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10620 if (IsCallerStructRet || IsCalleeStructRet) 10621 return false; 10622 10623 // Externally-defined functions with weak linkage should not be 10624 // tail-called. The behaviour of branch instructions in this situation (as 10625 // used for tail calls) is implementation-defined, so we cannot rely on the 10626 // linker replacing the tail call with a return. 10627 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10628 const GlobalValue *GV = G->getGlobal(); 10629 if (GV->hasExternalWeakLinkage()) 10630 return false; 10631 } 10632 10633 // The callee has to preserve all registers the caller needs to preserve. 10634 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10635 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10636 if (CalleeCC != CallerCC) { 10637 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10638 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10639 return false; 10640 } 10641 10642 // Byval parameters hand the function a pointer directly into the stack area 10643 // we want to reuse during a tail call. Working around this *is* possible 10644 // but less efficient and uglier in LowerCall. 10645 for (auto &Arg : Outs) 10646 if (Arg.Flags.isByVal()) 10647 return false; 10648 10649 return true; 10650 } 10651 10652 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10653 return DAG.getDataLayout().getPrefTypeAlign( 10654 VT.getTypeForEVT(*DAG.getContext())); 10655 } 10656 10657 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10658 // and output parameter nodes. 10659 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10660 SmallVectorImpl<SDValue> &InVals) const { 10661 SelectionDAG &DAG = CLI.DAG; 10662 SDLoc &DL = CLI.DL; 10663 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10664 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10665 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10666 SDValue Chain = CLI.Chain; 10667 SDValue Callee = CLI.Callee; 10668 bool &IsTailCall = CLI.IsTailCall; 10669 CallingConv::ID CallConv = CLI.CallConv; 10670 bool IsVarArg = CLI.IsVarArg; 10671 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10672 MVT XLenVT = Subtarget.getXLenVT(); 10673 10674 MachineFunction &MF = DAG.getMachineFunction(); 10675 10676 // Analyze the operands of the call, assigning locations to each operand. 10677 SmallVector<CCValAssign, 16> ArgLocs; 10678 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10679 10680 if (CallConv == CallingConv::GHC) 10681 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10682 else 10683 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10684 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10685 : CC_RISCV); 10686 10687 // Check if it's really possible to do a tail call. 10688 if (IsTailCall) 10689 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10690 10691 if (IsTailCall) 10692 ++NumTailCalls; 10693 else if (CLI.CB && CLI.CB->isMustTailCall()) 10694 report_fatal_error("failed to perform tail call elimination on a call " 10695 "site marked musttail"); 10696 10697 // Get a count of how many bytes are to be pushed on the stack. 10698 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10699 10700 // Create local copies for byval args 10701 SmallVector<SDValue, 8> ByValArgs; 10702 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10703 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10704 if (!Flags.isByVal()) 10705 continue; 10706 10707 SDValue Arg = OutVals[i]; 10708 unsigned Size = Flags.getByValSize(); 10709 Align Alignment = Flags.getNonZeroByValAlign(); 10710 10711 int FI = 10712 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10713 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10714 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10715 10716 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10717 /*IsVolatile=*/false, 10718 /*AlwaysInline=*/false, IsTailCall, 10719 MachinePointerInfo(), MachinePointerInfo()); 10720 ByValArgs.push_back(FIPtr); 10721 } 10722 10723 if (!IsTailCall) 10724 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10725 10726 // Copy argument values to their designated locations. 10727 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10728 SmallVector<SDValue, 8> MemOpChains; 10729 SDValue StackPtr; 10730 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10731 CCValAssign &VA = ArgLocs[i]; 10732 SDValue ArgValue = OutVals[i]; 10733 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10734 10735 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10736 bool IsF64OnRV32DSoftABI = 10737 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10738 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10739 SDValue SplitF64 = DAG.getNode( 10740 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10741 SDValue Lo = SplitF64.getValue(0); 10742 SDValue Hi = SplitF64.getValue(1); 10743 10744 Register RegLo = VA.getLocReg(); 10745 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10746 10747 if (RegLo == RISCV::X17) { 10748 // Second half of f64 is passed on the stack. 10749 // Work out the address of the stack slot. 10750 if (!StackPtr.getNode()) 10751 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10752 // Emit the store. 10753 MemOpChains.push_back( 10754 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10755 } else { 10756 // Second half of f64 is passed in another GPR. 10757 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10758 Register RegHigh = RegLo + 1; 10759 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10760 } 10761 continue; 10762 } 10763 10764 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10765 // as any other MemLoc. 10766 10767 // Promote the value if needed. 10768 // For now, only handle fully promoted and indirect arguments. 10769 if (VA.getLocInfo() == CCValAssign::Indirect) { 10770 // Store the argument in a stack slot and pass its address. 10771 Align StackAlign = 10772 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10773 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10774 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10775 // If the original argument was split (e.g. i128), we need 10776 // to store the required parts of it here (and pass just one address). 10777 // Vectors may be partly split to registers and partly to the stack, in 10778 // which case the base address is partly offset and subsequent stores are 10779 // relative to that. 10780 unsigned ArgIndex = Outs[i].OrigArgIndex; 10781 unsigned ArgPartOffset = Outs[i].PartOffset; 10782 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10783 // Calculate the total size to store. We don't have access to what we're 10784 // actually storing other than performing the loop and collecting the 10785 // info. 10786 SmallVector<std::pair<SDValue, SDValue>> Parts; 10787 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10788 SDValue PartValue = OutVals[i + 1]; 10789 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10790 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10791 EVT PartVT = PartValue.getValueType(); 10792 if (PartVT.isScalableVector()) 10793 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10794 StoredSize += PartVT.getStoreSize(); 10795 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10796 Parts.push_back(std::make_pair(PartValue, Offset)); 10797 ++i; 10798 } 10799 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10800 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10801 MemOpChains.push_back( 10802 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10803 MachinePointerInfo::getFixedStack(MF, FI))); 10804 for (const auto &Part : Parts) { 10805 SDValue PartValue = Part.first; 10806 SDValue PartOffset = Part.second; 10807 SDValue Address = 10808 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10809 MemOpChains.push_back( 10810 DAG.getStore(Chain, DL, PartValue, Address, 10811 MachinePointerInfo::getFixedStack(MF, FI))); 10812 } 10813 ArgValue = SpillSlot; 10814 } else { 10815 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10816 } 10817 10818 // Use local copy if it is a byval arg. 10819 if (Flags.isByVal()) 10820 ArgValue = ByValArgs[j++]; 10821 10822 if (VA.isRegLoc()) { 10823 // Queue up the argument copies and emit them at the end. 10824 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10825 } else { 10826 assert(VA.isMemLoc() && "Argument not register or memory"); 10827 assert(!IsTailCall && "Tail call not allowed if stack is used " 10828 "for passing parameters"); 10829 10830 // Work out the address of the stack slot. 10831 if (!StackPtr.getNode()) 10832 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10833 SDValue Address = 10834 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10835 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10836 10837 // Emit the store. 10838 MemOpChains.push_back( 10839 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10840 } 10841 } 10842 10843 // Join the stores, which are independent of one another. 10844 if (!MemOpChains.empty()) 10845 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10846 10847 SDValue Glue; 10848 10849 // Build a sequence of copy-to-reg nodes, chained and glued together. 10850 for (auto &Reg : RegsToPass) { 10851 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10852 Glue = Chain.getValue(1); 10853 } 10854 10855 // Validate that none of the argument registers have been marked as 10856 // reserved, if so report an error. Do the same for the return address if this 10857 // is not a tailcall. 10858 validateCCReservedRegs(RegsToPass, MF); 10859 if (!IsTailCall && 10860 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10861 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10862 MF.getFunction(), 10863 "Return address register required, but has been reserved."}); 10864 10865 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10866 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10867 // split it and then direct call can be matched by PseudoCALL. 10868 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10869 const GlobalValue *GV = S->getGlobal(); 10870 10871 unsigned OpFlags = RISCVII::MO_CALL; 10872 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10873 OpFlags = RISCVII::MO_PLT; 10874 10875 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10876 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10877 unsigned OpFlags = RISCVII::MO_CALL; 10878 10879 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10880 nullptr)) 10881 OpFlags = RISCVII::MO_PLT; 10882 10883 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10884 } 10885 10886 // The first call operand is the chain and the second is the target address. 10887 SmallVector<SDValue, 8> Ops; 10888 Ops.push_back(Chain); 10889 Ops.push_back(Callee); 10890 10891 // Add argument registers to the end of the list so that they are 10892 // known live into the call. 10893 for (auto &Reg : RegsToPass) 10894 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10895 10896 if (!IsTailCall) { 10897 // Add a register mask operand representing the call-preserved registers. 10898 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10899 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10900 assert(Mask && "Missing call preserved mask for calling convention"); 10901 Ops.push_back(DAG.getRegisterMask(Mask)); 10902 } 10903 10904 // Glue the call to the argument copies, if any. 10905 if (Glue.getNode()) 10906 Ops.push_back(Glue); 10907 10908 // Emit the call. 10909 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10910 10911 if (IsTailCall) { 10912 MF.getFrameInfo().setHasTailCall(); 10913 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10914 } 10915 10916 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10917 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10918 Glue = Chain.getValue(1); 10919 10920 // Mark the end of the call, which is glued to the call itself. 10921 Chain = DAG.getCALLSEQ_END(Chain, 10922 DAG.getConstant(NumBytes, DL, PtrVT, true), 10923 DAG.getConstant(0, DL, PtrVT, true), 10924 Glue, DL); 10925 Glue = Chain.getValue(1); 10926 10927 // Assign locations to each value returned by this call. 10928 SmallVector<CCValAssign, 16> RVLocs; 10929 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10930 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10931 10932 // Copy all of the result registers out of their specified physreg. 10933 for (auto &VA : RVLocs) { 10934 // Copy the value out 10935 SDValue RetValue = 10936 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10937 // Glue the RetValue to the end of the call sequence 10938 Chain = RetValue.getValue(1); 10939 Glue = RetValue.getValue(2); 10940 10941 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10942 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10943 SDValue RetValue2 = 10944 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10945 Chain = RetValue2.getValue(1); 10946 Glue = RetValue2.getValue(2); 10947 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10948 RetValue2); 10949 } 10950 10951 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10952 10953 InVals.push_back(RetValue); 10954 } 10955 10956 return Chain; 10957 } 10958 10959 bool RISCVTargetLowering::CanLowerReturn( 10960 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10961 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10962 SmallVector<CCValAssign, 16> RVLocs; 10963 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10964 10965 Optional<unsigned> FirstMaskArgument; 10966 if (Subtarget.hasVInstructions()) 10967 FirstMaskArgument = preAssignMask(Outs); 10968 10969 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10970 MVT VT = Outs[i].VT; 10971 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10972 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10973 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10974 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10975 *this, FirstMaskArgument)) 10976 return false; 10977 } 10978 return true; 10979 } 10980 10981 SDValue 10982 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10983 bool IsVarArg, 10984 const SmallVectorImpl<ISD::OutputArg> &Outs, 10985 const SmallVectorImpl<SDValue> &OutVals, 10986 const SDLoc &DL, SelectionDAG &DAG) const { 10987 const MachineFunction &MF = DAG.getMachineFunction(); 10988 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10989 10990 // Stores the assignment of the return value to a location. 10991 SmallVector<CCValAssign, 16> RVLocs; 10992 10993 // Info about the registers and stack slot. 10994 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10995 *DAG.getContext()); 10996 10997 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10998 nullptr, CC_RISCV); 10999 11000 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11001 report_fatal_error("GHC functions return void only"); 11002 11003 SDValue Glue; 11004 SmallVector<SDValue, 4> RetOps(1, Chain); 11005 11006 // Copy the result values into the output registers. 11007 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11008 SDValue Val = OutVals[i]; 11009 CCValAssign &VA = RVLocs[i]; 11010 assert(VA.isRegLoc() && "Can only return in registers!"); 11011 11012 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11013 // Handle returning f64 on RV32D with a soft float ABI. 11014 assert(VA.isRegLoc() && "Expected return via registers"); 11015 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11016 DAG.getVTList(MVT::i32, MVT::i32), Val); 11017 SDValue Lo = SplitF64.getValue(0); 11018 SDValue Hi = SplitF64.getValue(1); 11019 Register RegLo = VA.getLocReg(); 11020 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11021 Register RegHi = RegLo + 1; 11022 11023 if (STI.isRegisterReservedByUser(RegLo) || 11024 STI.isRegisterReservedByUser(RegHi)) 11025 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11026 MF.getFunction(), 11027 "Return value register required, but has been reserved."}); 11028 11029 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11030 Glue = Chain.getValue(1); 11031 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11032 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11033 Glue = Chain.getValue(1); 11034 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11035 } else { 11036 // Handle a 'normal' return. 11037 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11038 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11039 11040 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11041 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11042 MF.getFunction(), 11043 "Return value register required, but has been reserved."}); 11044 11045 // Guarantee that all emitted copies are stuck together. 11046 Glue = Chain.getValue(1); 11047 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11048 } 11049 } 11050 11051 RetOps[0] = Chain; // Update chain. 11052 11053 // Add the glue node if we have it. 11054 if (Glue.getNode()) { 11055 RetOps.push_back(Glue); 11056 } 11057 11058 unsigned RetOpc = RISCVISD::RET_FLAG; 11059 // Interrupt service routines use different return instructions. 11060 const Function &Func = DAG.getMachineFunction().getFunction(); 11061 if (Func.hasFnAttribute("interrupt")) { 11062 if (!Func.getReturnType()->isVoidTy()) 11063 report_fatal_error( 11064 "Functions with the interrupt attribute must have void return type!"); 11065 11066 MachineFunction &MF = DAG.getMachineFunction(); 11067 StringRef Kind = 11068 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11069 11070 if (Kind == "user") 11071 RetOpc = RISCVISD::URET_FLAG; 11072 else if (Kind == "supervisor") 11073 RetOpc = RISCVISD::SRET_FLAG; 11074 else 11075 RetOpc = RISCVISD::MRET_FLAG; 11076 } 11077 11078 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11079 } 11080 11081 void RISCVTargetLowering::validateCCReservedRegs( 11082 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11083 MachineFunction &MF) const { 11084 const Function &F = MF.getFunction(); 11085 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11086 11087 if (llvm::any_of(Regs, [&STI](auto Reg) { 11088 return STI.isRegisterReservedByUser(Reg.first); 11089 })) 11090 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11091 F, "Argument register required, but has been reserved."}); 11092 } 11093 11094 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11095 return CI->isTailCall(); 11096 } 11097 11098 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11099 #define NODE_NAME_CASE(NODE) \ 11100 case RISCVISD::NODE: \ 11101 return "RISCVISD::" #NODE; 11102 // clang-format off 11103 switch ((RISCVISD::NodeType)Opcode) { 11104 case RISCVISD::FIRST_NUMBER: 11105 break; 11106 NODE_NAME_CASE(RET_FLAG) 11107 NODE_NAME_CASE(URET_FLAG) 11108 NODE_NAME_CASE(SRET_FLAG) 11109 NODE_NAME_CASE(MRET_FLAG) 11110 NODE_NAME_CASE(CALL) 11111 NODE_NAME_CASE(SELECT_CC) 11112 NODE_NAME_CASE(BR_CC) 11113 NODE_NAME_CASE(BuildPairF64) 11114 NODE_NAME_CASE(SplitF64) 11115 NODE_NAME_CASE(TAIL) 11116 NODE_NAME_CASE(MULHSU) 11117 NODE_NAME_CASE(SLLW) 11118 NODE_NAME_CASE(SRAW) 11119 NODE_NAME_CASE(SRLW) 11120 NODE_NAME_CASE(DIVW) 11121 NODE_NAME_CASE(DIVUW) 11122 NODE_NAME_CASE(REMUW) 11123 NODE_NAME_CASE(ROLW) 11124 NODE_NAME_CASE(RORW) 11125 NODE_NAME_CASE(CLZW) 11126 NODE_NAME_CASE(CTZW) 11127 NODE_NAME_CASE(FSLW) 11128 NODE_NAME_CASE(FSRW) 11129 NODE_NAME_CASE(FSL) 11130 NODE_NAME_CASE(FSR) 11131 NODE_NAME_CASE(FMV_H_X) 11132 NODE_NAME_CASE(FMV_X_ANYEXTH) 11133 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11134 NODE_NAME_CASE(FMV_W_X_RV64) 11135 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11136 NODE_NAME_CASE(FCVT_X) 11137 NODE_NAME_CASE(FCVT_XU) 11138 NODE_NAME_CASE(FCVT_W_RV64) 11139 NODE_NAME_CASE(FCVT_WU_RV64) 11140 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11141 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11142 NODE_NAME_CASE(READ_CYCLE_WIDE) 11143 NODE_NAME_CASE(GREV) 11144 NODE_NAME_CASE(GREVW) 11145 NODE_NAME_CASE(GORC) 11146 NODE_NAME_CASE(GORCW) 11147 NODE_NAME_CASE(SHFL) 11148 NODE_NAME_CASE(SHFLW) 11149 NODE_NAME_CASE(UNSHFL) 11150 NODE_NAME_CASE(UNSHFLW) 11151 NODE_NAME_CASE(BFP) 11152 NODE_NAME_CASE(BFPW) 11153 NODE_NAME_CASE(BCOMPRESS) 11154 NODE_NAME_CASE(BCOMPRESSW) 11155 NODE_NAME_CASE(BDECOMPRESS) 11156 NODE_NAME_CASE(BDECOMPRESSW) 11157 NODE_NAME_CASE(VMV_V_X_VL) 11158 NODE_NAME_CASE(VFMV_V_F_VL) 11159 NODE_NAME_CASE(VMV_X_S) 11160 NODE_NAME_CASE(VMV_S_X_VL) 11161 NODE_NAME_CASE(VFMV_S_F_VL) 11162 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11163 NODE_NAME_CASE(READ_VLENB) 11164 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11165 NODE_NAME_CASE(VSLIDEUP_VL) 11166 NODE_NAME_CASE(VSLIDE1UP_VL) 11167 NODE_NAME_CASE(VSLIDEDOWN_VL) 11168 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11169 NODE_NAME_CASE(VID_VL) 11170 NODE_NAME_CASE(VFNCVT_ROD_VL) 11171 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11172 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11173 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11174 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11175 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11176 NODE_NAME_CASE(VECREDUCE_AND_VL) 11177 NODE_NAME_CASE(VECREDUCE_OR_VL) 11178 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11179 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11180 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11181 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11182 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11183 NODE_NAME_CASE(ADD_VL) 11184 NODE_NAME_CASE(AND_VL) 11185 NODE_NAME_CASE(MUL_VL) 11186 NODE_NAME_CASE(OR_VL) 11187 NODE_NAME_CASE(SDIV_VL) 11188 NODE_NAME_CASE(SHL_VL) 11189 NODE_NAME_CASE(SREM_VL) 11190 NODE_NAME_CASE(SRA_VL) 11191 NODE_NAME_CASE(SRL_VL) 11192 NODE_NAME_CASE(SUB_VL) 11193 NODE_NAME_CASE(UDIV_VL) 11194 NODE_NAME_CASE(UREM_VL) 11195 NODE_NAME_CASE(XOR_VL) 11196 NODE_NAME_CASE(SADDSAT_VL) 11197 NODE_NAME_CASE(UADDSAT_VL) 11198 NODE_NAME_CASE(SSUBSAT_VL) 11199 NODE_NAME_CASE(USUBSAT_VL) 11200 NODE_NAME_CASE(FADD_VL) 11201 NODE_NAME_CASE(FSUB_VL) 11202 NODE_NAME_CASE(FMUL_VL) 11203 NODE_NAME_CASE(FDIV_VL) 11204 NODE_NAME_CASE(FNEG_VL) 11205 NODE_NAME_CASE(FABS_VL) 11206 NODE_NAME_CASE(FSQRT_VL) 11207 NODE_NAME_CASE(FMA_VL) 11208 NODE_NAME_CASE(FCOPYSIGN_VL) 11209 NODE_NAME_CASE(SMIN_VL) 11210 NODE_NAME_CASE(SMAX_VL) 11211 NODE_NAME_CASE(UMIN_VL) 11212 NODE_NAME_CASE(UMAX_VL) 11213 NODE_NAME_CASE(FMINNUM_VL) 11214 NODE_NAME_CASE(FMAXNUM_VL) 11215 NODE_NAME_CASE(MULHS_VL) 11216 NODE_NAME_CASE(MULHU_VL) 11217 NODE_NAME_CASE(FP_TO_SINT_VL) 11218 NODE_NAME_CASE(FP_TO_UINT_VL) 11219 NODE_NAME_CASE(SINT_TO_FP_VL) 11220 NODE_NAME_CASE(UINT_TO_FP_VL) 11221 NODE_NAME_CASE(FP_EXTEND_VL) 11222 NODE_NAME_CASE(FP_ROUND_VL) 11223 NODE_NAME_CASE(VWMUL_VL) 11224 NODE_NAME_CASE(VWMULU_VL) 11225 NODE_NAME_CASE(VWMULSU_VL) 11226 NODE_NAME_CASE(VWADD_VL) 11227 NODE_NAME_CASE(VWADDU_VL) 11228 NODE_NAME_CASE(VWSUB_VL) 11229 NODE_NAME_CASE(VWSUBU_VL) 11230 NODE_NAME_CASE(VWADD_W_VL) 11231 NODE_NAME_CASE(VWADDU_W_VL) 11232 NODE_NAME_CASE(VWSUB_W_VL) 11233 NODE_NAME_CASE(VWSUBU_W_VL) 11234 NODE_NAME_CASE(SETCC_VL) 11235 NODE_NAME_CASE(VSELECT_VL) 11236 NODE_NAME_CASE(VP_MERGE_VL) 11237 NODE_NAME_CASE(VMAND_VL) 11238 NODE_NAME_CASE(VMOR_VL) 11239 NODE_NAME_CASE(VMXOR_VL) 11240 NODE_NAME_CASE(VMCLR_VL) 11241 NODE_NAME_CASE(VMSET_VL) 11242 NODE_NAME_CASE(VRGATHER_VX_VL) 11243 NODE_NAME_CASE(VRGATHER_VV_VL) 11244 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11245 NODE_NAME_CASE(VSEXT_VL) 11246 NODE_NAME_CASE(VZEXT_VL) 11247 NODE_NAME_CASE(VCPOP_VL) 11248 NODE_NAME_CASE(READ_CSR) 11249 NODE_NAME_CASE(WRITE_CSR) 11250 NODE_NAME_CASE(SWAP_CSR) 11251 } 11252 // clang-format on 11253 return nullptr; 11254 #undef NODE_NAME_CASE 11255 } 11256 11257 /// getConstraintType - Given a constraint letter, return the type of 11258 /// constraint it is for this target. 11259 RISCVTargetLowering::ConstraintType 11260 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11261 if (Constraint.size() == 1) { 11262 switch (Constraint[0]) { 11263 default: 11264 break; 11265 case 'f': 11266 return C_RegisterClass; 11267 case 'I': 11268 case 'J': 11269 case 'K': 11270 return C_Immediate; 11271 case 'A': 11272 return C_Memory; 11273 case 'S': // A symbolic address 11274 return C_Other; 11275 } 11276 } else { 11277 if (Constraint == "vr" || Constraint == "vm") 11278 return C_RegisterClass; 11279 } 11280 return TargetLowering::getConstraintType(Constraint); 11281 } 11282 11283 std::pair<unsigned, const TargetRegisterClass *> 11284 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11285 StringRef Constraint, 11286 MVT VT) const { 11287 // First, see if this is a constraint that directly corresponds to a 11288 // RISCV register class. 11289 if (Constraint.size() == 1) { 11290 switch (Constraint[0]) { 11291 case 'r': 11292 // TODO: Support fixed vectors up to XLen for P extension? 11293 if (VT.isVector()) 11294 break; 11295 return std::make_pair(0U, &RISCV::GPRRegClass); 11296 case 'f': 11297 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11298 return std::make_pair(0U, &RISCV::FPR16RegClass); 11299 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11300 return std::make_pair(0U, &RISCV::FPR32RegClass); 11301 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11302 return std::make_pair(0U, &RISCV::FPR64RegClass); 11303 break; 11304 default: 11305 break; 11306 } 11307 } else if (Constraint == "vr") { 11308 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11309 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11310 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11311 return std::make_pair(0U, RC); 11312 } 11313 } else if (Constraint == "vm") { 11314 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11315 return std::make_pair(0U, &RISCV::VMV0RegClass); 11316 } 11317 11318 // Clang will correctly decode the usage of register name aliases into their 11319 // official names. However, other frontends like `rustc` do not. This allows 11320 // users of these frontends to use the ABI names for registers in LLVM-style 11321 // register constraints. 11322 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11323 .Case("{zero}", RISCV::X0) 11324 .Case("{ra}", RISCV::X1) 11325 .Case("{sp}", RISCV::X2) 11326 .Case("{gp}", RISCV::X3) 11327 .Case("{tp}", RISCV::X4) 11328 .Case("{t0}", RISCV::X5) 11329 .Case("{t1}", RISCV::X6) 11330 .Case("{t2}", RISCV::X7) 11331 .Cases("{s0}", "{fp}", RISCV::X8) 11332 .Case("{s1}", RISCV::X9) 11333 .Case("{a0}", RISCV::X10) 11334 .Case("{a1}", RISCV::X11) 11335 .Case("{a2}", RISCV::X12) 11336 .Case("{a3}", RISCV::X13) 11337 .Case("{a4}", RISCV::X14) 11338 .Case("{a5}", RISCV::X15) 11339 .Case("{a6}", RISCV::X16) 11340 .Case("{a7}", RISCV::X17) 11341 .Case("{s2}", RISCV::X18) 11342 .Case("{s3}", RISCV::X19) 11343 .Case("{s4}", RISCV::X20) 11344 .Case("{s5}", RISCV::X21) 11345 .Case("{s6}", RISCV::X22) 11346 .Case("{s7}", RISCV::X23) 11347 .Case("{s8}", RISCV::X24) 11348 .Case("{s9}", RISCV::X25) 11349 .Case("{s10}", RISCV::X26) 11350 .Case("{s11}", RISCV::X27) 11351 .Case("{t3}", RISCV::X28) 11352 .Case("{t4}", RISCV::X29) 11353 .Case("{t5}", RISCV::X30) 11354 .Case("{t6}", RISCV::X31) 11355 .Default(RISCV::NoRegister); 11356 if (XRegFromAlias != RISCV::NoRegister) 11357 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11358 11359 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11360 // TableGen record rather than the AsmName to choose registers for InlineAsm 11361 // constraints, plus we want to match those names to the widest floating point 11362 // register type available, manually select floating point registers here. 11363 // 11364 // The second case is the ABI name of the register, so that frontends can also 11365 // use the ABI names in register constraint lists. 11366 if (Subtarget.hasStdExtF()) { 11367 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11368 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11369 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11370 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11371 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11372 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11373 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11374 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11375 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11376 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11377 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11378 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11379 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11380 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11381 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11382 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11383 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11384 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11385 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11386 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11387 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11388 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11389 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11390 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11391 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11392 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11393 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11394 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11395 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11396 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11397 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11398 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11399 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11400 .Default(RISCV::NoRegister); 11401 if (FReg != RISCV::NoRegister) { 11402 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11403 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11404 unsigned RegNo = FReg - RISCV::F0_F; 11405 unsigned DReg = RISCV::F0_D + RegNo; 11406 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11407 } 11408 if (VT == MVT::f32 || VT == MVT::Other) 11409 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11410 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11411 unsigned RegNo = FReg - RISCV::F0_F; 11412 unsigned HReg = RISCV::F0_H + RegNo; 11413 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11414 } 11415 } 11416 } 11417 11418 if (Subtarget.hasVInstructions()) { 11419 Register VReg = StringSwitch<Register>(Constraint.lower()) 11420 .Case("{v0}", RISCV::V0) 11421 .Case("{v1}", RISCV::V1) 11422 .Case("{v2}", RISCV::V2) 11423 .Case("{v3}", RISCV::V3) 11424 .Case("{v4}", RISCV::V4) 11425 .Case("{v5}", RISCV::V5) 11426 .Case("{v6}", RISCV::V6) 11427 .Case("{v7}", RISCV::V7) 11428 .Case("{v8}", RISCV::V8) 11429 .Case("{v9}", RISCV::V9) 11430 .Case("{v10}", RISCV::V10) 11431 .Case("{v11}", RISCV::V11) 11432 .Case("{v12}", RISCV::V12) 11433 .Case("{v13}", RISCV::V13) 11434 .Case("{v14}", RISCV::V14) 11435 .Case("{v15}", RISCV::V15) 11436 .Case("{v16}", RISCV::V16) 11437 .Case("{v17}", RISCV::V17) 11438 .Case("{v18}", RISCV::V18) 11439 .Case("{v19}", RISCV::V19) 11440 .Case("{v20}", RISCV::V20) 11441 .Case("{v21}", RISCV::V21) 11442 .Case("{v22}", RISCV::V22) 11443 .Case("{v23}", RISCV::V23) 11444 .Case("{v24}", RISCV::V24) 11445 .Case("{v25}", RISCV::V25) 11446 .Case("{v26}", RISCV::V26) 11447 .Case("{v27}", RISCV::V27) 11448 .Case("{v28}", RISCV::V28) 11449 .Case("{v29}", RISCV::V29) 11450 .Case("{v30}", RISCV::V30) 11451 .Case("{v31}", RISCV::V31) 11452 .Default(RISCV::NoRegister); 11453 if (VReg != RISCV::NoRegister) { 11454 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11455 return std::make_pair(VReg, &RISCV::VMRegClass); 11456 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11457 return std::make_pair(VReg, &RISCV::VRRegClass); 11458 for (const auto *RC : 11459 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11460 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11461 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11462 return std::make_pair(VReg, RC); 11463 } 11464 } 11465 } 11466 } 11467 11468 std::pair<Register, const TargetRegisterClass *> Res = 11469 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11470 11471 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11472 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11473 // Subtarget into account. 11474 if (Res.second == &RISCV::GPRF16RegClass || 11475 Res.second == &RISCV::GPRF32RegClass || 11476 Res.second == &RISCV::GPRF64RegClass) 11477 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11478 11479 return Res; 11480 } 11481 11482 unsigned 11483 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11484 // Currently only support length 1 constraints. 11485 if (ConstraintCode.size() == 1) { 11486 switch (ConstraintCode[0]) { 11487 case 'A': 11488 return InlineAsm::Constraint_A; 11489 default: 11490 break; 11491 } 11492 } 11493 11494 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11495 } 11496 11497 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11498 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11499 SelectionDAG &DAG) const { 11500 // Currently only support length 1 constraints. 11501 if (Constraint.length() == 1) { 11502 switch (Constraint[0]) { 11503 case 'I': 11504 // Validate & create a 12-bit signed immediate operand. 11505 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11506 uint64_t CVal = C->getSExtValue(); 11507 if (isInt<12>(CVal)) 11508 Ops.push_back( 11509 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11510 } 11511 return; 11512 case 'J': 11513 // Validate & create an integer zero operand. 11514 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11515 if (C->getZExtValue() == 0) 11516 Ops.push_back( 11517 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11518 return; 11519 case 'K': 11520 // Validate & create a 5-bit unsigned immediate operand. 11521 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11522 uint64_t CVal = C->getZExtValue(); 11523 if (isUInt<5>(CVal)) 11524 Ops.push_back( 11525 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11526 } 11527 return; 11528 case 'S': 11529 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11530 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11531 GA->getValueType(0))); 11532 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11533 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11534 BA->getValueType(0))); 11535 } 11536 return; 11537 default: 11538 break; 11539 } 11540 } 11541 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11542 } 11543 11544 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11545 Instruction *Inst, 11546 AtomicOrdering Ord) const { 11547 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11548 return Builder.CreateFence(Ord); 11549 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11550 return Builder.CreateFence(AtomicOrdering::Release); 11551 return nullptr; 11552 } 11553 11554 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11555 Instruction *Inst, 11556 AtomicOrdering Ord) const { 11557 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11558 return Builder.CreateFence(AtomicOrdering::Acquire); 11559 return nullptr; 11560 } 11561 11562 TargetLowering::AtomicExpansionKind 11563 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11564 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11565 // point operations can't be used in an lr/sc sequence without breaking the 11566 // forward-progress guarantee. 11567 if (AI->isFloatingPointOperation()) 11568 return AtomicExpansionKind::CmpXChg; 11569 11570 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11571 if (Size == 8 || Size == 16) 11572 return AtomicExpansionKind::MaskedIntrinsic; 11573 return AtomicExpansionKind::None; 11574 } 11575 11576 static Intrinsic::ID 11577 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11578 if (XLen == 32) { 11579 switch (BinOp) { 11580 default: 11581 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11582 case AtomicRMWInst::Xchg: 11583 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11584 case AtomicRMWInst::Add: 11585 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11586 case AtomicRMWInst::Sub: 11587 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11588 case AtomicRMWInst::Nand: 11589 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11590 case AtomicRMWInst::Max: 11591 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11592 case AtomicRMWInst::Min: 11593 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11594 case AtomicRMWInst::UMax: 11595 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11596 case AtomicRMWInst::UMin: 11597 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11598 } 11599 } 11600 11601 if (XLen == 64) { 11602 switch (BinOp) { 11603 default: 11604 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11605 case AtomicRMWInst::Xchg: 11606 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11607 case AtomicRMWInst::Add: 11608 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11609 case AtomicRMWInst::Sub: 11610 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11611 case AtomicRMWInst::Nand: 11612 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11613 case AtomicRMWInst::Max: 11614 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11615 case AtomicRMWInst::Min: 11616 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11617 case AtomicRMWInst::UMax: 11618 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11619 case AtomicRMWInst::UMin: 11620 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11621 } 11622 } 11623 11624 llvm_unreachable("Unexpected XLen\n"); 11625 } 11626 11627 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11628 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11629 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11630 unsigned XLen = Subtarget.getXLen(); 11631 Value *Ordering = 11632 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11633 Type *Tys[] = {AlignedAddr->getType()}; 11634 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11635 AI->getModule(), 11636 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11637 11638 if (XLen == 64) { 11639 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11640 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11641 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11642 } 11643 11644 Value *Result; 11645 11646 // Must pass the shift amount needed to sign extend the loaded value prior 11647 // to performing a signed comparison for min/max. ShiftAmt is the number of 11648 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11649 // is the number of bits to left+right shift the value in order to 11650 // sign-extend. 11651 if (AI->getOperation() == AtomicRMWInst::Min || 11652 AI->getOperation() == AtomicRMWInst::Max) { 11653 const DataLayout &DL = AI->getModule()->getDataLayout(); 11654 unsigned ValWidth = 11655 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11656 Value *SextShamt = 11657 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11658 Result = Builder.CreateCall(LrwOpScwLoop, 11659 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11660 } else { 11661 Result = 11662 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11663 } 11664 11665 if (XLen == 64) 11666 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11667 return Result; 11668 } 11669 11670 TargetLowering::AtomicExpansionKind 11671 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11672 AtomicCmpXchgInst *CI) const { 11673 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11674 if (Size == 8 || Size == 16) 11675 return AtomicExpansionKind::MaskedIntrinsic; 11676 return AtomicExpansionKind::None; 11677 } 11678 11679 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11680 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11681 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11682 unsigned XLen = Subtarget.getXLen(); 11683 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11684 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11685 if (XLen == 64) { 11686 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11687 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11688 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11689 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11690 } 11691 Type *Tys[] = {AlignedAddr->getType()}; 11692 Function *MaskedCmpXchg = 11693 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11694 Value *Result = Builder.CreateCall( 11695 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11696 if (XLen == 64) 11697 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11698 return Result; 11699 } 11700 11701 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11702 EVT DataVT) const { 11703 return false; 11704 } 11705 11706 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11707 EVT VT) const { 11708 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11709 return false; 11710 11711 switch (FPVT.getSimpleVT().SimpleTy) { 11712 case MVT::f16: 11713 return Subtarget.hasStdExtZfh(); 11714 case MVT::f32: 11715 return Subtarget.hasStdExtF(); 11716 case MVT::f64: 11717 return Subtarget.hasStdExtD(); 11718 default: 11719 return false; 11720 } 11721 } 11722 11723 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11724 // If we are using the small code model, we can reduce size of jump table 11725 // entry to 4 bytes. 11726 if (Subtarget.is64Bit() && !isPositionIndependent() && 11727 getTargetMachine().getCodeModel() == CodeModel::Small) { 11728 return MachineJumpTableInfo::EK_Custom32; 11729 } 11730 return TargetLowering::getJumpTableEncoding(); 11731 } 11732 11733 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11734 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11735 unsigned uid, MCContext &Ctx) const { 11736 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11737 getTargetMachine().getCodeModel() == CodeModel::Small); 11738 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11739 } 11740 11741 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11742 EVT VT) const { 11743 VT = VT.getScalarType(); 11744 11745 if (!VT.isSimple()) 11746 return false; 11747 11748 switch (VT.getSimpleVT().SimpleTy) { 11749 case MVT::f16: 11750 return Subtarget.hasStdExtZfh(); 11751 case MVT::f32: 11752 return Subtarget.hasStdExtF(); 11753 case MVT::f64: 11754 return Subtarget.hasStdExtD(); 11755 default: 11756 break; 11757 } 11758 11759 return false; 11760 } 11761 11762 Register RISCVTargetLowering::getExceptionPointerRegister( 11763 const Constant *PersonalityFn) const { 11764 return RISCV::X10; 11765 } 11766 11767 Register RISCVTargetLowering::getExceptionSelectorRegister( 11768 const Constant *PersonalityFn) const { 11769 return RISCV::X11; 11770 } 11771 11772 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11773 // Return false to suppress the unnecessary extensions if the LibCall 11774 // arguments or return value is f32 type for LP64 ABI. 11775 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11776 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11777 return false; 11778 11779 return true; 11780 } 11781 11782 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11783 if (Subtarget.is64Bit() && Type == MVT::i32) 11784 return true; 11785 11786 return IsSigned; 11787 } 11788 11789 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11790 SDValue C) const { 11791 // Check integral scalar types. 11792 if (VT.isScalarInteger()) { 11793 // Omit the optimization if the sub target has the M extension and the data 11794 // size exceeds XLen. 11795 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11796 return false; 11797 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11798 // Break the MUL to a SLLI and an ADD/SUB. 11799 const APInt &Imm = ConstNode->getAPIntValue(); 11800 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11801 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11802 return true; 11803 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11804 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11805 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11806 (Imm - 8).isPowerOf2())) 11807 return true; 11808 // Omit the following optimization if the sub target has the M extension 11809 // and the data size >= XLen. 11810 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11811 return false; 11812 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11813 // a pair of LUI/ADDI. 11814 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11815 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11816 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11817 (1 - ImmS).isPowerOf2()) 11818 return true; 11819 } 11820 } 11821 } 11822 11823 return false; 11824 } 11825 11826 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11827 SDValue ConstNode) const { 11828 // Let the DAGCombiner decide for vectors. 11829 EVT VT = AddNode.getValueType(); 11830 if (VT.isVector()) 11831 return true; 11832 11833 // Let the DAGCombiner decide for larger types. 11834 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11835 return true; 11836 11837 // It is worse if c1 is simm12 while c1*c2 is not. 11838 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11839 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11840 const APInt &C1 = C1Node->getAPIntValue(); 11841 const APInt &C2 = C2Node->getAPIntValue(); 11842 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11843 return false; 11844 11845 // Default to true and let the DAGCombiner decide. 11846 return true; 11847 } 11848 11849 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11850 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11851 bool *Fast) const { 11852 if (!VT.isVector()) { 11853 if (Fast) 11854 *Fast = false; 11855 return Subtarget.enableUnalignedScalarMem(); 11856 } 11857 11858 // All vector implementations must support element alignment 11859 EVT ElemVT = VT.getVectorElementType(); 11860 if (Alignment >= ElemVT.getStoreSize()) { 11861 if (Fast) 11862 *Fast = true; 11863 return true; 11864 } 11865 11866 return false; 11867 } 11868 11869 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11870 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11871 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11872 bool IsABIRegCopy = CC.hasValue(); 11873 EVT ValueVT = Val.getValueType(); 11874 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11875 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11876 // and cast to f32. 11877 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11878 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11879 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11880 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11881 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11882 Parts[0] = Val; 11883 return true; 11884 } 11885 11886 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11887 LLVMContext &Context = *DAG.getContext(); 11888 EVT ValueEltVT = ValueVT.getVectorElementType(); 11889 EVT PartEltVT = PartVT.getVectorElementType(); 11890 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11891 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11892 if (PartVTBitSize % ValueVTBitSize == 0) { 11893 assert(PartVTBitSize >= ValueVTBitSize); 11894 // If the element types are different, bitcast to the same element type of 11895 // PartVT first. 11896 // Give an example here, we want copy a <vscale x 1 x i8> value to 11897 // <vscale x 4 x i16>. 11898 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11899 // subvector, then we can bitcast to <vscale x 4 x i16>. 11900 if (ValueEltVT != PartEltVT) { 11901 if (PartVTBitSize > ValueVTBitSize) { 11902 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11903 assert(Count != 0 && "The number of element should not be zero."); 11904 EVT SameEltTypeVT = 11905 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11906 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11907 DAG.getUNDEF(SameEltTypeVT), Val, 11908 DAG.getVectorIdxConstant(0, DL)); 11909 } 11910 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11911 } else { 11912 Val = 11913 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11914 Val, DAG.getVectorIdxConstant(0, DL)); 11915 } 11916 Parts[0] = Val; 11917 return true; 11918 } 11919 } 11920 return false; 11921 } 11922 11923 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11924 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11925 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11926 bool IsABIRegCopy = CC.hasValue(); 11927 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11928 SDValue Val = Parts[0]; 11929 11930 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11931 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11932 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11933 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11934 return Val; 11935 } 11936 11937 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11938 LLVMContext &Context = *DAG.getContext(); 11939 SDValue Val = Parts[0]; 11940 EVT ValueEltVT = ValueVT.getVectorElementType(); 11941 EVT PartEltVT = PartVT.getVectorElementType(); 11942 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11943 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11944 if (PartVTBitSize % ValueVTBitSize == 0) { 11945 assert(PartVTBitSize >= ValueVTBitSize); 11946 EVT SameEltTypeVT = ValueVT; 11947 // If the element types are different, convert it to the same element type 11948 // of PartVT. 11949 // Give an example here, we want copy a <vscale x 1 x i8> value from 11950 // <vscale x 4 x i16>. 11951 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11952 // then we can extract <vscale x 1 x i8>. 11953 if (ValueEltVT != PartEltVT) { 11954 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11955 assert(Count != 0 && "The number of element should not be zero."); 11956 SameEltTypeVT = 11957 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11958 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11959 } 11960 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11961 DAG.getVectorIdxConstant(0, DL)); 11962 return Val; 11963 } 11964 } 11965 return SDValue(); 11966 } 11967 11968 SDValue 11969 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11970 SelectionDAG &DAG, 11971 SmallVectorImpl<SDNode *> &Created) const { 11972 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11973 if (isIntDivCheap(N->getValueType(0), Attr)) 11974 return SDValue(N, 0); // Lower SDIV as SDIV 11975 11976 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11977 "Unexpected divisor!"); 11978 11979 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11980 if (!Subtarget.hasStdExtZbt()) 11981 return SDValue(); 11982 11983 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11984 // Besides, more critical path instructions will be generated when dividing 11985 // by 2. So we keep using the original DAGs for these cases. 11986 unsigned Lg2 = Divisor.countTrailingZeros(); 11987 if (Lg2 == 1 || Lg2 >= 12) 11988 return SDValue(); 11989 11990 // fold (sdiv X, pow2) 11991 EVT VT = N->getValueType(0); 11992 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11993 return SDValue(); 11994 11995 SDLoc DL(N); 11996 SDValue N0 = N->getOperand(0); 11997 SDValue Zero = DAG.getConstant(0, DL, VT); 11998 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11999 12000 // Add (N0 < 0) ? Pow2 - 1 : 0; 12001 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12002 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12003 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12004 12005 Created.push_back(Cmp.getNode()); 12006 Created.push_back(Add.getNode()); 12007 Created.push_back(Sel.getNode()); 12008 12009 // Divide by pow2. 12010 SDValue SRA = 12011 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12012 12013 // If we're dividing by a positive value, we're done. Otherwise, we must 12014 // negate the result. 12015 if (Divisor.isNonNegative()) 12016 return SRA; 12017 12018 Created.push_back(SRA.getNode()); 12019 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12020 } 12021 12022 #define GET_REGISTER_MATCHER 12023 #include "RISCVGenAsmMatcher.inc" 12024 12025 Register 12026 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12027 const MachineFunction &MF) const { 12028 Register Reg = MatchRegisterAltName(RegName); 12029 if (Reg == RISCV::NoRegister) 12030 Reg = MatchRegisterName(RegName); 12031 if (Reg == RISCV::NoRegister) 12032 report_fatal_error( 12033 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12034 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12035 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12036 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12037 StringRef(RegName) + "\".")); 12038 return Reg; 12039 } 12040 12041 namespace llvm { 12042 namespace RISCVVIntrinsicsTable { 12043 12044 #define GET_RISCVVIntrinsicsTable_IMPL 12045 #include "RISCVGenSearchableTables.inc" 12046 12047 } // namespace RISCVVIntrinsicsTable 12048 12049 } // namespace llvm 12050