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 if (!Subtarget.hasStdExtZbb()) 191 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 192 193 if (Subtarget.is64Bit()) { 194 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 195 MVT::i32, Custom); 196 197 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 198 MVT::i32, Custom); 199 } else { 200 setLibcallName( 201 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 202 nullptr); 203 setLibcallName(RTLIB::MULO_I64, nullptr); 204 } 205 206 if (!Subtarget.hasStdExtM()) { 207 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 208 ISD::SREM, ISD::UREM}, 209 XLenVT, Expand); 210 } else { 211 if (Subtarget.is64Bit()) { 212 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 213 214 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 215 {MVT::i8, MVT::i16, MVT::i32}, Custom); 216 } else { 217 setOperationAction(ISD::MUL, MVT::i64, Custom); 218 } 219 } 220 221 setOperationAction( 222 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 223 Expand); 224 225 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 226 Custom); 227 228 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 229 Subtarget.hasStdExtZbkb()) { 230 if (Subtarget.is64Bit()) 231 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 232 } else { 233 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 234 } 235 236 if (Subtarget.hasStdExtZbp()) { 237 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 238 // more combining. 239 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 240 241 // BSWAP i8 doesn't exist. 242 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 243 244 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 245 246 if (Subtarget.is64Bit()) 247 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 248 } else { 249 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 250 // pattern match it directly in isel. 251 setOperationAction(ISD::BSWAP, XLenVT, 252 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 253 ? Legal 254 : Expand); 255 // Zbkb can use rev8+brev8 to implement bitreverse. 256 setOperationAction(ISD::BITREVERSE, XLenVT, 257 Subtarget.hasStdExtZbkb() ? Custom : Expand); 258 } 259 260 if (Subtarget.hasStdExtZbb()) { 261 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 262 Legal); 263 264 if (Subtarget.is64Bit()) 265 setOperationAction( 266 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 267 MVT::i32, Custom); 268 } else { 269 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 270 271 if (Subtarget.is64Bit()) 272 setOperationAction(ISD::ABS, MVT::i32, Custom); 273 } 274 275 if (Subtarget.hasStdExtZbt()) { 276 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 277 setOperationAction(ISD::SELECT, XLenVT, Legal); 278 279 if (Subtarget.is64Bit()) 280 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 281 } else { 282 setOperationAction(ISD::SELECT, XLenVT, Custom); 283 } 284 285 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 286 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 287 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 288 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 289 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 290 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 291 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 292 293 static const ISD::CondCode FPCCToExpand[] = { 294 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 295 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 296 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 297 298 static const ISD::NodeType FPOpToExpand[] = { 299 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 300 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 301 302 if (Subtarget.hasStdExtZfh()) 303 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 304 305 if (Subtarget.hasStdExtZfh()) { 306 for (auto NT : FPLegalNodeTypes) 307 setOperationAction(NT, MVT::f16, Legal); 308 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 309 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 310 for (auto CC : FPCCToExpand) 311 setCondCodeAction(CC, MVT::f16, Expand); 312 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 313 setOperationAction(ISD::SELECT, MVT::f16, Custom); 314 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 315 316 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 317 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 318 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 319 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 320 ISD::FLOG2, ISD::FLOG10}, 321 MVT::f16, Promote); 322 323 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 324 // complete support for all operations in LegalizeDAG. 325 326 // We need to custom promote this. 327 if (Subtarget.is64Bit()) 328 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 329 } 330 331 if (Subtarget.hasStdExtF()) { 332 for (auto NT : FPLegalNodeTypes) 333 setOperationAction(NT, MVT::f32, Legal); 334 for (auto CC : FPCCToExpand) 335 setCondCodeAction(CC, MVT::f32, Expand); 336 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 337 setOperationAction(ISD::SELECT, MVT::f32, Custom); 338 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 339 for (auto Op : FPOpToExpand) 340 setOperationAction(Op, MVT::f32, Expand); 341 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 342 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 343 } 344 345 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 346 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 347 348 if (Subtarget.hasStdExtD()) { 349 for (auto NT : FPLegalNodeTypes) 350 setOperationAction(NT, MVT::f64, Legal); 351 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 352 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 353 for (auto CC : FPCCToExpand) 354 setCondCodeAction(CC, MVT::f64, Expand); 355 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 356 setOperationAction(ISD::SELECT, MVT::f64, Custom); 357 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 358 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 359 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 360 for (auto Op : FPOpToExpand) 361 setOperationAction(Op, MVT::f64, Expand); 362 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 363 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 364 } 365 366 if (Subtarget.is64Bit()) 367 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 368 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 369 MVT::i32, Custom); 370 371 if (Subtarget.hasStdExtF()) { 372 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 373 Custom); 374 375 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 376 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 377 XLenVT, Legal); 378 379 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 380 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 381 } 382 383 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 384 ISD::JumpTable}, 385 XLenVT, Custom); 386 387 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 388 389 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 390 // Unfortunately this can't be determined just from the ISA naming string. 391 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 392 Subtarget.is64Bit() ? Legal : Custom); 393 394 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 395 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 396 if (Subtarget.is64Bit()) 397 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtA()) { 400 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 401 setMinCmpXchgSizeInBits(32); 402 } else { 403 setMaxAtomicSizeInBitsSupported(0); 404 } 405 406 setBooleanContents(ZeroOrOneBooleanContent); 407 408 if (Subtarget.hasVInstructions()) { 409 setBooleanVectorContents(ZeroOrOneBooleanContent); 410 411 setOperationAction(ISD::VSCALE, XLenVT, Custom); 412 413 // RVV intrinsics may have illegal operands. 414 // We also need to custom legalize vmv.x.s. 415 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 416 {MVT::i8, MVT::i16}, Custom); 417 if (Subtarget.is64Bit()) 418 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 419 else 420 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 421 MVT::i64, Custom); 422 423 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 424 MVT::Other, Custom); 425 426 static const unsigned IntegerVPOps[] = { 427 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 428 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 429 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 430 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 431 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 432 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 433 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 434 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 435 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SEXT, 436 ISD::VP_ZEXT, ISD::VP_TRUNC}; 437 438 static const unsigned FloatingPointVPOps[] = { 439 ISD::VP_FADD, ISD::VP_FSUB, 440 ISD::VP_FMUL, ISD::VP_FDIV, 441 ISD::VP_FNEG, ISD::VP_FMA, 442 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 443 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 444 ISD::VP_MERGE, ISD::VP_SELECT, 445 ISD::VP_SITOFP, ISD::VP_UITOFP, 446 ISD::VP_SETCC, ISD::VP_FP_ROUND}; 447 448 if (!Subtarget.is64Bit()) { 449 // We must custom-lower certain vXi64 operations on RV32 due to the vector 450 // element type being illegal. 451 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 452 MVT::i64, Custom); 453 454 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 455 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 456 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 457 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 458 MVT::i64, Custom); 459 460 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 461 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 462 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 463 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 464 MVT::i64, Custom); 465 } 466 467 for (MVT VT : BoolVecVTs) { 468 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 469 470 // Mask VTs are custom-expanded into a series of standard nodes 471 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 472 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 473 VT, Custom); 474 475 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 476 Custom); 477 478 setOperationAction(ISD::SELECT, VT, Custom); 479 setOperationAction( 480 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 481 Expand); 482 483 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 484 485 setOperationAction( 486 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 487 Custom); 488 489 setOperationAction( 490 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 491 Custom); 492 493 // RVV has native int->float & float->int conversions where the 494 // element type sizes are within one power-of-two of each other. Any 495 // wider distances between type sizes have to be lowered as sequences 496 // which progressively narrow the gap in stages. 497 setOperationAction( 498 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 499 VT, Custom); 500 501 // Expand all extending loads to types larger than this, and truncating 502 // stores from types larger than this. 503 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 504 setTruncStoreAction(OtherVT, VT, Expand); 505 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 506 VT, Expand); 507 } 508 509 setOperationAction( 510 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNC, ISD::VP_SETCC}, VT, 511 Custom); 512 } 513 514 for (MVT VT : IntVecVTs) { 515 if (VT.getVectorElementType() == MVT::i64 && 516 !Subtarget.hasVInstructionsI64()) 517 continue; 518 519 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 520 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 521 522 // Vectors implement MULHS/MULHU. 523 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 524 525 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 526 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 527 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 528 529 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 530 Legal); 531 532 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 533 534 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 535 Expand); 536 537 setOperationAction(ISD::BSWAP, VT, Expand); 538 539 // Custom-lower extensions and truncations from/to mask types. 540 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 541 VT, Custom); 542 543 // RVV has native int->float & float->int conversions where the 544 // element type sizes are within one power-of-two of each other. Any 545 // wider distances between type sizes have to be lowered as sequences 546 // which progressively narrow the gap in stages. 547 setOperationAction( 548 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 549 VT, Custom); 550 551 setOperationAction( 552 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 553 554 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 555 // nodes which truncate by one power of two at a time. 556 setOperationAction(ISD::TRUNCATE, VT, Custom); 557 558 // Custom-lower insert/extract operations to simplify patterns. 559 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 560 Custom); 561 562 // Custom-lower reduction operations to set up the corresponding custom 563 // nodes' operands. 564 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 565 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 566 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 567 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 568 VT, Custom); 569 570 for (unsigned VPOpc : IntegerVPOps) 571 setOperationAction(VPOpc, VT, Custom); 572 573 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 574 575 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 576 VT, Custom); 577 578 setOperationAction( 579 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 580 Custom); 581 582 setOperationAction( 583 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 584 VT, Custom); 585 586 setOperationAction(ISD::SELECT, VT, Custom); 587 setOperationAction(ISD::SELECT_CC, VT, Expand); 588 589 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 590 591 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 592 setTruncStoreAction(VT, OtherVT, Expand); 593 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 594 VT, Expand); 595 } 596 597 // Splice 598 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 599 600 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 601 // type that can represent the value exactly. 602 if (VT.getVectorElementType() != MVT::i64) { 603 MVT FloatEltVT = 604 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 605 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 606 if (isTypeLegal(FloatVT)) { 607 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 608 Custom); 609 } 610 } 611 } 612 613 // Expand various CCs to best match the RVV ISA, which natively supports UNE 614 // but no other unordered comparisons, and supports all ordered comparisons 615 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 616 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 617 // and we pattern-match those back to the "original", swapping operands once 618 // more. This way we catch both operations and both "vf" and "fv" forms with 619 // fewer patterns. 620 static const ISD::CondCode VFPCCToExpand[] = { 621 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 622 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 623 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 624 }; 625 626 // Sets common operation actions on RVV floating-point vector types. 627 const auto SetCommonVFPActions = [&](MVT VT) { 628 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 629 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 630 // sizes are within one power-of-two of each other. Therefore conversions 631 // between vXf16 and vXf64 must be lowered as sequences which convert via 632 // vXf32. 633 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 634 // Custom-lower insert/extract operations to simplify patterns. 635 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 636 Custom); 637 // Expand various condition codes (explained above). 638 for (auto CC : VFPCCToExpand) 639 setCondCodeAction(CC, VT, Expand); 640 641 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 642 643 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 644 VT, Custom); 645 646 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 647 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 648 VT, Custom); 649 650 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 651 652 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 653 654 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 655 VT, Custom); 656 657 setOperationAction( 658 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 659 Custom); 660 661 setOperationAction(ISD::SELECT, VT, Custom); 662 setOperationAction(ISD::SELECT_CC, VT, Expand); 663 664 setOperationAction( 665 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 666 VT, Custom); 667 668 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 669 670 for (unsigned VPOpc : FloatingPointVPOps) 671 setOperationAction(VPOpc, VT, Custom); 672 }; 673 674 // Sets common extload/truncstore actions on RVV floating-point vector 675 // types. 676 const auto SetCommonVFPExtLoadTruncStoreActions = 677 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 678 for (auto SmallVT : SmallerVTs) { 679 setTruncStoreAction(VT, SmallVT, Expand); 680 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 681 } 682 }; 683 684 if (Subtarget.hasVInstructionsF16()) 685 for (MVT VT : F16VecVTs) 686 SetCommonVFPActions(VT); 687 688 for (MVT VT : F32VecVTs) { 689 if (Subtarget.hasVInstructionsF32()) 690 SetCommonVFPActions(VT); 691 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 692 } 693 694 for (MVT VT : F64VecVTs) { 695 if (Subtarget.hasVInstructionsF64()) 696 SetCommonVFPActions(VT); 697 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 698 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 699 } 700 701 if (Subtarget.useRVVForFixedLengthVectors()) { 702 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 703 if (!useRVVForFixedLengthVectorVT(VT)) 704 continue; 705 706 // By default everything must be expanded. 707 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 708 setOperationAction(Op, VT, Expand); 709 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 710 setTruncStoreAction(VT, OtherVT, Expand); 711 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 712 OtherVT, VT, Expand); 713 } 714 715 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 716 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 717 Custom); 718 719 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 720 Custom); 721 722 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 723 VT, Custom); 724 725 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 726 727 setOperationAction(ISD::SETCC, VT, Custom); 728 729 setOperationAction(ISD::SELECT, VT, Custom); 730 731 setOperationAction(ISD::TRUNCATE, VT, Custom); 732 733 setOperationAction(ISD::BITCAST, VT, Custom); 734 735 setOperationAction( 736 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 737 Custom); 738 739 setOperationAction( 740 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 741 Custom); 742 743 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 744 ISD::FP_TO_UINT}, 745 VT, Custom); 746 747 // Operations below are different for between masks and other vectors. 748 if (VT.getVectorElementType() == MVT::i1) { 749 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 750 ISD::OR, ISD::XOR}, 751 VT, Custom); 752 753 setOperationAction( 754 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNC}, 755 VT, Custom); 756 continue; 757 } 758 759 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 760 // it before type legalization for i64 vectors on RV32. It will then be 761 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 762 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 763 // improvements first. 764 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 765 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 766 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 767 } 768 769 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 770 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 771 772 setOperationAction( 773 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 774 775 setOperationAction( 776 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 777 Custom); 778 779 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 780 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 781 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 782 VT, Custom); 783 784 setOperationAction( 785 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 786 787 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 788 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 789 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 790 791 setOperationAction( 792 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 793 Custom); 794 795 setOperationAction(ISD::VSELECT, VT, Custom); 796 setOperationAction(ISD::SELECT_CC, VT, Expand); 797 798 setOperationAction( 799 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 800 801 // Custom-lower reduction operations to set up the corresponding custom 802 // nodes' operands. 803 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 804 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 805 ISD::VECREDUCE_UMIN}, 806 VT, Custom); 807 808 for (unsigned VPOpc : IntegerVPOps) 809 setOperationAction(VPOpc, VT, Custom); 810 811 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 812 // type that can represent the value exactly. 813 if (VT.getVectorElementType() != MVT::i64) { 814 MVT FloatEltVT = 815 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 816 EVT FloatVT = 817 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 818 if (isTypeLegal(FloatVT)) 819 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 820 Custom); 821 } 822 } 823 824 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 825 if (!useRVVForFixedLengthVectorVT(VT)) 826 continue; 827 828 // By default everything must be expanded. 829 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 830 setOperationAction(Op, VT, Expand); 831 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 832 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 833 setTruncStoreAction(VT, OtherVT, Expand); 834 } 835 836 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 837 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 838 Custom); 839 840 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 841 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 842 ISD::EXTRACT_VECTOR_ELT}, 843 VT, Custom); 844 845 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 846 ISD::MGATHER, ISD::MSCATTER}, 847 VT, Custom); 848 849 setOperationAction( 850 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 851 Custom); 852 853 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 854 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 855 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 856 VT, Custom); 857 858 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 859 860 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 861 VT, Custom); 862 863 for (auto CC : VFPCCToExpand) 864 setCondCodeAction(CC, VT, Expand); 865 866 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 867 setOperationAction(ISD::SELECT_CC, VT, Expand); 868 869 setOperationAction(ISD::BITCAST, VT, Custom); 870 871 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 872 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 873 VT, Custom); 874 875 for (unsigned VPOpc : FloatingPointVPOps) 876 setOperationAction(VPOpc, VT, Custom); 877 } 878 879 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 880 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 881 Custom); 882 if (Subtarget.hasStdExtZfh()) 883 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 884 if (Subtarget.hasStdExtF()) 885 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 886 if (Subtarget.hasStdExtD()) 887 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 888 } 889 } 890 891 // Function alignments. 892 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 893 setMinFunctionAlignment(FunctionAlignment); 894 setPrefFunctionAlignment(FunctionAlignment); 895 896 setMinimumJumpTableEntries(5); 897 898 // Jumps are expensive, compared to logic 899 setJumpIsExpensive(); 900 901 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 902 ISD::OR, ISD::XOR}); 903 904 if (Subtarget.hasStdExtZbp()) 905 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 906 if (Subtarget.hasStdExtZbkb()) 907 setTargetDAGCombine(ISD::BITREVERSE); 908 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 909 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 910 if (Subtarget.hasStdExtF()) 911 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 912 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 913 if (Subtarget.hasVInstructions()) 914 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 915 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 916 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 917 918 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 919 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 920 } 921 922 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 923 LLVMContext &Context, 924 EVT VT) const { 925 if (!VT.isVector()) 926 return getPointerTy(DL); 927 if (Subtarget.hasVInstructions() && 928 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 929 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 930 return VT.changeVectorElementTypeToInteger(); 931 } 932 933 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 934 return Subtarget.getXLenVT(); 935 } 936 937 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 938 const CallInst &I, 939 MachineFunction &MF, 940 unsigned Intrinsic) const { 941 auto &DL = I.getModule()->getDataLayout(); 942 switch (Intrinsic) { 943 default: 944 return false; 945 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 946 case Intrinsic::riscv_masked_atomicrmw_add_i32: 947 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 948 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 949 case Intrinsic::riscv_masked_atomicrmw_max_i32: 950 case Intrinsic::riscv_masked_atomicrmw_min_i32: 951 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 952 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 953 case Intrinsic::riscv_masked_cmpxchg_i32: 954 Info.opc = ISD::INTRINSIC_W_CHAIN; 955 Info.memVT = MVT::i32; 956 Info.ptrVal = I.getArgOperand(0); 957 Info.offset = 0; 958 Info.align = Align(4); 959 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 960 MachineMemOperand::MOVolatile; 961 return true; 962 case Intrinsic::riscv_masked_strided_load: 963 Info.opc = ISD::INTRINSIC_W_CHAIN; 964 Info.ptrVal = I.getArgOperand(1); 965 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 966 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 967 Info.size = MemoryLocation::UnknownSize; 968 Info.flags |= MachineMemOperand::MOLoad; 969 return true; 970 case Intrinsic::riscv_masked_strided_store: 971 Info.opc = ISD::INTRINSIC_VOID; 972 Info.ptrVal = I.getArgOperand(1); 973 Info.memVT = 974 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 975 Info.align = Align( 976 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 977 8); 978 Info.size = MemoryLocation::UnknownSize; 979 Info.flags |= MachineMemOperand::MOStore; 980 return true; 981 case Intrinsic::riscv_seg2_load: 982 case Intrinsic::riscv_seg3_load: 983 case Intrinsic::riscv_seg4_load: 984 case Intrinsic::riscv_seg5_load: 985 case Intrinsic::riscv_seg6_load: 986 case Intrinsic::riscv_seg7_load: 987 case Intrinsic::riscv_seg8_load: 988 Info.opc = ISD::INTRINSIC_W_CHAIN; 989 Info.ptrVal = I.getArgOperand(0); 990 Info.memVT = 991 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 992 Info.align = 993 Align(DL.getTypeSizeInBits( 994 I.getType()->getStructElementType(0)->getScalarType()) / 995 8); 996 Info.size = MemoryLocation::UnknownSize; 997 Info.flags |= MachineMemOperand::MOLoad; 998 return true; 999 } 1000 } 1001 1002 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1003 const AddrMode &AM, Type *Ty, 1004 unsigned AS, 1005 Instruction *I) const { 1006 // No global is ever allowed as a base. 1007 if (AM.BaseGV) 1008 return false; 1009 1010 // Require a 12-bit signed offset. 1011 if (!isInt<12>(AM.BaseOffs)) 1012 return false; 1013 1014 switch (AM.Scale) { 1015 case 0: // "r+i" or just "i", depending on HasBaseReg. 1016 break; 1017 case 1: 1018 if (!AM.HasBaseReg) // allow "r+i". 1019 break; 1020 return false; // disallow "r+r" or "r+r+i". 1021 default: 1022 return false; 1023 } 1024 1025 return true; 1026 } 1027 1028 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1029 return isInt<12>(Imm); 1030 } 1031 1032 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1033 return isInt<12>(Imm); 1034 } 1035 1036 // On RV32, 64-bit integers are split into their high and low parts and held 1037 // in two different registers, so the trunc is free since the low register can 1038 // just be used. 1039 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1040 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1041 return false; 1042 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1043 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1044 return (SrcBits == 64 && DestBits == 32); 1045 } 1046 1047 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1048 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1049 !SrcVT.isInteger() || !DstVT.isInteger()) 1050 return false; 1051 unsigned SrcBits = SrcVT.getSizeInBits(); 1052 unsigned DestBits = DstVT.getSizeInBits(); 1053 return (SrcBits == 64 && DestBits == 32); 1054 } 1055 1056 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1057 // Zexts are free if they can be combined with a load. 1058 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1059 // poorly with type legalization of compares preferring sext. 1060 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1061 EVT MemVT = LD->getMemoryVT(); 1062 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1063 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1064 LD->getExtensionType() == ISD::ZEXTLOAD)) 1065 return true; 1066 } 1067 1068 return TargetLowering::isZExtFree(Val, VT2); 1069 } 1070 1071 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1072 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1073 } 1074 1075 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1076 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1077 } 1078 1079 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1080 return Subtarget.hasStdExtZbb(); 1081 } 1082 1083 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1084 return Subtarget.hasStdExtZbb(); 1085 } 1086 1087 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1088 EVT VT = Y.getValueType(); 1089 1090 // FIXME: Support vectors once we have tests. 1091 if (VT.isVector()) 1092 return false; 1093 1094 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1095 Subtarget.hasStdExtZbkb()) && 1096 !isa<ConstantSDNode>(Y); 1097 } 1098 1099 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1100 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1101 auto *C = dyn_cast<ConstantSDNode>(Y); 1102 return C && C->getAPIntValue().ule(10); 1103 } 1104 1105 /// Check if sinking \p I's operands to I's basic block is profitable, because 1106 /// the operands can be folded into a target instruction, e.g. 1107 /// splats of scalars can fold into vector instructions. 1108 bool RISCVTargetLowering::shouldSinkOperands( 1109 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1110 using namespace llvm::PatternMatch; 1111 1112 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1113 return false; 1114 1115 auto IsSinker = [&](Instruction *I, int Operand) { 1116 switch (I->getOpcode()) { 1117 case Instruction::Add: 1118 case Instruction::Sub: 1119 case Instruction::Mul: 1120 case Instruction::And: 1121 case Instruction::Or: 1122 case Instruction::Xor: 1123 case Instruction::FAdd: 1124 case Instruction::FSub: 1125 case Instruction::FMul: 1126 case Instruction::FDiv: 1127 case Instruction::ICmp: 1128 case Instruction::FCmp: 1129 return true; 1130 case Instruction::Shl: 1131 case Instruction::LShr: 1132 case Instruction::AShr: 1133 case Instruction::UDiv: 1134 case Instruction::SDiv: 1135 case Instruction::URem: 1136 case Instruction::SRem: 1137 return Operand == 1; 1138 case Instruction::Call: 1139 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1140 switch (II->getIntrinsicID()) { 1141 case Intrinsic::fma: 1142 case Intrinsic::vp_fma: 1143 return Operand == 0 || Operand == 1; 1144 // FIXME: Our patterns can only match vx/vf instructions when the splat 1145 // it on the RHS, because TableGen doesn't recognize our VP operations 1146 // as commutative. 1147 case Intrinsic::vp_add: 1148 case Intrinsic::vp_mul: 1149 case Intrinsic::vp_and: 1150 case Intrinsic::vp_or: 1151 case Intrinsic::vp_xor: 1152 case Intrinsic::vp_fadd: 1153 case Intrinsic::vp_fmul: 1154 case Intrinsic::vp_shl: 1155 case Intrinsic::vp_lshr: 1156 case Intrinsic::vp_ashr: 1157 case Intrinsic::vp_udiv: 1158 case Intrinsic::vp_sdiv: 1159 case Intrinsic::vp_urem: 1160 case Intrinsic::vp_srem: 1161 return Operand == 1; 1162 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1163 // explicit patterns for both LHS and RHS (as 'vr' versions). 1164 case Intrinsic::vp_sub: 1165 case Intrinsic::vp_fsub: 1166 case Intrinsic::vp_fdiv: 1167 return Operand == 0 || Operand == 1; 1168 default: 1169 return false; 1170 } 1171 } 1172 return false; 1173 default: 1174 return false; 1175 } 1176 }; 1177 1178 for (auto OpIdx : enumerate(I->operands())) { 1179 if (!IsSinker(I, OpIdx.index())) 1180 continue; 1181 1182 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1183 // Make sure we are not already sinking this operand 1184 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1185 continue; 1186 1187 // We are looking for a splat that can be sunk. 1188 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1189 m_Undef(), m_ZeroMask()))) 1190 continue; 1191 1192 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1193 // and vector registers 1194 for (Use &U : Op->uses()) { 1195 Instruction *Insn = cast<Instruction>(U.getUser()); 1196 if (!IsSinker(Insn, U.getOperandNo())) 1197 return false; 1198 } 1199 1200 Ops.push_back(&Op->getOperandUse(0)); 1201 Ops.push_back(&OpIdx.value()); 1202 } 1203 return true; 1204 } 1205 1206 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1207 bool ForCodeSize) const { 1208 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1209 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1210 return false; 1211 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1212 return false; 1213 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1214 return false; 1215 return Imm.isZero(); 1216 } 1217 1218 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1219 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1220 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1221 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1222 } 1223 1224 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1225 CallingConv::ID CC, 1226 EVT VT) const { 1227 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1228 // We might still end up using a GPR but that will be decided based on ABI. 1229 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1230 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1231 return MVT::f32; 1232 1233 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1234 } 1235 1236 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1237 CallingConv::ID CC, 1238 EVT VT) const { 1239 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1240 // We might still end up using a GPR but that will be decided based on ABI. 1241 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1242 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1243 return 1; 1244 1245 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1246 } 1247 1248 // Changes the condition code and swaps operands if necessary, so the SetCC 1249 // operation matches one of the comparisons supported directly by branches 1250 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1251 // with 1/-1. 1252 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1253 ISD::CondCode &CC, SelectionDAG &DAG) { 1254 // Convert X > -1 to X >= 0. 1255 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1256 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1257 CC = ISD::SETGE; 1258 return; 1259 } 1260 // Convert X < 1 to 0 >= X. 1261 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1262 RHS = LHS; 1263 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1264 CC = ISD::SETGE; 1265 return; 1266 } 1267 1268 switch (CC) { 1269 default: 1270 break; 1271 case ISD::SETGT: 1272 case ISD::SETLE: 1273 case ISD::SETUGT: 1274 case ISD::SETULE: 1275 CC = ISD::getSetCCSwappedOperands(CC); 1276 std::swap(LHS, RHS); 1277 break; 1278 } 1279 } 1280 1281 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1282 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1283 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1284 if (VT.getVectorElementType() == MVT::i1) 1285 KnownSize *= 8; 1286 1287 switch (KnownSize) { 1288 default: 1289 llvm_unreachable("Invalid LMUL."); 1290 case 8: 1291 return RISCVII::VLMUL::LMUL_F8; 1292 case 16: 1293 return RISCVII::VLMUL::LMUL_F4; 1294 case 32: 1295 return RISCVII::VLMUL::LMUL_F2; 1296 case 64: 1297 return RISCVII::VLMUL::LMUL_1; 1298 case 128: 1299 return RISCVII::VLMUL::LMUL_2; 1300 case 256: 1301 return RISCVII::VLMUL::LMUL_4; 1302 case 512: 1303 return RISCVII::VLMUL::LMUL_8; 1304 } 1305 } 1306 1307 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1308 switch (LMul) { 1309 default: 1310 llvm_unreachable("Invalid LMUL."); 1311 case RISCVII::VLMUL::LMUL_F8: 1312 case RISCVII::VLMUL::LMUL_F4: 1313 case RISCVII::VLMUL::LMUL_F2: 1314 case RISCVII::VLMUL::LMUL_1: 1315 return RISCV::VRRegClassID; 1316 case RISCVII::VLMUL::LMUL_2: 1317 return RISCV::VRM2RegClassID; 1318 case RISCVII::VLMUL::LMUL_4: 1319 return RISCV::VRM4RegClassID; 1320 case RISCVII::VLMUL::LMUL_8: 1321 return RISCV::VRM8RegClassID; 1322 } 1323 } 1324 1325 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1326 RISCVII::VLMUL LMUL = getLMUL(VT); 1327 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1328 LMUL == RISCVII::VLMUL::LMUL_F4 || 1329 LMUL == RISCVII::VLMUL::LMUL_F2 || 1330 LMUL == RISCVII::VLMUL::LMUL_1) { 1331 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1332 "Unexpected subreg numbering"); 1333 return RISCV::sub_vrm1_0 + Index; 1334 } 1335 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1336 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1337 "Unexpected subreg numbering"); 1338 return RISCV::sub_vrm2_0 + Index; 1339 } 1340 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1341 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1342 "Unexpected subreg numbering"); 1343 return RISCV::sub_vrm4_0 + Index; 1344 } 1345 llvm_unreachable("Invalid vector type."); 1346 } 1347 1348 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1349 if (VT.getVectorElementType() == MVT::i1) 1350 return RISCV::VRRegClassID; 1351 return getRegClassIDForLMUL(getLMUL(VT)); 1352 } 1353 1354 // Attempt to decompose a subvector insert/extract between VecVT and 1355 // SubVecVT via subregister indices. Returns the subregister index that 1356 // can perform the subvector insert/extract with the given element index, as 1357 // well as the index corresponding to any leftover subvectors that must be 1358 // further inserted/extracted within the register class for SubVecVT. 1359 std::pair<unsigned, unsigned> 1360 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1361 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1362 const RISCVRegisterInfo *TRI) { 1363 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1364 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1365 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1366 "Register classes not ordered"); 1367 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1368 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1369 // Try to compose a subregister index that takes us from the incoming 1370 // LMUL>1 register class down to the outgoing one. At each step we half 1371 // the LMUL: 1372 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1373 // Note that this is not guaranteed to find a subregister index, such as 1374 // when we are extracting from one VR type to another. 1375 unsigned SubRegIdx = RISCV::NoSubRegister; 1376 for (const unsigned RCID : 1377 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1378 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1379 VecVT = VecVT.getHalfNumVectorElementsVT(); 1380 bool IsHi = 1381 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1382 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1383 getSubregIndexByMVT(VecVT, IsHi)); 1384 if (IsHi) 1385 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1386 } 1387 return {SubRegIdx, InsertExtractIdx}; 1388 } 1389 1390 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1391 // stores for those types. 1392 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1393 return !Subtarget.useRVVForFixedLengthVectors() || 1394 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1395 } 1396 1397 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1398 if (ScalarTy->isPointerTy()) 1399 return true; 1400 1401 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1402 ScalarTy->isIntegerTy(32)) 1403 return true; 1404 1405 if (ScalarTy->isIntegerTy(64)) 1406 return Subtarget.hasVInstructionsI64(); 1407 1408 if (ScalarTy->isHalfTy()) 1409 return Subtarget.hasVInstructionsF16(); 1410 if (ScalarTy->isFloatTy()) 1411 return Subtarget.hasVInstructionsF32(); 1412 if (ScalarTy->isDoubleTy()) 1413 return Subtarget.hasVInstructionsF64(); 1414 1415 return false; 1416 } 1417 1418 static SDValue getVLOperand(SDValue Op) { 1419 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1420 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1421 "Unexpected opcode"); 1422 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1423 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1424 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1425 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1426 if (!II) 1427 return SDValue(); 1428 return Op.getOperand(II->VLOperand + 1 + HasChain); 1429 } 1430 1431 static bool useRVVForFixedLengthVectorVT(MVT VT, 1432 const RISCVSubtarget &Subtarget) { 1433 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1434 if (!Subtarget.useRVVForFixedLengthVectors()) 1435 return false; 1436 1437 // We only support a set of vector types with a consistent maximum fixed size 1438 // across all supported vector element types to avoid legalization issues. 1439 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1440 // fixed-length vector type we support is 1024 bytes. 1441 if (VT.getFixedSizeInBits() > 1024 * 8) 1442 return false; 1443 1444 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1445 1446 MVT EltVT = VT.getVectorElementType(); 1447 1448 // Don't use RVV for vectors we cannot scalarize if required. 1449 switch (EltVT.SimpleTy) { 1450 // i1 is supported but has different rules. 1451 default: 1452 return false; 1453 case MVT::i1: 1454 // Masks can only use a single register. 1455 if (VT.getVectorNumElements() > MinVLen) 1456 return false; 1457 MinVLen /= 8; 1458 break; 1459 case MVT::i8: 1460 case MVT::i16: 1461 case MVT::i32: 1462 break; 1463 case MVT::i64: 1464 if (!Subtarget.hasVInstructionsI64()) 1465 return false; 1466 break; 1467 case MVT::f16: 1468 if (!Subtarget.hasVInstructionsF16()) 1469 return false; 1470 break; 1471 case MVT::f32: 1472 if (!Subtarget.hasVInstructionsF32()) 1473 return false; 1474 break; 1475 case MVT::f64: 1476 if (!Subtarget.hasVInstructionsF64()) 1477 return false; 1478 break; 1479 } 1480 1481 // Reject elements larger than ELEN. 1482 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1483 return false; 1484 1485 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1486 // Don't use RVV for types that don't fit. 1487 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1488 return false; 1489 1490 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1491 // the base fixed length RVV support in place. 1492 if (!VT.isPow2VectorType()) 1493 return false; 1494 1495 return true; 1496 } 1497 1498 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1499 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1500 } 1501 1502 // Return the largest legal scalable vector type that matches VT's element type. 1503 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1504 const RISCVSubtarget &Subtarget) { 1505 // This may be called before legal types are setup. 1506 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1507 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1508 "Expected legal fixed length vector!"); 1509 1510 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1511 unsigned MaxELen = Subtarget.getELEN(); 1512 1513 MVT EltVT = VT.getVectorElementType(); 1514 switch (EltVT.SimpleTy) { 1515 default: 1516 llvm_unreachable("unexpected element type for RVV container"); 1517 case MVT::i1: 1518 case MVT::i8: 1519 case MVT::i16: 1520 case MVT::i32: 1521 case MVT::i64: 1522 case MVT::f16: 1523 case MVT::f32: 1524 case MVT::f64: { 1525 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1526 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1527 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1528 unsigned NumElts = 1529 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1530 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1531 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1532 return MVT::getScalableVectorVT(EltVT, NumElts); 1533 } 1534 } 1535 } 1536 1537 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1538 const RISCVSubtarget &Subtarget) { 1539 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1540 Subtarget); 1541 } 1542 1543 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1544 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1545 } 1546 1547 // Grow V to consume an entire RVV register. 1548 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1549 const RISCVSubtarget &Subtarget) { 1550 assert(VT.isScalableVector() && 1551 "Expected to convert into a scalable vector!"); 1552 assert(V.getValueType().isFixedLengthVector() && 1553 "Expected a fixed length vector operand!"); 1554 SDLoc DL(V); 1555 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1556 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1557 } 1558 1559 // Shrink V so it's just big enough to maintain a VT's worth of data. 1560 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1561 const RISCVSubtarget &Subtarget) { 1562 assert(VT.isFixedLengthVector() && 1563 "Expected to convert into a fixed length vector!"); 1564 assert(V.getValueType().isScalableVector() && 1565 "Expected a scalable vector operand!"); 1566 SDLoc DL(V); 1567 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1568 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1569 } 1570 1571 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1572 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1573 // the vector type that it is contained in. 1574 static std::pair<SDValue, SDValue> 1575 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1576 const RISCVSubtarget &Subtarget) { 1577 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1578 MVT XLenVT = Subtarget.getXLenVT(); 1579 SDValue VL = VecVT.isFixedLengthVector() 1580 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1581 : DAG.getRegister(RISCV::X0, XLenVT); 1582 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1583 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1584 return {Mask, VL}; 1585 } 1586 1587 // As above but assuming the given type is a scalable vector type. 1588 static std::pair<SDValue, SDValue> 1589 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1590 const RISCVSubtarget &Subtarget) { 1591 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1592 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1593 } 1594 1595 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1596 // of either is (currently) supported. This can get us into an infinite loop 1597 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1598 // as a ..., etc. 1599 // Until either (or both) of these can reliably lower any node, reporting that 1600 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1601 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1602 // which is not desirable. 1603 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1604 EVT VT, unsigned DefinedValues) const { 1605 return false; 1606 } 1607 1608 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1609 const RISCVSubtarget &Subtarget) { 1610 // RISCV FP-to-int conversions saturate to the destination register size, but 1611 // don't produce 0 for nan. We can use a conversion instruction and fix the 1612 // nan case with a compare and a select. 1613 SDValue Src = Op.getOperand(0); 1614 1615 EVT DstVT = Op.getValueType(); 1616 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1617 1618 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1619 unsigned Opc; 1620 if (SatVT == DstVT) 1621 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1622 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1623 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1624 else 1625 return SDValue(); 1626 // FIXME: Support other SatVTs by clamping before or after the conversion. 1627 1628 SDLoc DL(Op); 1629 SDValue FpToInt = DAG.getNode( 1630 Opc, DL, DstVT, Src, 1631 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1632 1633 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1634 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1635 } 1636 1637 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1638 // and back. Taking care to avoid converting values that are nan or already 1639 // correct. 1640 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1641 // have FRM dependencies modeled yet. 1642 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1643 MVT VT = Op.getSimpleValueType(); 1644 assert(VT.isVector() && "Unexpected type"); 1645 1646 SDLoc DL(Op); 1647 1648 // Freeze the source since we are increasing the number of uses. 1649 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1650 1651 // Truncate to integer and convert back to FP. 1652 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1653 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1654 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1655 1656 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1657 1658 if (Op.getOpcode() == ISD::FCEIL) { 1659 // If the truncated value is the greater than or equal to the original 1660 // value, we've computed the ceil. Otherwise, we went the wrong way and 1661 // need to increase by 1. 1662 // FIXME: This should use a masked operation. Handle here or in isel? 1663 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1664 DAG.getConstantFP(1.0, DL, VT)); 1665 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1666 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1667 } else if (Op.getOpcode() == ISD::FFLOOR) { 1668 // If the truncated value is the less than or equal to the original value, 1669 // we've computed the floor. Otherwise, we went the wrong way and need to 1670 // decrease by 1. 1671 // FIXME: This should use a masked operation. Handle here or in isel? 1672 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1673 DAG.getConstantFP(1.0, DL, VT)); 1674 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1675 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1676 } 1677 1678 // Restore the original sign so that -0.0 is preserved. 1679 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1680 1681 // Determine the largest integer that can be represented exactly. This and 1682 // values larger than it don't have any fractional bits so don't need to 1683 // be converted. 1684 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1685 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1686 APFloat MaxVal = APFloat(FltSem); 1687 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1688 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1689 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1690 1691 // If abs(Src) was larger than MaxVal or nan, keep it. 1692 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1693 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1694 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1695 } 1696 1697 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1698 // This mode isn't supported in vector hardware on RISCV. But as long as we 1699 // aren't compiling with trapping math, we can emulate this with 1700 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1701 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1702 // dependencies modeled yet. 1703 // FIXME: Use masked operations to avoid final merge. 1704 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1705 MVT VT = Op.getSimpleValueType(); 1706 assert(VT.isVector() && "Unexpected type"); 1707 1708 SDLoc DL(Op); 1709 1710 // Freeze the source since we are increasing the number of uses. 1711 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1712 1713 // We do the conversion on the absolute value and fix the sign at the end. 1714 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1715 1716 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1717 bool Ignored; 1718 APFloat Point5Pred = APFloat(0.5f); 1719 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1720 Point5Pred.next(/*nextDown*/ true); 1721 1722 // Add the adjustment. 1723 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1724 DAG.getConstantFP(Point5Pred, DL, VT)); 1725 1726 // Truncate to integer and convert back to fp. 1727 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1728 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1729 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1730 1731 // Restore the original sign. 1732 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1733 1734 // Determine the largest integer that can be represented exactly. This and 1735 // values larger than it don't have any fractional bits so don't need to 1736 // be converted. 1737 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1738 APFloat MaxVal = APFloat(FltSem); 1739 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1740 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1741 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1742 1743 // If abs(Src) was larger than MaxVal or nan, keep it. 1744 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1745 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1746 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1747 } 1748 1749 struct VIDSequence { 1750 int64_t StepNumerator; 1751 unsigned StepDenominator; 1752 int64_t Addend; 1753 }; 1754 1755 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1756 // to the (non-zero) step S and start value X. This can be then lowered as the 1757 // RVV sequence (VID * S) + X, for example. 1758 // The step S is represented as an integer numerator divided by a positive 1759 // denominator. Note that the implementation currently only identifies 1760 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1761 // cannot detect 2/3, for example. 1762 // Note that this method will also match potentially unappealing index 1763 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1764 // determine whether this is worth generating code for. 1765 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1766 unsigned NumElts = Op.getNumOperands(); 1767 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1768 if (!Op.getValueType().isInteger()) 1769 return None; 1770 1771 Optional<unsigned> SeqStepDenom; 1772 Optional<int64_t> SeqStepNum, SeqAddend; 1773 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1774 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1775 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1776 // Assume undef elements match the sequence; we just have to be careful 1777 // when interpolating across them. 1778 if (Op.getOperand(Idx).isUndef()) 1779 continue; 1780 // The BUILD_VECTOR must be all constants. 1781 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1782 return None; 1783 1784 uint64_t Val = Op.getConstantOperandVal(Idx) & 1785 maskTrailingOnes<uint64_t>(EltSizeInBits); 1786 1787 if (PrevElt) { 1788 // Calculate the step since the last non-undef element, and ensure 1789 // it's consistent across the entire sequence. 1790 unsigned IdxDiff = Idx - PrevElt->second; 1791 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1792 1793 // A zero-value value difference means that we're somewhere in the middle 1794 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1795 // step change before evaluating the sequence. 1796 if (ValDiff == 0) 1797 continue; 1798 1799 int64_t Remainder = ValDiff % IdxDiff; 1800 // Normalize the step if it's greater than 1. 1801 if (Remainder != ValDiff) { 1802 // The difference must cleanly divide the element span. 1803 if (Remainder != 0) 1804 return None; 1805 ValDiff /= IdxDiff; 1806 IdxDiff = 1; 1807 } 1808 1809 if (!SeqStepNum) 1810 SeqStepNum = ValDiff; 1811 else if (ValDiff != SeqStepNum) 1812 return None; 1813 1814 if (!SeqStepDenom) 1815 SeqStepDenom = IdxDiff; 1816 else if (IdxDiff != *SeqStepDenom) 1817 return None; 1818 } 1819 1820 // Record this non-undef element for later. 1821 if (!PrevElt || PrevElt->first != Val) 1822 PrevElt = std::make_pair(Val, Idx); 1823 } 1824 1825 // We need to have logged a step for this to count as a legal index sequence. 1826 if (!SeqStepNum || !SeqStepDenom) 1827 return None; 1828 1829 // Loop back through the sequence and validate elements we might have skipped 1830 // while waiting for a valid step. While doing this, log any sequence addend. 1831 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1832 if (Op.getOperand(Idx).isUndef()) 1833 continue; 1834 uint64_t Val = Op.getConstantOperandVal(Idx) & 1835 maskTrailingOnes<uint64_t>(EltSizeInBits); 1836 uint64_t ExpectedVal = 1837 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1838 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1839 if (!SeqAddend) 1840 SeqAddend = Addend; 1841 else if (Addend != SeqAddend) 1842 return None; 1843 } 1844 1845 assert(SeqAddend && "Must have an addend if we have a step"); 1846 1847 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1848 } 1849 1850 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1851 // and lower it as a VRGATHER_VX_VL from the source vector. 1852 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1853 SelectionDAG &DAG, 1854 const RISCVSubtarget &Subtarget) { 1855 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1856 return SDValue(); 1857 SDValue Vec = SplatVal.getOperand(0); 1858 // Only perform this optimization on vectors of the same size for simplicity. 1859 if (Vec.getValueType() != VT) 1860 return SDValue(); 1861 SDValue Idx = SplatVal.getOperand(1); 1862 // The index must be a legal type. 1863 if (Idx.getValueType() != Subtarget.getXLenVT()) 1864 return SDValue(); 1865 1866 MVT ContainerVT = VT; 1867 if (VT.isFixedLengthVector()) { 1868 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1869 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1870 } 1871 1872 SDValue Mask, VL; 1873 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1874 1875 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1876 Idx, Mask, VL); 1877 1878 if (!VT.isFixedLengthVector()) 1879 return Gather; 1880 1881 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1882 } 1883 1884 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1885 const RISCVSubtarget &Subtarget) { 1886 MVT VT = Op.getSimpleValueType(); 1887 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1888 1889 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1890 1891 SDLoc DL(Op); 1892 SDValue Mask, VL; 1893 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1894 1895 MVT XLenVT = Subtarget.getXLenVT(); 1896 unsigned NumElts = Op.getNumOperands(); 1897 1898 if (VT.getVectorElementType() == MVT::i1) { 1899 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1900 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1901 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1902 } 1903 1904 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1905 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1906 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1907 } 1908 1909 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1910 // scalar integer chunks whose bit-width depends on the number of mask 1911 // bits and XLEN. 1912 // First, determine the most appropriate scalar integer type to use. This 1913 // is at most XLenVT, but may be shrunk to a smaller vector element type 1914 // according to the size of the final vector - use i8 chunks rather than 1915 // XLenVT if we're producing a v8i1. This results in more consistent 1916 // codegen across RV32 and RV64. 1917 unsigned NumViaIntegerBits = 1918 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1919 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1920 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1921 // If we have to use more than one INSERT_VECTOR_ELT then this 1922 // optimization is likely to increase code size; avoid peforming it in 1923 // such a case. We can use a load from a constant pool in this case. 1924 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1925 return SDValue(); 1926 // Now we can create our integer vector type. Note that it may be larger 1927 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1928 MVT IntegerViaVecVT = 1929 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1930 divideCeil(NumElts, NumViaIntegerBits)); 1931 1932 uint64_t Bits = 0; 1933 unsigned BitPos = 0, IntegerEltIdx = 0; 1934 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1935 1936 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1937 // Once we accumulate enough bits to fill our scalar type, insert into 1938 // our vector and clear our accumulated data. 1939 if (I != 0 && I % NumViaIntegerBits == 0) { 1940 if (NumViaIntegerBits <= 32) 1941 Bits = SignExtend64(Bits, 32); 1942 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1943 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1944 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1945 Bits = 0; 1946 BitPos = 0; 1947 IntegerEltIdx++; 1948 } 1949 SDValue V = Op.getOperand(I); 1950 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1951 Bits |= ((uint64_t)BitValue << BitPos); 1952 } 1953 1954 // Insert the (remaining) scalar value into position in our integer 1955 // vector type. 1956 if (NumViaIntegerBits <= 32) 1957 Bits = SignExtend64(Bits, 32); 1958 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1959 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1960 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1961 1962 if (NumElts < NumViaIntegerBits) { 1963 // If we're producing a smaller vector than our minimum legal integer 1964 // type, bitcast to the equivalent (known-legal) mask type, and extract 1965 // our final mask. 1966 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1967 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1968 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1969 DAG.getConstant(0, DL, XLenVT)); 1970 } else { 1971 // Else we must have produced an integer type with the same size as the 1972 // mask type; bitcast for the final result. 1973 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1974 Vec = DAG.getBitcast(VT, Vec); 1975 } 1976 1977 return Vec; 1978 } 1979 1980 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1981 // vector type, we have a legal equivalently-sized i8 type, so we can use 1982 // that. 1983 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1984 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1985 1986 SDValue WideVec; 1987 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1988 // For a splat, perform a scalar truncate before creating the wider 1989 // vector. 1990 assert(Splat.getValueType() == XLenVT && 1991 "Unexpected type for i1 splat value"); 1992 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1993 DAG.getConstant(1, DL, XLenVT)); 1994 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1995 } else { 1996 SmallVector<SDValue, 8> Ops(Op->op_values()); 1997 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1998 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1999 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2000 } 2001 2002 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2003 } 2004 2005 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2006 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2007 return Gather; 2008 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2009 : RISCVISD::VMV_V_X_VL; 2010 Splat = 2011 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2012 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2013 } 2014 2015 // Try and match index sequences, which we can lower to the vid instruction 2016 // with optional modifications. An all-undef vector is matched by 2017 // getSplatValue, above. 2018 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2019 int64_t StepNumerator = SimpleVID->StepNumerator; 2020 unsigned StepDenominator = SimpleVID->StepDenominator; 2021 int64_t Addend = SimpleVID->Addend; 2022 2023 assert(StepNumerator != 0 && "Invalid step"); 2024 bool Negate = false; 2025 int64_t SplatStepVal = StepNumerator; 2026 unsigned StepOpcode = ISD::MUL; 2027 if (StepNumerator != 1) { 2028 if (isPowerOf2_64(std::abs(StepNumerator))) { 2029 Negate = StepNumerator < 0; 2030 StepOpcode = ISD::SHL; 2031 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2032 } 2033 } 2034 2035 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2036 // threshold since it's the immediate value many RVV instructions accept. 2037 // There is no vmul.vi instruction so ensure multiply constant can fit in 2038 // a single addi instruction. 2039 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2040 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2041 isPowerOf2_32(StepDenominator) && 2042 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2043 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2044 // Convert right out of the scalable type so we can use standard ISD 2045 // nodes for the rest of the computation. If we used scalable types with 2046 // these, we'd lose the fixed-length vector info and generate worse 2047 // vsetvli code. 2048 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2049 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2050 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2051 SDValue SplatStep = DAG.getSplatBuildVector( 2052 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2053 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2054 } 2055 if (StepDenominator != 1) { 2056 SDValue SplatStep = DAG.getSplatBuildVector( 2057 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2058 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2059 } 2060 if (Addend != 0 || Negate) { 2061 SDValue SplatAddend = DAG.getSplatBuildVector( 2062 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2063 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2064 } 2065 return VID; 2066 } 2067 } 2068 2069 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2070 // when re-interpreted as a vector with a larger element type. For example, 2071 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2072 // could be instead splat as 2073 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2074 // TODO: This optimization could also work on non-constant splats, but it 2075 // would require bit-manipulation instructions to construct the splat value. 2076 SmallVector<SDValue> Sequence; 2077 unsigned EltBitSize = VT.getScalarSizeInBits(); 2078 const auto *BV = cast<BuildVectorSDNode>(Op); 2079 if (VT.isInteger() && EltBitSize < 64 && 2080 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2081 BV->getRepeatedSequence(Sequence) && 2082 (Sequence.size() * EltBitSize) <= 64) { 2083 unsigned SeqLen = Sequence.size(); 2084 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2085 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2086 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2087 ViaIntVT == MVT::i64) && 2088 "Unexpected sequence type"); 2089 2090 unsigned EltIdx = 0; 2091 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2092 uint64_t SplatValue = 0; 2093 // Construct the amalgamated value which can be splatted as this larger 2094 // vector type. 2095 for (const auto &SeqV : Sequence) { 2096 if (!SeqV.isUndef()) 2097 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2098 << (EltIdx * EltBitSize)); 2099 EltIdx++; 2100 } 2101 2102 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2103 // achieve better constant materializion. 2104 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2105 SplatValue = SignExtend64(SplatValue, 32); 2106 2107 // Since we can't introduce illegal i64 types at this stage, we can only 2108 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2109 // way we can use RVV instructions to splat. 2110 assert((ViaIntVT.bitsLE(XLenVT) || 2111 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2112 "Unexpected bitcast sequence"); 2113 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2114 SDValue ViaVL = 2115 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2116 MVT ViaContainerVT = 2117 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2118 SDValue Splat = 2119 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2120 DAG.getUNDEF(ViaContainerVT), 2121 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2122 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2123 return DAG.getBitcast(VT, Splat); 2124 } 2125 } 2126 2127 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2128 // which constitute a large proportion of the elements. In such cases we can 2129 // splat a vector with the dominant element and make up the shortfall with 2130 // INSERT_VECTOR_ELTs. 2131 // Note that this includes vectors of 2 elements by association. The 2132 // upper-most element is the "dominant" one, allowing us to use a splat to 2133 // "insert" the upper element, and an insert of the lower element at position 2134 // 0, which improves codegen. 2135 SDValue DominantValue; 2136 unsigned MostCommonCount = 0; 2137 DenseMap<SDValue, unsigned> ValueCounts; 2138 unsigned NumUndefElts = 2139 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2140 2141 // Track the number of scalar loads we know we'd be inserting, estimated as 2142 // any non-zero floating-point constant. Other kinds of element are either 2143 // already in registers or are materialized on demand. The threshold at which 2144 // a vector load is more desirable than several scalar materializion and 2145 // vector-insertion instructions is not known. 2146 unsigned NumScalarLoads = 0; 2147 2148 for (SDValue V : Op->op_values()) { 2149 if (V.isUndef()) 2150 continue; 2151 2152 ValueCounts.insert(std::make_pair(V, 0)); 2153 unsigned &Count = ValueCounts[V]; 2154 2155 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2156 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2157 2158 // Is this value dominant? In case of a tie, prefer the highest element as 2159 // it's cheaper to insert near the beginning of a vector than it is at the 2160 // end. 2161 if (++Count >= MostCommonCount) { 2162 DominantValue = V; 2163 MostCommonCount = Count; 2164 } 2165 } 2166 2167 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2168 unsigned NumDefElts = NumElts - NumUndefElts; 2169 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2170 2171 // Don't perform this optimization when optimizing for size, since 2172 // materializing elements and inserting them tends to cause code bloat. 2173 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2174 ((MostCommonCount > DominantValueCountThreshold) || 2175 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2176 // Start by splatting the most common element. 2177 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2178 2179 DenseSet<SDValue> Processed{DominantValue}; 2180 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2181 for (const auto &OpIdx : enumerate(Op->ops())) { 2182 const SDValue &V = OpIdx.value(); 2183 if (V.isUndef() || !Processed.insert(V).second) 2184 continue; 2185 if (ValueCounts[V] == 1) { 2186 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2187 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2188 } else { 2189 // Blend in all instances of this value using a VSELECT, using a 2190 // mask where each bit signals whether that element is the one 2191 // we're after. 2192 SmallVector<SDValue> Ops; 2193 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2194 return DAG.getConstant(V == V1, DL, XLenVT); 2195 }); 2196 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2197 DAG.getBuildVector(SelMaskTy, DL, Ops), 2198 DAG.getSplatBuildVector(VT, DL, V), Vec); 2199 } 2200 } 2201 2202 return Vec; 2203 } 2204 2205 return SDValue(); 2206 } 2207 2208 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2209 SDValue Lo, SDValue Hi, SDValue VL, 2210 SelectionDAG &DAG) { 2211 if (!Passthru) 2212 Passthru = DAG.getUNDEF(VT); 2213 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2214 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2215 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2216 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2217 // node in order to try and match RVV vector/scalar instructions. 2218 if ((LoC >> 31) == HiC) 2219 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2220 2221 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2222 // vmv.v.x whose EEW = 32 to lower it. 2223 auto *Const = dyn_cast<ConstantSDNode>(VL); 2224 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2225 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2226 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2227 // access the subtarget here now. 2228 auto InterVec = DAG.getNode( 2229 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2230 DAG.getRegister(RISCV::X0, MVT::i32)); 2231 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2232 } 2233 } 2234 2235 // Fall back to a stack store and stride x0 vector load. 2236 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2237 Hi, VL); 2238 } 2239 2240 // Called by type legalization to handle splat of i64 on RV32. 2241 // FIXME: We can optimize this when the type has sign or zero bits in one 2242 // of the halves. 2243 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2244 SDValue Scalar, SDValue VL, 2245 SelectionDAG &DAG) { 2246 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2247 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2248 DAG.getConstant(0, DL, MVT::i32)); 2249 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2250 DAG.getConstant(1, DL, MVT::i32)); 2251 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2252 } 2253 2254 // This function lowers a splat of a scalar operand Splat with the vector 2255 // length VL. It ensures the final sequence is type legal, which is useful when 2256 // lowering a splat after type legalization. 2257 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2258 MVT VT, SDLoc DL, SelectionDAG &DAG, 2259 const RISCVSubtarget &Subtarget) { 2260 bool HasPassthru = Passthru && !Passthru.isUndef(); 2261 if (!HasPassthru && !Passthru) 2262 Passthru = DAG.getUNDEF(VT); 2263 if (VT.isFloatingPoint()) { 2264 // If VL is 1, we could use vfmv.s.f. 2265 if (isOneConstant(VL)) 2266 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2267 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2268 } 2269 2270 MVT XLenVT = Subtarget.getXLenVT(); 2271 2272 // Simplest case is that the operand needs to be promoted to XLenVT. 2273 if (Scalar.getValueType().bitsLE(XLenVT)) { 2274 // If the operand is a constant, sign extend to increase our chances 2275 // of being able to use a .vi instruction. ANY_EXTEND would become a 2276 // a zero extend and the simm5 check in isel would fail. 2277 // FIXME: Should we ignore the upper bits in isel instead? 2278 unsigned ExtOpc = 2279 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2280 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2281 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2282 // If VL is 1 and the scalar value won't benefit from immediate, we could 2283 // use vmv.s.x. 2284 if (isOneConstant(VL) && 2285 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2286 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2287 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2288 } 2289 2290 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2291 "Unexpected scalar for splat lowering!"); 2292 2293 if (isOneConstant(VL) && isNullConstant(Scalar)) 2294 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2295 DAG.getConstant(0, DL, XLenVT), VL); 2296 2297 // Otherwise use the more complicated splatting algorithm. 2298 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2299 } 2300 2301 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2302 const RISCVSubtarget &Subtarget) { 2303 // We need to be able to widen elements to the next larger integer type. 2304 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2305 return false; 2306 2307 int Size = Mask.size(); 2308 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2309 2310 int Srcs[] = {-1, -1}; 2311 for (int i = 0; i != Size; ++i) { 2312 // Ignore undef elements. 2313 if (Mask[i] < 0) 2314 continue; 2315 2316 // Is this an even or odd element. 2317 int Pol = i % 2; 2318 2319 // Ensure we consistently use the same source for this element polarity. 2320 int Src = Mask[i] / Size; 2321 if (Srcs[Pol] < 0) 2322 Srcs[Pol] = Src; 2323 if (Srcs[Pol] != Src) 2324 return false; 2325 2326 // Make sure the element within the source is appropriate for this element 2327 // in the destination. 2328 int Elt = Mask[i] % Size; 2329 if (Elt != i / 2) 2330 return false; 2331 } 2332 2333 // We need to find a source for each polarity and they can't be the same. 2334 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2335 return false; 2336 2337 // Swap the sources if the second source was in the even polarity. 2338 SwapSources = Srcs[0] > Srcs[1]; 2339 2340 return true; 2341 } 2342 2343 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2344 /// and then extract the original number of elements from the rotated result. 2345 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2346 /// returned rotation amount is for a rotate right, where elements move from 2347 /// higher elements to lower elements. \p LoSrc indicates the first source 2348 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2349 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2350 /// 0 or 1 if a rotation is found. 2351 /// 2352 /// NOTE: We talk about rotate to the right which matches how bit shift and 2353 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2354 /// and the table below write vectors with the lowest elements on the left. 2355 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2356 int Size = Mask.size(); 2357 2358 // We need to detect various ways of spelling a rotation: 2359 // [11, 12, 13, 14, 15, 0, 1, 2] 2360 // [-1, 12, 13, 14, -1, -1, 1, -1] 2361 // [-1, -1, -1, -1, -1, -1, 1, 2] 2362 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2363 // [-1, 4, 5, 6, -1, -1, 9, -1] 2364 // [-1, 4, 5, 6, -1, -1, -1, -1] 2365 int Rotation = 0; 2366 LoSrc = -1; 2367 HiSrc = -1; 2368 for (int i = 0; i != Size; ++i) { 2369 int M = Mask[i]; 2370 if (M < 0) 2371 continue; 2372 2373 // Determine where a rotate vector would have started. 2374 int StartIdx = i - (M % Size); 2375 // The identity rotation isn't interesting, stop. 2376 if (StartIdx == 0) 2377 return -1; 2378 2379 // If we found the tail of a vector the rotation must be the missing 2380 // front. If we found the head of a vector, it must be how much of the 2381 // head. 2382 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2383 2384 if (Rotation == 0) 2385 Rotation = CandidateRotation; 2386 else if (Rotation != CandidateRotation) 2387 // The rotations don't match, so we can't match this mask. 2388 return -1; 2389 2390 // Compute which value this mask is pointing at. 2391 int MaskSrc = M < Size ? 0 : 1; 2392 2393 // Compute which of the two target values this index should be assigned to. 2394 // This reflects whether the high elements are remaining or the low elemnts 2395 // are remaining. 2396 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2397 2398 // Either set up this value if we've not encountered it before, or check 2399 // that it remains consistent. 2400 if (TargetSrc < 0) 2401 TargetSrc = MaskSrc; 2402 else if (TargetSrc != MaskSrc) 2403 // This may be a rotation, but it pulls from the inputs in some 2404 // unsupported interleaving. 2405 return -1; 2406 } 2407 2408 // Check that we successfully analyzed the mask, and normalize the results. 2409 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2410 assert((LoSrc >= 0 || HiSrc >= 0) && 2411 "Failed to find a rotated input vector!"); 2412 2413 return Rotation; 2414 } 2415 2416 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2417 const RISCVSubtarget &Subtarget) { 2418 SDValue V1 = Op.getOperand(0); 2419 SDValue V2 = Op.getOperand(1); 2420 SDLoc DL(Op); 2421 MVT XLenVT = Subtarget.getXLenVT(); 2422 MVT VT = Op.getSimpleValueType(); 2423 unsigned NumElts = VT.getVectorNumElements(); 2424 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2425 2426 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2427 2428 SDValue TrueMask, VL; 2429 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2430 2431 if (SVN->isSplat()) { 2432 const int Lane = SVN->getSplatIndex(); 2433 if (Lane >= 0) { 2434 MVT SVT = VT.getVectorElementType(); 2435 2436 // Turn splatted vector load into a strided load with an X0 stride. 2437 SDValue V = V1; 2438 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2439 // with undef. 2440 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2441 int Offset = Lane; 2442 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2443 int OpElements = 2444 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2445 V = V.getOperand(Offset / OpElements); 2446 Offset %= OpElements; 2447 } 2448 2449 // We need to ensure the load isn't atomic or volatile. 2450 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2451 auto *Ld = cast<LoadSDNode>(V); 2452 Offset *= SVT.getStoreSize(); 2453 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2454 TypeSize::Fixed(Offset), DL); 2455 2456 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2457 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2458 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2459 SDValue IntID = 2460 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2461 SDValue Ops[] = {Ld->getChain(), 2462 IntID, 2463 DAG.getUNDEF(ContainerVT), 2464 NewAddr, 2465 DAG.getRegister(RISCV::X0, XLenVT), 2466 VL}; 2467 SDValue NewLoad = DAG.getMemIntrinsicNode( 2468 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2469 DAG.getMachineFunction().getMachineMemOperand( 2470 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2471 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2472 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2473 } 2474 2475 // Otherwise use a scalar load and splat. This will give the best 2476 // opportunity to fold a splat into the operation. ISel can turn it into 2477 // the x0 strided load if we aren't able to fold away the select. 2478 if (SVT.isFloatingPoint()) 2479 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2480 Ld->getPointerInfo().getWithOffset(Offset), 2481 Ld->getOriginalAlign(), 2482 Ld->getMemOperand()->getFlags()); 2483 else 2484 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2485 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2486 Ld->getOriginalAlign(), 2487 Ld->getMemOperand()->getFlags()); 2488 DAG.makeEquivalentMemoryOrdering(Ld, V); 2489 2490 unsigned Opc = 2491 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2492 SDValue Splat = 2493 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2494 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2495 } 2496 2497 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2498 assert(Lane < (int)NumElts && "Unexpected lane!"); 2499 SDValue Gather = 2500 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2501 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2502 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2503 } 2504 } 2505 2506 ArrayRef<int> Mask = SVN->getMask(); 2507 2508 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2509 // be undef which can be handled with a single SLIDEDOWN/UP. 2510 int LoSrc, HiSrc; 2511 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2512 if (Rotation > 0) { 2513 SDValue LoV, HiV; 2514 if (LoSrc >= 0) { 2515 LoV = LoSrc == 0 ? V1 : V2; 2516 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2517 } 2518 if (HiSrc >= 0) { 2519 HiV = HiSrc == 0 ? V1 : V2; 2520 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2521 } 2522 2523 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2524 // to slide LoV up by (NumElts - Rotation). 2525 unsigned InvRotate = NumElts - Rotation; 2526 2527 SDValue Res = DAG.getUNDEF(ContainerVT); 2528 if (HiV) { 2529 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2530 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2531 // causes multiple vsetvlis in some test cases such as lowering 2532 // reduce.mul 2533 SDValue DownVL = VL; 2534 if (LoV) 2535 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2536 Res = 2537 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2538 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2539 } 2540 if (LoV) 2541 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2542 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2543 2544 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2545 } 2546 2547 // Detect an interleave shuffle and lower to 2548 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2549 bool SwapSources; 2550 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2551 // Swap sources if needed. 2552 if (SwapSources) 2553 std::swap(V1, V2); 2554 2555 // Extract the lower half of the vectors. 2556 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2557 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2558 DAG.getConstant(0, DL, XLenVT)); 2559 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2560 DAG.getConstant(0, DL, XLenVT)); 2561 2562 // Double the element width and halve the number of elements in an int type. 2563 unsigned EltBits = VT.getScalarSizeInBits(); 2564 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2565 MVT WideIntVT = 2566 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2567 // Convert this to a scalable vector. We need to base this on the 2568 // destination size to ensure there's always a type with a smaller LMUL. 2569 MVT WideIntContainerVT = 2570 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2571 2572 // Convert sources to scalable vectors with the same element count as the 2573 // larger type. 2574 MVT HalfContainerVT = MVT::getVectorVT( 2575 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2576 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2577 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2578 2579 // Cast sources to integer. 2580 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2581 MVT IntHalfVT = 2582 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2583 V1 = DAG.getBitcast(IntHalfVT, V1); 2584 V2 = DAG.getBitcast(IntHalfVT, V2); 2585 2586 // Freeze V2 since we use it twice and we need to be sure that the add and 2587 // multiply see the same value. 2588 V2 = DAG.getFreeze(V2); 2589 2590 // Recreate TrueMask using the widened type's element count. 2591 MVT MaskVT = 2592 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2593 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2594 2595 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2596 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2597 V2, TrueMask, VL); 2598 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2599 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2600 DAG.getUNDEF(IntHalfVT), 2601 DAG.getAllOnesConstant(DL, XLenVT)); 2602 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2603 V2, Multiplier, TrueMask, VL); 2604 // Add the new copies to our previous addition giving us 2^eltbits copies of 2605 // V2. This is equivalent to shifting V2 left by eltbits. This should 2606 // combine with the vwmulu.vv above to form vwmaccu.vv. 2607 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2608 TrueMask, VL); 2609 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2610 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2611 // vector VT. 2612 ContainerVT = 2613 MVT::getVectorVT(VT.getVectorElementType(), 2614 WideIntContainerVT.getVectorElementCount() * 2); 2615 Add = DAG.getBitcast(ContainerVT, Add); 2616 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2617 } 2618 2619 // Detect shuffles which can be re-expressed as vector selects; these are 2620 // shuffles in which each element in the destination is taken from an element 2621 // at the corresponding index in either source vectors. 2622 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2623 int MaskIndex = MaskIdx.value(); 2624 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2625 }); 2626 2627 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2628 2629 SmallVector<SDValue> MaskVals; 2630 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2631 // merged with a second vrgather. 2632 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2633 2634 // By default we preserve the original operand order, and use a mask to 2635 // select LHS as true and RHS as false. However, since RVV vector selects may 2636 // feature splats but only on the LHS, we may choose to invert our mask and 2637 // instead select between RHS and LHS. 2638 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2639 bool InvertMask = IsSelect == SwapOps; 2640 2641 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2642 // half. 2643 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2644 2645 // Now construct the mask that will be used by the vselect or blended 2646 // vrgather operation. For vrgathers, construct the appropriate indices into 2647 // each vector. 2648 for (int MaskIndex : Mask) { 2649 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2650 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2651 if (!IsSelect) { 2652 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2653 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2654 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2655 : DAG.getUNDEF(XLenVT)); 2656 GatherIndicesRHS.push_back( 2657 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2658 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2659 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2660 ++LHSIndexCounts[MaskIndex]; 2661 if (!IsLHSOrUndefIndex) 2662 ++RHSIndexCounts[MaskIndex - NumElts]; 2663 } 2664 } 2665 2666 if (SwapOps) { 2667 std::swap(V1, V2); 2668 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2669 } 2670 2671 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2672 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2673 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2674 2675 if (IsSelect) 2676 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2677 2678 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2679 // On such a large vector we're unable to use i8 as the index type. 2680 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2681 // may involve vector splitting if we're already at LMUL=8, or our 2682 // user-supplied maximum fixed-length LMUL. 2683 return SDValue(); 2684 } 2685 2686 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2687 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2688 MVT IndexVT = VT.changeTypeToInteger(); 2689 // Since we can't introduce illegal index types at this stage, use i16 and 2690 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2691 // than XLenVT. 2692 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2693 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2694 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2695 } 2696 2697 MVT IndexContainerVT = 2698 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2699 2700 SDValue Gather; 2701 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2702 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2703 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2704 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2705 Subtarget); 2706 } else { 2707 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2708 // If only one index is used, we can use a "splat" vrgather. 2709 // TODO: We can splat the most-common index and fix-up any stragglers, if 2710 // that's beneficial. 2711 if (LHSIndexCounts.size() == 1) { 2712 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2713 Gather = 2714 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2715 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2716 } else { 2717 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2718 LHSIndices = 2719 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2720 2721 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2722 TrueMask, VL); 2723 } 2724 } 2725 2726 // If a second vector operand is used by this shuffle, blend it in with an 2727 // additional vrgather. 2728 if (!V2.isUndef()) { 2729 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2730 // If only one index is used, we can use a "splat" vrgather. 2731 // TODO: We can splat the most-common index and fix-up any stragglers, if 2732 // that's beneficial. 2733 if (RHSIndexCounts.size() == 1) { 2734 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2735 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2736 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2737 } else { 2738 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2739 RHSIndices = 2740 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2741 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2742 VL); 2743 } 2744 2745 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2746 SelectMask = 2747 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2748 2749 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2750 Gather, VL); 2751 } 2752 2753 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2754 } 2755 2756 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2757 // Support splats for any type. These should type legalize well. 2758 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2759 return true; 2760 2761 // Only support legal VTs for other shuffles for now. 2762 if (!isTypeLegal(VT)) 2763 return false; 2764 2765 MVT SVT = VT.getSimpleVT(); 2766 2767 bool SwapSources; 2768 int LoSrc, HiSrc; 2769 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2770 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2771 } 2772 2773 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2774 SDLoc DL, SelectionDAG &DAG, 2775 const RISCVSubtarget &Subtarget) { 2776 if (VT.isScalableVector()) 2777 return DAG.getFPExtendOrRound(Op, DL, VT); 2778 assert(VT.isFixedLengthVector() && 2779 "Unexpected value type for RVV FP extend/round lowering"); 2780 SDValue Mask, VL; 2781 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2782 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2783 ? RISCVISD::FP_EXTEND_VL 2784 : RISCVISD::FP_ROUND_VL; 2785 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2786 } 2787 2788 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2789 // the exponent. 2790 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2791 MVT VT = Op.getSimpleValueType(); 2792 unsigned EltSize = VT.getScalarSizeInBits(); 2793 SDValue Src = Op.getOperand(0); 2794 SDLoc DL(Op); 2795 2796 // We need a FP type that can represent the value. 2797 // TODO: Use f16 for i8 when possible? 2798 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2799 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2800 2801 // Legal types should have been checked in the RISCVTargetLowering 2802 // constructor. 2803 // TODO: Splitting may make sense in some cases. 2804 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2805 "Expected legal float type!"); 2806 2807 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2808 // The trailing zero count is equal to log2 of this single bit value. 2809 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2810 SDValue Neg = 2811 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2812 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2813 } 2814 2815 // We have a legal FP type, convert to it. 2816 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2817 // Bitcast to integer and shift the exponent to the LSB. 2818 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2819 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2820 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2821 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2822 DAG.getConstant(ShiftAmt, DL, IntVT)); 2823 // Truncate back to original type to allow vnsrl. 2824 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2825 // The exponent contains log2 of the value in biased form. 2826 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2827 2828 // For trailing zeros, we just need to subtract the bias. 2829 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2830 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2831 DAG.getConstant(ExponentBias, DL, VT)); 2832 2833 // For leading zeros, we need to remove the bias and convert from log2 to 2834 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2835 unsigned Adjust = ExponentBias + (EltSize - 1); 2836 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2837 } 2838 2839 // While RVV has alignment restrictions, we should always be able to load as a 2840 // legal equivalently-sized byte-typed vector instead. This method is 2841 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2842 // the load is already correctly-aligned, it returns SDValue(). 2843 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2844 SelectionDAG &DAG) const { 2845 auto *Load = cast<LoadSDNode>(Op); 2846 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2847 2848 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2849 Load->getMemoryVT(), 2850 *Load->getMemOperand())) 2851 return SDValue(); 2852 2853 SDLoc DL(Op); 2854 MVT VT = Op.getSimpleValueType(); 2855 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2856 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2857 "Unexpected unaligned RVV load type"); 2858 MVT NewVT = 2859 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2860 assert(NewVT.isValid() && 2861 "Expecting equally-sized RVV vector types to be legal"); 2862 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2863 Load->getPointerInfo(), Load->getOriginalAlign(), 2864 Load->getMemOperand()->getFlags()); 2865 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2866 } 2867 2868 // While RVV has alignment restrictions, we should always be able to store as a 2869 // legal equivalently-sized byte-typed vector instead. This method is 2870 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2871 // returns SDValue() if the store is already correctly aligned. 2872 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2873 SelectionDAG &DAG) const { 2874 auto *Store = cast<StoreSDNode>(Op); 2875 assert(Store && Store->getValue().getValueType().isVector() && 2876 "Expected vector store"); 2877 2878 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2879 Store->getMemoryVT(), 2880 *Store->getMemOperand())) 2881 return SDValue(); 2882 2883 SDLoc DL(Op); 2884 SDValue StoredVal = Store->getValue(); 2885 MVT VT = StoredVal.getSimpleValueType(); 2886 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2887 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2888 "Unexpected unaligned RVV store type"); 2889 MVT NewVT = 2890 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2891 assert(NewVT.isValid() && 2892 "Expecting equally-sized RVV vector types to be legal"); 2893 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2894 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2895 Store->getPointerInfo(), Store->getOriginalAlign(), 2896 Store->getMemOperand()->getFlags()); 2897 } 2898 2899 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2900 SelectionDAG &DAG) const { 2901 switch (Op.getOpcode()) { 2902 default: 2903 report_fatal_error("unimplemented operand"); 2904 case ISD::GlobalAddress: 2905 return lowerGlobalAddress(Op, DAG); 2906 case ISD::BlockAddress: 2907 return lowerBlockAddress(Op, DAG); 2908 case ISD::ConstantPool: 2909 return lowerConstantPool(Op, DAG); 2910 case ISD::JumpTable: 2911 return lowerJumpTable(Op, DAG); 2912 case ISD::GlobalTLSAddress: 2913 return lowerGlobalTLSAddress(Op, DAG); 2914 case ISD::SELECT: 2915 return lowerSELECT(Op, DAG); 2916 case ISD::BRCOND: 2917 return lowerBRCOND(Op, DAG); 2918 case ISD::VASTART: 2919 return lowerVASTART(Op, DAG); 2920 case ISD::FRAMEADDR: 2921 return lowerFRAMEADDR(Op, DAG); 2922 case ISD::RETURNADDR: 2923 return lowerRETURNADDR(Op, DAG); 2924 case ISD::SHL_PARTS: 2925 return lowerShiftLeftParts(Op, DAG); 2926 case ISD::SRA_PARTS: 2927 return lowerShiftRightParts(Op, DAG, true); 2928 case ISD::SRL_PARTS: 2929 return lowerShiftRightParts(Op, DAG, false); 2930 case ISD::BITCAST: { 2931 SDLoc DL(Op); 2932 EVT VT = Op.getValueType(); 2933 SDValue Op0 = Op.getOperand(0); 2934 EVT Op0VT = Op0.getValueType(); 2935 MVT XLenVT = Subtarget.getXLenVT(); 2936 if (VT.isFixedLengthVector()) { 2937 // We can handle fixed length vector bitcasts with a simple replacement 2938 // in isel. 2939 if (Op0VT.isFixedLengthVector()) 2940 return Op; 2941 // When bitcasting from scalar to fixed-length vector, insert the scalar 2942 // into a one-element vector of the result type, and perform a vector 2943 // bitcast. 2944 if (!Op0VT.isVector()) { 2945 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2946 if (!isTypeLegal(BVT)) 2947 return SDValue(); 2948 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2949 DAG.getUNDEF(BVT), Op0, 2950 DAG.getConstant(0, DL, XLenVT))); 2951 } 2952 return SDValue(); 2953 } 2954 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2955 // thus: bitcast the vector to a one-element vector type whose element type 2956 // is the same as the result type, and extract the first element. 2957 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2958 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2959 if (!isTypeLegal(BVT)) 2960 return SDValue(); 2961 SDValue BVec = DAG.getBitcast(BVT, Op0); 2962 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2963 DAG.getConstant(0, DL, XLenVT)); 2964 } 2965 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2966 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2967 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2968 return FPConv; 2969 } 2970 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2971 Subtarget.hasStdExtF()) { 2972 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2973 SDValue FPConv = 2974 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2975 return FPConv; 2976 } 2977 return SDValue(); 2978 } 2979 case ISD::INTRINSIC_WO_CHAIN: 2980 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2981 case ISD::INTRINSIC_W_CHAIN: 2982 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2983 case ISD::INTRINSIC_VOID: 2984 return LowerINTRINSIC_VOID(Op, DAG); 2985 case ISD::BSWAP: 2986 case ISD::BITREVERSE: { 2987 MVT VT = Op.getSimpleValueType(); 2988 SDLoc DL(Op); 2989 if (Subtarget.hasStdExtZbp()) { 2990 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2991 // Start with the maximum immediate value which is the bitwidth - 1. 2992 unsigned Imm = VT.getSizeInBits() - 1; 2993 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2994 if (Op.getOpcode() == ISD::BSWAP) 2995 Imm &= ~0x7U; 2996 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2997 DAG.getConstant(Imm, DL, VT)); 2998 } 2999 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3000 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3001 // Expand bitreverse to a bswap(rev8) followed by brev8. 3002 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3003 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3004 // as brev8 by an isel pattern. 3005 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3006 DAG.getConstant(7, DL, VT)); 3007 } 3008 case ISD::FSHL: 3009 case ISD::FSHR: { 3010 MVT VT = Op.getSimpleValueType(); 3011 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3012 SDLoc DL(Op); 3013 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3014 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3015 // accidentally setting the extra bit. 3016 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3017 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3018 DAG.getConstant(ShAmtWidth, DL, VT)); 3019 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3020 // instruction use different orders. fshl will return its first operand for 3021 // shift of zero, fshr will return its second operand. fsl and fsr both 3022 // return rs1 so the ISD nodes need to have different operand orders. 3023 // Shift amount is in rs2. 3024 SDValue Op0 = Op.getOperand(0); 3025 SDValue Op1 = Op.getOperand(1); 3026 unsigned Opc = RISCVISD::FSL; 3027 if (Op.getOpcode() == ISD::FSHR) { 3028 std::swap(Op0, Op1); 3029 Opc = RISCVISD::FSR; 3030 } 3031 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3032 } 3033 case ISD::TRUNCATE: 3034 // Only custom-lower vector truncates 3035 if (!Op.getSimpleValueType().isVector()) 3036 return Op; 3037 return lowerVectorTruncLike(Op, DAG); 3038 case ISD::ANY_EXTEND: 3039 case ISD::ZERO_EXTEND: 3040 if (Op.getOperand(0).getValueType().isVector() && 3041 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3042 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3043 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3044 case ISD::SIGN_EXTEND: 3045 if (Op.getOperand(0).getValueType().isVector() && 3046 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3047 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3048 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3049 case ISD::SPLAT_VECTOR_PARTS: 3050 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3051 case ISD::INSERT_VECTOR_ELT: 3052 return lowerINSERT_VECTOR_ELT(Op, DAG); 3053 case ISD::EXTRACT_VECTOR_ELT: 3054 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3055 case ISD::VSCALE: { 3056 MVT VT = Op.getSimpleValueType(); 3057 SDLoc DL(Op); 3058 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3059 // We define our scalable vector types for lmul=1 to use a 64 bit known 3060 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3061 // vscale as VLENB / 8. 3062 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3063 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3064 report_fatal_error("Support for VLEN==32 is incomplete."); 3065 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3066 // We assume VLENB is a multiple of 8. We manually choose the best shift 3067 // here because SimplifyDemandedBits isn't always able to simplify it. 3068 uint64_t Val = Op.getConstantOperandVal(0); 3069 if (isPowerOf2_64(Val)) { 3070 uint64_t Log2 = Log2_64(Val); 3071 if (Log2 < 3) 3072 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3073 DAG.getConstant(3 - Log2, DL, VT)); 3074 if (Log2 > 3) 3075 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3076 DAG.getConstant(Log2 - 3, DL, VT)); 3077 return VLENB; 3078 } 3079 // If the multiplier is a multiple of 8, scale it down to avoid needing 3080 // to shift the VLENB value. 3081 if ((Val % 8) == 0) 3082 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3083 DAG.getConstant(Val / 8, DL, VT)); 3084 } 3085 3086 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3087 DAG.getConstant(3, DL, VT)); 3088 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3089 } 3090 case ISD::FPOWI: { 3091 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3092 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3093 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3094 Op.getOperand(1).getValueType() == MVT::i32) { 3095 SDLoc DL(Op); 3096 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3097 SDValue Powi = 3098 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3099 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3100 DAG.getIntPtrConstant(0, DL)); 3101 } 3102 return SDValue(); 3103 } 3104 case ISD::FP_EXTEND: { 3105 // RVV can only do fp_extend to types double the size as the source. We 3106 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3107 // via f32. 3108 SDLoc DL(Op); 3109 MVT VT = Op.getSimpleValueType(); 3110 SDValue Src = Op.getOperand(0); 3111 MVT SrcVT = Src.getSimpleValueType(); 3112 3113 // Prepare any fixed-length vector operands. 3114 MVT ContainerVT = VT; 3115 if (SrcVT.isFixedLengthVector()) { 3116 ContainerVT = getContainerForFixedLengthVector(VT); 3117 MVT SrcContainerVT = 3118 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3119 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3120 } 3121 3122 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3123 SrcVT.getVectorElementType() != MVT::f16) { 3124 // For scalable vectors, we only need to close the gap between 3125 // vXf16->vXf64. 3126 if (!VT.isFixedLengthVector()) 3127 return Op; 3128 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3129 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3130 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3131 } 3132 3133 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3134 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3135 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3136 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3137 3138 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3139 DL, DAG, Subtarget); 3140 if (VT.isFixedLengthVector()) 3141 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3142 return Extend; 3143 } 3144 case ISD::FP_ROUND: 3145 if (!Op.getValueType().isVector()) 3146 return Op; 3147 return lowerVectorFPRoundLike(Op, DAG); 3148 case ISD::FP_TO_SINT: 3149 case ISD::FP_TO_UINT: 3150 case ISD::SINT_TO_FP: 3151 case ISD::UINT_TO_FP: { 3152 // RVV can only do fp<->int conversions to types half/double the size as 3153 // the source. We custom-lower any conversions that do two hops into 3154 // sequences. 3155 MVT VT = Op.getSimpleValueType(); 3156 if (!VT.isVector()) 3157 return Op; 3158 SDLoc DL(Op); 3159 SDValue Src = Op.getOperand(0); 3160 MVT EltVT = VT.getVectorElementType(); 3161 MVT SrcVT = Src.getSimpleValueType(); 3162 MVT SrcEltVT = SrcVT.getVectorElementType(); 3163 unsigned EltSize = EltVT.getSizeInBits(); 3164 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3165 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3166 "Unexpected vector element types"); 3167 3168 bool IsInt2FP = SrcEltVT.isInteger(); 3169 // Widening conversions 3170 if (EltSize > (2 * SrcEltSize)) { 3171 if (IsInt2FP) { 3172 // Do a regular integer sign/zero extension then convert to float. 3173 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3174 VT.getVectorElementCount()); 3175 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3176 ? ISD::ZERO_EXTEND 3177 : ISD::SIGN_EXTEND; 3178 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3179 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3180 } 3181 // FP2Int 3182 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3183 // Do one doubling fp_extend then complete the operation by converting 3184 // to int. 3185 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3186 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3187 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3188 } 3189 3190 // Narrowing conversions 3191 if (SrcEltSize > (2 * EltSize)) { 3192 if (IsInt2FP) { 3193 // One narrowing int_to_fp, then an fp_round. 3194 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3195 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3196 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3197 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3198 } 3199 // FP2Int 3200 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3201 // representable by the integer, the result is poison. 3202 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3203 VT.getVectorElementCount()); 3204 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3205 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3206 } 3207 3208 // Scalable vectors can exit here. Patterns will handle equally-sized 3209 // conversions halving/doubling ones. 3210 if (!VT.isFixedLengthVector()) 3211 return Op; 3212 3213 // For fixed-length vectors we lower to a custom "VL" node. 3214 unsigned RVVOpc = 0; 3215 switch (Op.getOpcode()) { 3216 default: 3217 llvm_unreachable("Impossible opcode"); 3218 case ISD::FP_TO_SINT: 3219 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3220 break; 3221 case ISD::FP_TO_UINT: 3222 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3223 break; 3224 case ISD::SINT_TO_FP: 3225 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3226 break; 3227 case ISD::UINT_TO_FP: 3228 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3229 break; 3230 } 3231 3232 MVT ContainerVT, SrcContainerVT; 3233 // Derive the reference container type from the larger vector type. 3234 if (SrcEltSize > EltSize) { 3235 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3236 ContainerVT = 3237 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3238 } else { 3239 ContainerVT = getContainerForFixedLengthVector(VT); 3240 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3241 } 3242 3243 SDValue Mask, VL; 3244 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3245 3246 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3247 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3248 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3249 } 3250 case ISD::FP_TO_SINT_SAT: 3251 case ISD::FP_TO_UINT_SAT: 3252 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3253 case ISD::FTRUNC: 3254 case ISD::FCEIL: 3255 case ISD::FFLOOR: 3256 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3257 case ISD::FROUND: 3258 return lowerFROUND(Op, DAG); 3259 case ISD::VECREDUCE_ADD: 3260 case ISD::VECREDUCE_UMAX: 3261 case ISD::VECREDUCE_SMAX: 3262 case ISD::VECREDUCE_UMIN: 3263 case ISD::VECREDUCE_SMIN: 3264 return lowerVECREDUCE(Op, DAG); 3265 case ISD::VECREDUCE_AND: 3266 case ISD::VECREDUCE_OR: 3267 case ISD::VECREDUCE_XOR: 3268 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3269 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3270 return lowerVECREDUCE(Op, DAG); 3271 case ISD::VECREDUCE_FADD: 3272 case ISD::VECREDUCE_SEQ_FADD: 3273 case ISD::VECREDUCE_FMIN: 3274 case ISD::VECREDUCE_FMAX: 3275 return lowerFPVECREDUCE(Op, DAG); 3276 case ISD::VP_REDUCE_ADD: 3277 case ISD::VP_REDUCE_UMAX: 3278 case ISD::VP_REDUCE_SMAX: 3279 case ISD::VP_REDUCE_UMIN: 3280 case ISD::VP_REDUCE_SMIN: 3281 case ISD::VP_REDUCE_FADD: 3282 case ISD::VP_REDUCE_SEQ_FADD: 3283 case ISD::VP_REDUCE_FMIN: 3284 case ISD::VP_REDUCE_FMAX: 3285 return lowerVPREDUCE(Op, DAG); 3286 case ISD::VP_REDUCE_AND: 3287 case ISD::VP_REDUCE_OR: 3288 case ISD::VP_REDUCE_XOR: 3289 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3290 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3291 return lowerVPREDUCE(Op, DAG); 3292 case ISD::INSERT_SUBVECTOR: 3293 return lowerINSERT_SUBVECTOR(Op, DAG); 3294 case ISD::EXTRACT_SUBVECTOR: 3295 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3296 case ISD::STEP_VECTOR: 3297 return lowerSTEP_VECTOR(Op, DAG); 3298 case ISD::VECTOR_REVERSE: 3299 return lowerVECTOR_REVERSE(Op, DAG); 3300 case ISD::VECTOR_SPLICE: 3301 return lowerVECTOR_SPLICE(Op, DAG); 3302 case ISD::BUILD_VECTOR: 3303 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3304 case ISD::SPLAT_VECTOR: 3305 if (Op.getValueType().getVectorElementType() == MVT::i1) 3306 return lowerVectorMaskSplat(Op, DAG); 3307 return SDValue(); 3308 case ISD::VECTOR_SHUFFLE: 3309 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3310 case ISD::CONCAT_VECTORS: { 3311 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3312 // better than going through the stack, as the default expansion does. 3313 SDLoc DL(Op); 3314 MVT VT = Op.getSimpleValueType(); 3315 unsigned NumOpElts = 3316 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3317 SDValue Vec = DAG.getUNDEF(VT); 3318 for (const auto &OpIdx : enumerate(Op->ops())) { 3319 SDValue SubVec = OpIdx.value(); 3320 // Don't insert undef subvectors. 3321 if (SubVec.isUndef()) 3322 continue; 3323 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3324 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3325 } 3326 return Vec; 3327 } 3328 case ISD::LOAD: 3329 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3330 return V; 3331 if (Op.getValueType().isFixedLengthVector()) 3332 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3333 return Op; 3334 case ISD::STORE: 3335 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3336 return V; 3337 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3338 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3339 return Op; 3340 case ISD::MLOAD: 3341 case ISD::VP_LOAD: 3342 return lowerMaskedLoad(Op, DAG); 3343 case ISD::MSTORE: 3344 case ISD::VP_STORE: 3345 return lowerMaskedStore(Op, DAG); 3346 case ISD::SETCC: 3347 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3348 case ISD::ADD: 3349 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3350 case ISD::SUB: 3351 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3352 case ISD::MUL: 3353 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3354 case ISD::MULHS: 3355 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3356 case ISD::MULHU: 3357 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3358 case ISD::AND: 3359 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3360 RISCVISD::AND_VL); 3361 case ISD::OR: 3362 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3363 RISCVISD::OR_VL); 3364 case ISD::XOR: 3365 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3366 RISCVISD::XOR_VL); 3367 case ISD::SDIV: 3368 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3369 case ISD::SREM: 3370 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3371 case ISD::UDIV: 3372 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3373 case ISD::UREM: 3374 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3375 case ISD::SHL: 3376 case ISD::SRA: 3377 case ISD::SRL: 3378 if (Op.getSimpleValueType().isFixedLengthVector()) 3379 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3380 // This can be called for an i32 shift amount that needs to be promoted. 3381 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3382 "Unexpected custom legalisation"); 3383 return SDValue(); 3384 case ISD::SADDSAT: 3385 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3386 case ISD::UADDSAT: 3387 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3388 case ISD::SSUBSAT: 3389 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3390 case ISD::USUBSAT: 3391 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3392 case ISD::FADD: 3393 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3394 case ISD::FSUB: 3395 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3396 case ISD::FMUL: 3397 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3398 case ISD::FDIV: 3399 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3400 case ISD::FNEG: 3401 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3402 case ISD::FABS: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3404 case ISD::FSQRT: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3406 case ISD::FMA: 3407 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3408 case ISD::SMIN: 3409 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3410 case ISD::SMAX: 3411 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3412 case ISD::UMIN: 3413 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3414 case ISD::UMAX: 3415 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3416 case ISD::FMINNUM: 3417 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3418 case ISD::FMAXNUM: 3419 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3420 case ISD::ABS: 3421 return lowerABS(Op, DAG); 3422 case ISD::CTLZ_ZERO_UNDEF: 3423 case ISD::CTTZ_ZERO_UNDEF: 3424 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3425 case ISD::VSELECT: 3426 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3427 case ISD::FCOPYSIGN: 3428 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3429 case ISD::MGATHER: 3430 case ISD::VP_GATHER: 3431 return lowerMaskedGather(Op, DAG); 3432 case ISD::MSCATTER: 3433 case ISD::VP_SCATTER: 3434 return lowerMaskedScatter(Op, DAG); 3435 case ISD::FLT_ROUNDS_: 3436 return lowerGET_ROUNDING(Op, DAG); 3437 case ISD::SET_ROUNDING: 3438 return lowerSET_ROUNDING(Op, DAG); 3439 case ISD::VP_SELECT: 3440 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3441 case ISD::VP_MERGE: 3442 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3443 case ISD::VP_ADD: 3444 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3445 case ISD::VP_SUB: 3446 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3447 case ISD::VP_MUL: 3448 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3449 case ISD::VP_SDIV: 3450 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3451 case ISD::VP_UDIV: 3452 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3453 case ISD::VP_SREM: 3454 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3455 case ISD::VP_UREM: 3456 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3457 case ISD::VP_AND: 3458 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3459 case ISD::VP_OR: 3460 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3461 case ISD::VP_XOR: 3462 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3463 case ISD::VP_ASHR: 3464 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3465 case ISD::VP_LSHR: 3466 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3467 case ISD::VP_SHL: 3468 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3469 case ISD::VP_FADD: 3470 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3471 case ISD::VP_FSUB: 3472 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3473 case ISD::VP_FMUL: 3474 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3475 case ISD::VP_FDIV: 3476 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3477 case ISD::VP_FNEG: 3478 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3479 case ISD::VP_FMA: 3480 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3481 case ISD::VP_SEXT: 3482 case ISD::VP_ZEXT: 3483 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3484 return lowerVPExtMaskOp(Op, DAG); 3485 return lowerVPOp(Op, DAG, 3486 Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL 3487 : RISCVISD::VZEXT_VL); 3488 case ISD::VP_TRUNC: 3489 return lowerVectorTruncLike(Op, DAG); 3490 case ISD::VP_FP_ROUND: 3491 return lowerVectorFPRoundLike(Op, DAG); 3492 case ISD::VP_FPTOSI: 3493 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3494 case ISD::VP_FPTOUI: 3495 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3496 case ISD::VP_SITOFP: 3497 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3498 case ISD::VP_UITOFP: 3499 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3500 case ISD::VP_SETCC: 3501 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3502 return lowerVPSetCCMaskOp(Op, DAG); 3503 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3504 } 3505 } 3506 3507 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3508 SelectionDAG &DAG, unsigned Flags) { 3509 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3510 } 3511 3512 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3513 SelectionDAG &DAG, unsigned Flags) { 3514 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3515 Flags); 3516 } 3517 3518 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3519 SelectionDAG &DAG, unsigned Flags) { 3520 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3521 N->getOffset(), Flags); 3522 } 3523 3524 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3525 SelectionDAG &DAG, unsigned Flags) { 3526 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3527 } 3528 3529 template <class NodeTy> 3530 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3531 bool IsLocal) const { 3532 SDLoc DL(N); 3533 EVT Ty = getPointerTy(DAG.getDataLayout()); 3534 3535 if (isPositionIndependent()) { 3536 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3537 if (IsLocal) 3538 // Use PC-relative addressing to access the symbol. This generates the 3539 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3540 // %pcrel_lo(auipc)). 3541 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3542 3543 // Use PC-relative addressing to access the GOT for this symbol, then load 3544 // the address from the GOT. This generates the pattern (PseudoLA sym), 3545 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3546 SDValue Load = 3547 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3548 MachineFunction &MF = DAG.getMachineFunction(); 3549 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3550 MachinePointerInfo::getGOT(MF), 3551 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3552 MachineMemOperand::MOInvariant, 3553 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3554 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3555 return Load; 3556 } 3557 3558 switch (getTargetMachine().getCodeModel()) { 3559 default: 3560 report_fatal_error("Unsupported code model for lowering"); 3561 case CodeModel::Small: { 3562 // Generate a sequence for accessing addresses within the first 2 GiB of 3563 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3564 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3565 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3566 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3567 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3568 } 3569 case CodeModel::Medium: { 3570 // Generate a sequence for accessing addresses within any 2GiB range within 3571 // the address space. This generates the pattern (PseudoLLA sym), which 3572 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3573 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3574 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3575 } 3576 } 3577 } 3578 3579 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3580 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3581 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3582 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3583 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3584 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3585 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3586 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3587 3588 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3589 SelectionDAG &DAG) const { 3590 SDLoc DL(Op); 3591 EVT Ty = Op.getValueType(); 3592 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3593 int64_t Offset = N->getOffset(); 3594 MVT XLenVT = Subtarget.getXLenVT(); 3595 3596 const GlobalValue *GV = N->getGlobal(); 3597 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3598 SDValue Addr = getAddr(N, DAG, IsLocal); 3599 3600 // In order to maximise the opportunity for common subexpression elimination, 3601 // emit a separate ADD node for the global address offset instead of folding 3602 // it in the global address node. Later peephole optimisations may choose to 3603 // fold it back in when profitable. 3604 if (Offset != 0) 3605 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3606 DAG.getConstant(Offset, DL, XLenVT)); 3607 return Addr; 3608 } 3609 3610 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3611 SelectionDAG &DAG) const { 3612 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3613 3614 return getAddr(N, DAG); 3615 } 3616 3617 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3618 SelectionDAG &DAG) const { 3619 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3620 3621 return getAddr(N, DAG); 3622 } 3623 3624 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3625 SelectionDAG &DAG) const { 3626 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3627 3628 return getAddr(N, DAG); 3629 } 3630 3631 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3632 SelectionDAG &DAG, 3633 bool UseGOT) const { 3634 SDLoc DL(N); 3635 EVT Ty = getPointerTy(DAG.getDataLayout()); 3636 const GlobalValue *GV = N->getGlobal(); 3637 MVT XLenVT = Subtarget.getXLenVT(); 3638 3639 if (UseGOT) { 3640 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3641 // load the address from the GOT and add the thread pointer. This generates 3642 // the pattern (PseudoLA_TLS_IE sym), which expands to 3643 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3644 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3645 SDValue Load = 3646 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3647 MachineFunction &MF = DAG.getMachineFunction(); 3648 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3649 MachinePointerInfo::getGOT(MF), 3650 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3651 MachineMemOperand::MOInvariant, 3652 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3653 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3654 3655 // Add the thread pointer. 3656 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3657 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3658 } 3659 3660 // Generate a sequence for accessing the address relative to the thread 3661 // pointer, with the appropriate adjustment for the thread pointer offset. 3662 // This generates the pattern 3663 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3664 SDValue AddrHi = 3665 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3666 SDValue AddrAdd = 3667 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3668 SDValue AddrLo = 3669 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3670 3671 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3672 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3673 SDValue MNAdd = SDValue( 3674 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3675 0); 3676 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3677 } 3678 3679 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3680 SelectionDAG &DAG) const { 3681 SDLoc DL(N); 3682 EVT Ty = getPointerTy(DAG.getDataLayout()); 3683 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3684 const GlobalValue *GV = N->getGlobal(); 3685 3686 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3687 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3688 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3689 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3690 SDValue Load = 3691 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3692 3693 // Prepare argument list to generate call. 3694 ArgListTy Args; 3695 ArgListEntry Entry; 3696 Entry.Node = Load; 3697 Entry.Ty = CallTy; 3698 Args.push_back(Entry); 3699 3700 // Setup call to __tls_get_addr. 3701 TargetLowering::CallLoweringInfo CLI(DAG); 3702 CLI.setDebugLoc(DL) 3703 .setChain(DAG.getEntryNode()) 3704 .setLibCallee(CallingConv::C, CallTy, 3705 DAG.getExternalSymbol("__tls_get_addr", Ty), 3706 std::move(Args)); 3707 3708 return LowerCallTo(CLI).first; 3709 } 3710 3711 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3712 SelectionDAG &DAG) const { 3713 SDLoc DL(Op); 3714 EVT Ty = Op.getValueType(); 3715 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3716 int64_t Offset = N->getOffset(); 3717 MVT XLenVT = Subtarget.getXLenVT(); 3718 3719 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3720 3721 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3722 CallingConv::GHC) 3723 report_fatal_error("In GHC calling convention TLS is not supported"); 3724 3725 SDValue Addr; 3726 switch (Model) { 3727 case TLSModel::LocalExec: 3728 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3729 break; 3730 case TLSModel::InitialExec: 3731 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3732 break; 3733 case TLSModel::LocalDynamic: 3734 case TLSModel::GeneralDynamic: 3735 Addr = getDynamicTLSAddr(N, DAG); 3736 break; 3737 } 3738 3739 // In order to maximise the opportunity for common subexpression elimination, 3740 // emit a separate ADD node for the global address offset instead of folding 3741 // it in the global address node. Later peephole optimisations may choose to 3742 // fold it back in when profitable. 3743 if (Offset != 0) 3744 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3745 DAG.getConstant(Offset, DL, XLenVT)); 3746 return Addr; 3747 } 3748 3749 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3750 SDValue CondV = Op.getOperand(0); 3751 SDValue TrueV = Op.getOperand(1); 3752 SDValue FalseV = Op.getOperand(2); 3753 SDLoc DL(Op); 3754 MVT VT = Op.getSimpleValueType(); 3755 MVT XLenVT = Subtarget.getXLenVT(); 3756 3757 // Lower vector SELECTs to VSELECTs by splatting the condition. 3758 if (VT.isVector()) { 3759 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3760 SDValue CondSplat = VT.isScalableVector() 3761 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3762 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3763 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3764 } 3765 3766 // If the result type is XLenVT and CondV is the output of a SETCC node 3767 // which also operated on XLenVT inputs, then merge the SETCC node into the 3768 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3769 // compare+branch instructions. i.e.: 3770 // (select (setcc lhs, rhs, cc), truev, falsev) 3771 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3772 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3773 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3774 SDValue LHS = CondV.getOperand(0); 3775 SDValue RHS = CondV.getOperand(1); 3776 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3777 ISD::CondCode CCVal = CC->get(); 3778 3779 // Special case for a select of 2 constants that have a diffence of 1. 3780 // Normally this is done by DAGCombine, but if the select is introduced by 3781 // type legalization or op legalization, we miss it. Restricting to SETLT 3782 // case for now because that is what signed saturating add/sub need. 3783 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3784 // but we would probably want to swap the true/false values if the condition 3785 // is SETGE/SETLE to avoid an XORI. 3786 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3787 CCVal == ISD::SETLT) { 3788 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3789 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3790 if (TrueVal - 1 == FalseVal) 3791 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3792 if (TrueVal + 1 == FalseVal) 3793 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3794 } 3795 3796 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3797 3798 SDValue TargetCC = DAG.getCondCode(CCVal); 3799 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3800 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3801 } 3802 3803 // Otherwise: 3804 // (select condv, truev, falsev) 3805 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3806 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3807 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3808 3809 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3810 3811 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3812 } 3813 3814 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3815 SDValue CondV = Op.getOperand(1); 3816 SDLoc DL(Op); 3817 MVT XLenVT = Subtarget.getXLenVT(); 3818 3819 if (CondV.getOpcode() == ISD::SETCC && 3820 CondV.getOperand(0).getValueType() == XLenVT) { 3821 SDValue LHS = CondV.getOperand(0); 3822 SDValue RHS = CondV.getOperand(1); 3823 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3824 3825 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3826 3827 SDValue TargetCC = DAG.getCondCode(CCVal); 3828 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3829 LHS, RHS, TargetCC, Op.getOperand(2)); 3830 } 3831 3832 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3833 CondV, DAG.getConstant(0, DL, XLenVT), 3834 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3835 } 3836 3837 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3838 MachineFunction &MF = DAG.getMachineFunction(); 3839 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3840 3841 SDLoc DL(Op); 3842 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3843 getPointerTy(MF.getDataLayout())); 3844 3845 // vastart just stores the address of the VarArgsFrameIndex slot into the 3846 // memory location argument. 3847 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3848 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3849 MachinePointerInfo(SV)); 3850 } 3851 3852 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3853 SelectionDAG &DAG) const { 3854 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3855 MachineFunction &MF = DAG.getMachineFunction(); 3856 MachineFrameInfo &MFI = MF.getFrameInfo(); 3857 MFI.setFrameAddressIsTaken(true); 3858 Register FrameReg = RI.getFrameRegister(MF); 3859 int XLenInBytes = Subtarget.getXLen() / 8; 3860 3861 EVT VT = Op.getValueType(); 3862 SDLoc DL(Op); 3863 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3864 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3865 while (Depth--) { 3866 int Offset = -(XLenInBytes * 2); 3867 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3868 DAG.getIntPtrConstant(Offset, DL)); 3869 FrameAddr = 3870 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3871 } 3872 return FrameAddr; 3873 } 3874 3875 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3876 SelectionDAG &DAG) const { 3877 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3878 MachineFunction &MF = DAG.getMachineFunction(); 3879 MachineFrameInfo &MFI = MF.getFrameInfo(); 3880 MFI.setReturnAddressIsTaken(true); 3881 MVT XLenVT = Subtarget.getXLenVT(); 3882 int XLenInBytes = Subtarget.getXLen() / 8; 3883 3884 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3885 return SDValue(); 3886 3887 EVT VT = Op.getValueType(); 3888 SDLoc DL(Op); 3889 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3890 if (Depth) { 3891 int Off = -XLenInBytes; 3892 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3893 SDValue Offset = DAG.getConstant(Off, DL, VT); 3894 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3895 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3896 MachinePointerInfo()); 3897 } 3898 3899 // Return the value of the return address register, marking it an implicit 3900 // live-in. 3901 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3902 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3903 } 3904 3905 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3906 SelectionDAG &DAG) const { 3907 SDLoc DL(Op); 3908 SDValue Lo = Op.getOperand(0); 3909 SDValue Hi = Op.getOperand(1); 3910 SDValue Shamt = Op.getOperand(2); 3911 EVT VT = Lo.getValueType(); 3912 3913 // if Shamt-XLEN < 0: // Shamt < XLEN 3914 // Lo = Lo << Shamt 3915 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3916 // else: 3917 // Lo = 0 3918 // Hi = Lo << (Shamt-XLEN) 3919 3920 SDValue Zero = DAG.getConstant(0, DL, VT); 3921 SDValue One = DAG.getConstant(1, DL, VT); 3922 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3923 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3924 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3925 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3926 3927 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3928 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3929 SDValue ShiftRightLo = 3930 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3931 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3932 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3933 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3934 3935 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3936 3937 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3938 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3939 3940 SDValue Parts[2] = {Lo, Hi}; 3941 return DAG.getMergeValues(Parts, DL); 3942 } 3943 3944 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3945 bool IsSRA) 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 // SRA expansion: 3953 // if Shamt-XLEN < 0: // Shamt < XLEN 3954 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3955 // Hi = Hi >>s Shamt 3956 // else: 3957 // Lo = Hi >>s (Shamt-XLEN); 3958 // Hi = Hi >>s (XLEN-1) 3959 // 3960 // SRL expansion: 3961 // if Shamt-XLEN < 0: // Shamt < XLEN 3962 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3963 // Hi = Hi >>u Shamt 3964 // else: 3965 // Lo = Hi >>u (Shamt-XLEN); 3966 // Hi = 0; 3967 3968 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3969 3970 SDValue Zero = DAG.getConstant(0, DL, VT); 3971 SDValue One = DAG.getConstant(1, DL, VT); 3972 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3973 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3974 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3975 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3976 3977 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3978 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3979 SDValue ShiftLeftHi = 3980 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3981 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3982 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3983 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3984 SDValue HiFalse = 3985 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3986 3987 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3988 3989 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3990 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3991 3992 SDValue Parts[2] = {Lo, Hi}; 3993 return DAG.getMergeValues(Parts, DL); 3994 } 3995 3996 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3997 // legal equivalently-sized i8 type, so we can use that as a go-between. 3998 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3999 SelectionDAG &DAG) const { 4000 SDLoc DL(Op); 4001 MVT VT = Op.getSimpleValueType(); 4002 SDValue SplatVal = Op.getOperand(0); 4003 // All-zeros or all-ones splats are handled specially. 4004 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4005 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4006 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4007 } 4008 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4009 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4010 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4011 } 4012 MVT XLenVT = Subtarget.getXLenVT(); 4013 assert(SplatVal.getValueType() == XLenVT && 4014 "Unexpected type for i1 splat value"); 4015 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4016 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4017 DAG.getConstant(1, DL, XLenVT)); 4018 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4019 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4020 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4021 } 4022 4023 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4024 // illegal (currently only vXi64 RV32). 4025 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4026 // them to VMV_V_X_VL. 4027 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4028 SelectionDAG &DAG) const { 4029 SDLoc DL(Op); 4030 MVT VecVT = Op.getSimpleValueType(); 4031 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4032 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4033 4034 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4035 SDValue Lo = Op.getOperand(0); 4036 SDValue Hi = Op.getOperand(1); 4037 4038 if (VecVT.isFixedLengthVector()) { 4039 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4040 SDLoc DL(Op); 4041 SDValue Mask, VL; 4042 std::tie(Mask, VL) = 4043 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4044 4045 SDValue Res = 4046 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4047 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4048 } 4049 4050 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4051 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4052 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4053 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4054 // node in order to try and match RVV vector/scalar instructions. 4055 if ((LoC >> 31) == HiC) 4056 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4057 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4058 } 4059 4060 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4061 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4062 isa<ConstantSDNode>(Hi.getOperand(1)) && 4063 Hi.getConstantOperandVal(1) == 31) 4064 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4065 DAG.getRegister(RISCV::X0, MVT::i32)); 4066 4067 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4068 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4069 DAG.getUNDEF(VecVT), Lo, Hi, 4070 DAG.getRegister(RISCV::X0, MVT::i32)); 4071 } 4072 4073 // Custom-lower extensions from mask vectors by using a vselect either with 1 4074 // for zero/any-extension or -1 for sign-extension: 4075 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4076 // Note that any-extension is lowered identically to zero-extension. 4077 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4078 int64_t ExtTrueVal) const { 4079 SDLoc DL(Op); 4080 MVT VecVT = Op.getSimpleValueType(); 4081 SDValue Src = Op.getOperand(0); 4082 // Only custom-lower extensions from mask types 4083 assert(Src.getValueType().isVector() && 4084 Src.getValueType().getVectorElementType() == MVT::i1); 4085 4086 if (VecVT.isScalableVector()) { 4087 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4088 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4089 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4090 } 4091 4092 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4093 MVT I1ContainerVT = 4094 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4095 4096 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4097 4098 SDValue Mask, VL; 4099 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4100 4101 MVT XLenVT = Subtarget.getXLenVT(); 4102 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4103 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4104 4105 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4106 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4107 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4108 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4109 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4110 SplatTrueVal, SplatZero, VL); 4111 4112 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4113 } 4114 4115 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4116 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4117 MVT ExtVT = Op.getSimpleValueType(); 4118 // Only custom-lower extensions from fixed-length vector types. 4119 if (!ExtVT.isFixedLengthVector()) 4120 return Op; 4121 MVT VT = Op.getOperand(0).getSimpleValueType(); 4122 // Grab the canonical container type for the extended type. Infer the smaller 4123 // type from that to ensure the same number of vector elements, as we know 4124 // the LMUL will be sufficient to hold the smaller type. 4125 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4126 // Get the extended container type manually to ensure the same number of 4127 // vector elements between source and dest. 4128 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4129 ContainerExtVT.getVectorElementCount()); 4130 4131 SDValue Op1 = 4132 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4133 4134 SDLoc DL(Op); 4135 SDValue Mask, VL; 4136 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4137 4138 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4139 4140 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4141 } 4142 4143 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4144 // setcc operation: 4145 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4146 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4147 SelectionDAG &DAG) const { 4148 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4149 SDLoc DL(Op); 4150 EVT MaskVT = Op.getValueType(); 4151 // Only expect to custom-lower truncations to mask types 4152 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4153 "Unexpected type for vector mask lowering"); 4154 SDValue Src = Op.getOperand(0); 4155 MVT VecVT = Src.getSimpleValueType(); 4156 SDValue Mask, VL; 4157 if (IsVPTrunc) { 4158 Mask = Op.getOperand(1); 4159 VL = Op.getOperand(2); 4160 } 4161 // If this is a fixed vector, we need to convert it to a scalable vector. 4162 MVT ContainerVT = VecVT; 4163 4164 if (VecVT.isFixedLengthVector()) { 4165 ContainerVT = getContainerForFixedLengthVector(VecVT); 4166 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4167 if (IsVPTrunc) { 4168 MVT MaskContainerVT = 4169 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4170 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4171 } 4172 } 4173 4174 if (!IsVPTrunc) { 4175 std::tie(Mask, VL) = 4176 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4177 } 4178 4179 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4180 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4181 4182 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4183 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4184 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4185 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4186 4187 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4188 SDValue Trunc = 4189 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4190 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4191 DAG.getCondCode(ISD::SETNE), Mask, VL); 4192 if (MaskVT.isFixedLengthVector()) 4193 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4194 return Trunc; 4195 } 4196 4197 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4198 SelectionDAG &DAG) const { 4199 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4200 SDLoc DL(Op); 4201 4202 MVT VT = Op.getSimpleValueType(); 4203 // Only custom-lower vector truncates 4204 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4205 4206 // Truncates to mask types are handled differently 4207 if (VT.getVectorElementType() == MVT::i1) 4208 return lowerVectorMaskTruncLike(Op, DAG); 4209 4210 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4211 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4212 // truncate by one power of two at a time. 4213 MVT DstEltVT = VT.getVectorElementType(); 4214 4215 SDValue Src = Op.getOperand(0); 4216 MVT SrcVT = Src.getSimpleValueType(); 4217 MVT SrcEltVT = SrcVT.getVectorElementType(); 4218 4219 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4220 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4221 "Unexpected vector truncate lowering"); 4222 4223 MVT ContainerVT = SrcVT; 4224 SDValue Mask, VL; 4225 if (IsVPTrunc) { 4226 Mask = Op.getOperand(1); 4227 VL = Op.getOperand(2); 4228 } 4229 if (SrcVT.isFixedLengthVector()) { 4230 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4231 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4232 if (IsVPTrunc) { 4233 MVT MaskVT = 4234 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4235 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4236 } 4237 } 4238 4239 SDValue Result = Src; 4240 if (!IsVPTrunc) { 4241 std::tie(Mask, VL) = 4242 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4243 } 4244 4245 LLVMContext &Context = *DAG.getContext(); 4246 const ElementCount Count = ContainerVT.getVectorElementCount(); 4247 do { 4248 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4249 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4250 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4251 Mask, VL); 4252 } while (SrcEltVT != DstEltVT); 4253 4254 if (SrcVT.isFixedLengthVector()) 4255 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4256 4257 return Result; 4258 } 4259 4260 SDValue RISCVTargetLowering::lowerVectorFPRoundLike(SDValue Op, 4261 SelectionDAG &DAG) const { 4262 bool IsVPFPTrunc = Op.getOpcode() == ISD::VP_FP_ROUND; 4263 // RVV can only do truncate fp to types half the size as the source. We 4264 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4265 // conversion instruction. 4266 SDLoc DL(Op); 4267 MVT VT = Op.getSimpleValueType(); 4268 4269 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4270 4271 SDValue Src = Op.getOperand(0); 4272 MVT SrcVT = Src.getSimpleValueType(); 4273 4274 bool IsDirectConv = VT.getVectorElementType() != MVT::f16 || 4275 SrcVT.getVectorElementType() != MVT::f64; 4276 4277 // For FP_ROUND of scalable vectors, leave it to the pattern. 4278 if (!VT.isFixedLengthVector() && !IsVPFPTrunc && IsDirectConv) 4279 return Op; 4280 4281 // Prepare any fixed-length vector operands. 4282 MVT ContainerVT = VT; 4283 SDValue Mask, VL; 4284 if (IsVPFPTrunc) { 4285 Mask = Op.getOperand(1); 4286 VL = Op.getOperand(2); 4287 } 4288 if (VT.isFixedLengthVector()) { 4289 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4290 ContainerVT = 4291 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4292 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4293 if (IsVPFPTrunc) { 4294 MVT MaskVT = 4295 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4296 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4297 } 4298 } 4299 4300 if (!IsVPFPTrunc) 4301 std::tie(Mask, VL) = 4302 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4303 4304 if (IsDirectConv) { 4305 Src = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, Src, Mask, VL); 4306 if (VT.isFixedLengthVector()) 4307 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4308 return Src; 4309 } 4310 4311 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4312 SDValue IntermediateRound = 4313 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 4314 SDValue Round = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, 4315 IntermediateRound, Mask, VL); 4316 if (VT.isFixedLengthVector()) 4317 return convertFromScalableVector(VT, Round, DAG, Subtarget); 4318 return Round; 4319 } 4320 4321 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4322 // first position of a vector, and that vector is slid up to the insert index. 4323 // By limiting the active vector length to index+1 and merging with the 4324 // original vector (with an undisturbed tail policy for elements >= VL), we 4325 // achieve the desired result of leaving all elements untouched except the one 4326 // at VL-1, which is replaced with the desired value. 4327 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4328 SelectionDAG &DAG) const { 4329 SDLoc DL(Op); 4330 MVT VecVT = Op.getSimpleValueType(); 4331 SDValue Vec = Op.getOperand(0); 4332 SDValue Val = Op.getOperand(1); 4333 SDValue Idx = Op.getOperand(2); 4334 4335 if (VecVT.getVectorElementType() == MVT::i1) { 4336 // FIXME: For now we just promote to an i8 vector and insert into that, 4337 // but this is probably not optimal. 4338 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4339 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4340 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4341 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4342 } 4343 4344 MVT ContainerVT = VecVT; 4345 // If the operand is a fixed-length vector, convert to a scalable one. 4346 if (VecVT.isFixedLengthVector()) { 4347 ContainerVT = getContainerForFixedLengthVector(VecVT); 4348 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4349 } 4350 4351 MVT XLenVT = Subtarget.getXLenVT(); 4352 4353 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4354 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4355 // Even i64-element vectors on RV32 can be lowered without scalar 4356 // legalization if the most-significant 32 bits of the value are not affected 4357 // by the sign-extension of the lower 32 bits. 4358 // TODO: We could also catch sign extensions of a 32-bit value. 4359 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4360 const auto *CVal = cast<ConstantSDNode>(Val); 4361 if (isInt<32>(CVal->getSExtValue())) { 4362 IsLegalInsert = true; 4363 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4364 } 4365 } 4366 4367 SDValue Mask, VL; 4368 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4369 4370 SDValue ValInVec; 4371 4372 if (IsLegalInsert) { 4373 unsigned Opc = 4374 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4375 if (isNullConstant(Idx)) { 4376 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4377 if (!VecVT.isFixedLengthVector()) 4378 return Vec; 4379 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4380 } 4381 ValInVec = 4382 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4383 } else { 4384 // On RV32, i64-element vectors must be specially handled to place the 4385 // value at element 0, by using two vslide1up instructions in sequence on 4386 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4387 // this. 4388 SDValue One = DAG.getConstant(1, DL, XLenVT); 4389 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4390 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4391 MVT I32ContainerVT = 4392 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4393 SDValue I32Mask = 4394 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4395 // Limit the active VL to two. 4396 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4397 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4398 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4399 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4400 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4401 // First slide in the hi value, then the lo in underneath it. 4402 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4403 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4404 I32Mask, InsertI64VL); 4405 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4406 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4407 I32Mask, InsertI64VL); 4408 // Bitcast back to the right container type. 4409 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4410 } 4411 4412 // Now that the value is in a vector, slide it into position. 4413 SDValue InsertVL = 4414 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4415 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4416 ValInVec, Idx, Mask, InsertVL); 4417 if (!VecVT.isFixedLengthVector()) 4418 return Slideup; 4419 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4420 } 4421 4422 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4423 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4424 // types this is done using VMV_X_S to allow us to glean information about the 4425 // sign bits of the result. 4426 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4427 SelectionDAG &DAG) const { 4428 SDLoc DL(Op); 4429 SDValue Idx = Op.getOperand(1); 4430 SDValue Vec = Op.getOperand(0); 4431 EVT EltVT = Op.getValueType(); 4432 MVT VecVT = Vec.getSimpleValueType(); 4433 MVT XLenVT = Subtarget.getXLenVT(); 4434 4435 if (VecVT.getVectorElementType() == MVT::i1) { 4436 if (VecVT.isFixedLengthVector()) { 4437 unsigned NumElts = VecVT.getVectorNumElements(); 4438 if (NumElts >= 8) { 4439 MVT WideEltVT; 4440 unsigned WidenVecLen; 4441 SDValue ExtractElementIdx; 4442 SDValue ExtractBitIdx; 4443 unsigned MaxEEW = Subtarget.getELEN(); 4444 MVT LargestEltVT = MVT::getIntegerVT( 4445 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4446 if (NumElts <= LargestEltVT.getSizeInBits()) { 4447 assert(isPowerOf2_32(NumElts) && 4448 "the number of elements should be power of 2"); 4449 WideEltVT = MVT::getIntegerVT(NumElts); 4450 WidenVecLen = 1; 4451 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4452 ExtractBitIdx = Idx; 4453 } else { 4454 WideEltVT = LargestEltVT; 4455 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4456 // extract element index = index / element width 4457 ExtractElementIdx = DAG.getNode( 4458 ISD::SRL, DL, XLenVT, Idx, 4459 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4460 // mask bit index = index % element width 4461 ExtractBitIdx = DAG.getNode( 4462 ISD::AND, DL, XLenVT, Idx, 4463 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4464 } 4465 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4466 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4467 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4468 Vec, ExtractElementIdx); 4469 // Extract the bit from GPR. 4470 SDValue ShiftRight = 4471 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4472 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4473 DAG.getConstant(1, DL, XLenVT)); 4474 } 4475 } 4476 // Otherwise, promote to an i8 vector and extract from that. 4477 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4478 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4479 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4480 } 4481 4482 // If this is a fixed vector, we need to convert it to a scalable vector. 4483 MVT ContainerVT = VecVT; 4484 if (VecVT.isFixedLengthVector()) { 4485 ContainerVT = getContainerForFixedLengthVector(VecVT); 4486 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4487 } 4488 4489 // If the index is 0, the vector is already in the right position. 4490 if (!isNullConstant(Idx)) { 4491 // Use a VL of 1 to avoid processing more elements than we need. 4492 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4493 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4494 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4495 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4496 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4497 } 4498 4499 if (!EltVT.isInteger()) { 4500 // Floating-point extracts are handled in TableGen. 4501 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4502 DAG.getConstant(0, DL, XLenVT)); 4503 } 4504 4505 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4506 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4507 } 4508 4509 // Some RVV intrinsics may claim that they want an integer operand to be 4510 // promoted or expanded. 4511 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4512 const RISCVSubtarget &Subtarget) { 4513 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4514 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4515 "Unexpected opcode"); 4516 4517 if (!Subtarget.hasVInstructions()) 4518 return SDValue(); 4519 4520 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4521 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4522 SDLoc DL(Op); 4523 4524 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4525 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4526 if (!II || !II->hasScalarOperand()) 4527 return SDValue(); 4528 4529 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4530 assert(SplatOp < Op.getNumOperands()); 4531 4532 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4533 SDValue &ScalarOp = Operands[SplatOp]; 4534 MVT OpVT = ScalarOp.getSimpleValueType(); 4535 MVT XLenVT = Subtarget.getXLenVT(); 4536 4537 // If this isn't a scalar, or its type is XLenVT we're done. 4538 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4539 return SDValue(); 4540 4541 // Simplest case is that the operand needs to be promoted to XLenVT. 4542 if (OpVT.bitsLT(XLenVT)) { 4543 // If the operand is a constant, sign extend to increase our chances 4544 // of being able to use a .vi instruction. ANY_EXTEND would become a 4545 // a zero extend and the simm5 check in isel would fail. 4546 // FIXME: Should we ignore the upper bits in isel instead? 4547 unsigned ExtOpc = 4548 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4549 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4550 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4551 } 4552 4553 // Use the previous operand to get the vXi64 VT. The result might be a mask 4554 // VT for compares. Using the previous operand assumes that the previous 4555 // operand will never have a smaller element size than a scalar operand and 4556 // that a widening operation never uses SEW=64. 4557 // NOTE: If this fails the below assert, we can probably just find the 4558 // element count from any operand or result and use it to construct the VT. 4559 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4560 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4561 4562 // The more complex case is when the scalar is larger than XLenVT. 4563 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4564 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4565 4566 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4567 // instruction to sign-extend since SEW>XLEN. 4568 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4569 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4570 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4571 } 4572 4573 switch (IntNo) { 4574 case Intrinsic::riscv_vslide1up: 4575 case Intrinsic::riscv_vslide1down: 4576 case Intrinsic::riscv_vslide1up_mask: 4577 case Intrinsic::riscv_vslide1down_mask: { 4578 // We need to special case these when the scalar is larger than XLen. 4579 unsigned NumOps = Op.getNumOperands(); 4580 bool IsMasked = NumOps == 7; 4581 4582 // Convert the vector source to the equivalent nxvXi32 vector. 4583 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4584 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4585 4586 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4587 DAG.getConstant(0, DL, XLenVT)); 4588 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4589 DAG.getConstant(1, DL, XLenVT)); 4590 4591 // Double the VL since we halved SEW. 4592 SDValue AVL = getVLOperand(Op); 4593 SDValue I32VL; 4594 4595 // Optimize for constant AVL 4596 if (isa<ConstantSDNode>(AVL)) { 4597 unsigned EltSize = VT.getScalarSizeInBits(); 4598 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4599 4600 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4601 unsigned MaxVLMAX = 4602 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4603 4604 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4605 unsigned MinVLMAX = 4606 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4607 4608 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4609 if (AVLInt <= MinVLMAX) { 4610 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4611 } else if (AVLInt >= 2 * MaxVLMAX) { 4612 // Just set vl to VLMAX in this situation 4613 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4614 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4615 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4616 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4617 SDValue SETVLMAX = DAG.getTargetConstant( 4618 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4619 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4620 LMUL); 4621 } else { 4622 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4623 // is related to the hardware implementation. 4624 // So let the following code handle 4625 } 4626 } 4627 if (!I32VL) { 4628 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4629 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4630 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4631 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4632 SDValue SETVL = 4633 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4634 // Using vsetvli instruction to get actually used length which related to 4635 // the hardware implementation 4636 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4637 SEW, LMUL); 4638 I32VL = 4639 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4640 } 4641 4642 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4643 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL); 4644 4645 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4646 // instructions. 4647 SDValue Passthru; 4648 if (IsMasked) 4649 Passthru = DAG.getUNDEF(I32VT); 4650 else 4651 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4652 4653 if (IntNo == Intrinsic::riscv_vslide1up || 4654 IntNo == Intrinsic::riscv_vslide1up_mask) { 4655 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4656 ScalarHi, I32Mask, I32VL); 4657 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4658 ScalarLo, I32Mask, I32VL); 4659 } else { 4660 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4661 ScalarLo, I32Mask, I32VL); 4662 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4663 ScalarHi, I32Mask, I32VL); 4664 } 4665 4666 // Convert back to nxvXi64. 4667 Vec = DAG.getBitcast(VT, Vec); 4668 4669 if (!IsMasked) 4670 return Vec; 4671 // Apply mask after the operation. 4672 SDValue Mask = Operands[NumOps - 3]; 4673 SDValue MaskedOff = Operands[1]; 4674 // Assume Policy operand is the last operand. 4675 uint64_t Policy = 4676 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4677 // We don't need to select maskedoff if it's undef. 4678 if (MaskedOff.isUndef()) 4679 return Vec; 4680 // TAMU 4681 if (Policy == RISCVII::TAIL_AGNOSTIC) 4682 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4683 AVL); 4684 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4685 // It's fine because vmerge does not care mask policy. 4686 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4687 AVL); 4688 } 4689 } 4690 4691 // We need to convert the scalar to a splat vector. 4692 SDValue VL = getVLOperand(Op); 4693 assert(VL.getValueType() == XLenVT); 4694 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4695 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4696 } 4697 4698 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4699 SelectionDAG &DAG) const { 4700 unsigned IntNo = Op.getConstantOperandVal(0); 4701 SDLoc DL(Op); 4702 MVT XLenVT = Subtarget.getXLenVT(); 4703 4704 switch (IntNo) { 4705 default: 4706 break; // Don't custom lower most intrinsics. 4707 case Intrinsic::thread_pointer: { 4708 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4709 return DAG.getRegister(RISCV::X4, PtrVT); 4710 } 4711 case Intrinsic::riscv_orc_b: 4712 case Intrinsic::riscv_brev8: { 4713 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4714 unsigned Opc = 4715 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4716 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4717 DAG.getConstant(7, DL, XLenVT)); 4718 } 4719 case Intrinsic::riscv_grev: 4720 case Intrinsic::riscv_gorc: { 4721 unsigned Opc = 4722 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4723 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4724 } 4725 case Intrinsic::riscv_zip: 4726 case Intrinsic::riscv_unzip: { 4727 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4728 // For i32 the immediate is 15. For i64 the immediate is 31. 4729 unsigned Opc = 4730 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4731 unsigned BitWidth = Op.getValueSizeInBits(); 4732 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4733 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4734 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4735 } 4736 case Intrinsic::riscv_shfl: 4737 case Intrinsic::riscv_unshfl: { 4738 unsigned Opc = 4739 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4740 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4741 } 4742 case Intrinsic::riscv_bcompress: 4743 case Intrinsic::riscv_bdecompress: { 4744 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4745 : RISCVISD::BDECOMPRESS; 4746 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4747 } 4748 case Intrinsic::riscv_bfp: 4749 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4750 Op.getOperand(2)); 4751 case Intrinsic::riscv_fsl: 4752 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4753 Op.getOperand(2), Op.getOperand(3)); 4754 case Intrinsic::riscv_fsr: 4755 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4756 Op.getOperand(2), Op.getOperand(3)); 4757 case Intrinsic::riscv_vmv_x_s: 4758 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4759 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4760 Op.getOperand(1)); 4761 case Intrinsic::riscv_vmv_v_x: 4762 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4763 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4764 Subtarget); 4765 case Intrinsic::riscv_vfmv_v_f: 4766 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4767 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4768 case Intrinsic::riscv_vmv_s_x: { 4769 SDValue Scalar = Op.getOperand(2); 4770 4771 if (Scalar.getValueType().bitsLE(XLenVT)) { 4772 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4773 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4774 Op.getOperand(1), Scalar, Op.getOperand(3)); 4775 } 4776 4777 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4778 4779 // This is an i64 value that lives in two scalar registers. We have to 4780 // insert this in a convoluted way. First we build vXi64 splat containing 4781 // the two values that we assemble using some bit math. Next we'll use 4782 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4783 // to merge element 0 from our splat into the source vector. 4784 // FIXME: This is probably not the best way to do this, but it is 4785 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4786 // point. 4787 // sw lo, (a0) 4788 // sw hi, 4(a0) 4789 // vlse vX, (a0) 4790 // 4791 // vid.v vVid 4792 // vmseq.vx mMask, vVid, 0 4793 // vmerge.vvm vDest, vSrc, vVal, mMask 4794 MVT VT = Op.getSimpleValueType(); 4795 SDValue Vec = Op.getOperand(1); 4796 SDValue VL = getVLOperand(Op); 4797 4798 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4799 if (Op.getOperand(1).isUndef()) 4800 return SplattedVal; 4801 SDValue SplattedIdx = 4802 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4803 DAG.getConstant(0, DL, MVT::i32), VL); 4804 4805 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4806 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4807 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4808 SDValue SelectCond = 4809 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4810 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4811 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4812 Vec, VL); 4813 } 4814 } 4815 4816 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4817 } 4818 4819 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4820 SelectionDAG &DAG) const { 4821 unsigned IntNo = Op.getConstantOperandVal(1); 4822 switch (IntNo) { 4823 default: 4824 break; 4825 case Intrinsic::riscv_masked_strided_load: { 4826 SDLoc DL(Op); 4827 MVT XLenVT = Subtarget.getXLenVT(); 4828 4829 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4830 // the selection of the masked intrinsics doesn't do this for us. 4831 SDValue Mask = Op.getOperand(5); 4832 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4833 4834 MVT VT = Op->getSimpleValueType(0); 4835 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4836 4837 SDValue PassThru = Op.getOperand(2); 4838 if (!IsUnmasked) { 4839 MVT MaskVT = 4840 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4841 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4842 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4843 } 4844 4845 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4846 4847 SDValue IntID = DAG.getTargetConstant( 4848 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4849 XLenVT); 4850 4851 auto *Load = cast<MemIntrinsicSDNode>(Op); 4852 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4853 if (IsUnmasked) 4854 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4855 else 4856 Ops.push_back(PassThru); 4857 Ops.push_back(Op.getOperand(3)); // Ptr 4858 Ops.push_back(Op.getOperand(4)); // Stride 4859 if (!IsUnmasked) 4860 Ops.push_back(Mask); 4861 Ops.push_back(VL); 4862 if (!IsUnmasked) { 4863 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4864 Ops.push_back(Policy); 4865 } 4866 4867 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4868 SDValue Result = 4869 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4870 Load->getMemoryVT(), Load->getMemOperand()); 4871 SDValue Chain = Result.getValue(1); 4872 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4873 return DAG.getMergeValues({Result, Chain}, DL); 4874 } 4875 case Intrinsic::riscv_seg2_load: 4876 case Intrinsic::riscv_seg3_load: 4877 case Intrinsic::riscv_seg4_load: 4878 case Intrinsic::riscv_seg5_load: 4879 case Intrinsic::riscv_seg6_load: 4880 case Intrinsic::riscv_seg7_load: 4881 case Intrinsic::riscv_seg8_load: { 4882 SDLoc DL(Op); 4883 static const Intrinsic::ID VlsegInts[7] = { 4884 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4885 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4886 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4887 Intrinsic::riscv_vlseg8}; 4888 unsigned NF = Op->getNumValues() - 1; 4889 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4890 MVT XLenVT = Subtarget.getXLenVT(); 4891 MVT VT = Op->getSimpleValueType(0); 4892 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4893 4894 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4895 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4896 auto *Load = cast<MemIntrinsicSDNode>(Op); 4897 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4898 ContainerVTs.push_back(MVT::Other); 4899 SDVTList VTs = DAG.getVTList(ContainerVTs); 4900 SDValue Result = 4901 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4902 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4903 Load->getMemoryVT(), Load->getMemOperand()); 4904 SmallVector<SDValue, 9> Results; 4905 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4906 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4907 DAG, Subtarget)); 4908 Results.push_back(Result.getValue(NF)); 4909 return DAG.getMergeValues(Results, DL); 4910 } 4911 } 4912 4913 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4914 } 4915 4916 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4917 SelectionDAG &DAG) const { 4918 unsigned IntNo = Op.getConstantOperandVal(1); 4919 switch (IntNo) { 4920 default: 4921 break; 4922 case Intrinsic::riscv_masked_strided_store: { 4923 SDLoc DL(Op); 4924 MVT XLenVT = Subtarget.getXLenVT(); 4925 4926 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4927 // the selection of the masked intrinsics doesn't do this for us. 4928 SDValue Mask = Op.getOperand(5); 4929 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4930 4931 SDValue Val = Op.getOperand(2); 4932 MVT VT = Val.getSimpleValueType(); 4933 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4934 4935 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4936 if (!IsUnmasked) { 4937 MVT MaskVT = 4938 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4939 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4940 } 4941 4942 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4943 4944 SDValue IntID = DAG.getTargetConstant( 4945 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4946 XLenVT); 4947 4948 auto *Store = cast<MemIntrinsicSDNode>(Op); 4949 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4950 Ops.push_back(Val); 4951 Ops.push_back(Op.getOperand(3)); // Ptr 4952 Ops.push_back(Op.getOperand(4)); // Stride 4953 if (!IsUnmasked) 4954 Ops.push_back(Mask); 4955 Ops.push_back(VL); 4956 4957 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4958 Ops, Store->getMemoryVT(), 4959 Store->getMemOperand()); 4960 } 4961 } 4962 4963 return SDValue(); 4964 } 4965 4966 static MVT getLMUL1VT(MVT VT) { 4967 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4968 "Unexpected vector MVT"); 4969 return MVT::getScalableVectorVT( 4970 VT.getVectorElementType(), 4971 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4972 } 4973 4974 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4975 switch (ISDOpcode) { 4976 default: 4977 llvm_unreachable("Unhandled reduction"); 4978 case ISD::VECREDUCE_ADD: 4979 return RISCVISD::VECREDUCE_ADD_VL; 4980 case ISD::VECREDUCE_UMAX: 4981 return RISCVISD::VECREDUCE_UMAX_VL; 4982 case ISD::VECREDUCE_SMAX: 4983 return RISCVISD::VECREDUCE_SMAX_VL; 4984 case ISD::VECREDUCE_UMIN: 4985 return RISCVISD::VECREDUCE_UMIN_VL; 4986 case ISD::VECREDUCE_SMIN: 4987 return RISCVISD::VECREDUCE_SMIN_VL; 4988 case ISD::VECREDUCE_AND: 4989 return RISCVISD::VECREDUCE_AND_VL; 4990 case ISD::VECREDUCE_OR: 4991 return RISCVISD::VECREDUCE_OR_VL; 4992 case ISD::VECREDUCE_XOR: 4993 return RISCVISD::VECREDUCE_XOR_VL; 4994 } 4995 } 4996 4997 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4998 SelectionDAG &DAG, 4999 bool IsVP) const { 5000 SDLoc DL(Op); 5001 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5002 MVT VecVT = Vec.getSimpleValueType(); 5003 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5004 Op.getOpcode() == ISD::VECREDUCE_OR || 5005 Op.getOpcode() == ISD::VECREDUCE_XOR || 5006 Op.getOpcode() == ISD::VP_REDUCE_AND || 5007 Op.getOpcode() == ISD::VP_REDUCE_OR || 5008 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5009 "Unexpected reduction lowering"); 5010 5011 MVT XLenVT = Subtarget.getXLenVT(); 5012 assert(Op.getValueType() == XLenVT && 5013 "Expected reduction output to be legalized to XLenVT"); 5014 5015 MVT ContainerVT = VecVT; 5016 if (VecVT.isFixedLengthVector()) { 5017 ContainerVT = getContainerForFixedLengthVector(VecVT); 5018 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5019 } 5020 5021 SDValue Mask, VL; 5022 if (IsVP) { 5023 Mask = Op.getOperand(2); 5024 VL = Op.getOperand(3); 5025 } else { 5026 std::tie(Mask, VL) = 5027 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5028 } 5029 5030 unsigned BaseOpc; 5031 ISD::CondCode CC; 5032 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5033 5034 switch (Op.getOpcode()) { 5035 default: 5036 llvm_unreachable("Unhandled reduction"); 5037 case ISD::VECREDUCE_AND: 5038 case ISD::VP_REDUCE_AND: { 5039 // vcpop ~x == 0 5040 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5041 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5042 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5043 CC = ISD::SETEQ; 5044 BaseOpc = ISD::AND; 5045 break; 5046 } 5047 case ISD::VECREDUCE_OR: 5048 case ISD::VP_REDUCE_OR: 5049 // vcpop x != 0 5050 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5051 CC = ISD::SETNE; 5052 BaseOpc = ISD::OR; 5053 break; 5054 case ISD::VECREDUCE_XOR: 5055 case ISD::VP_REDUCE_XOR: { 5056 // ((vcpop x) & 1) != 0 5057 SDValue One = DAG.getConstant(1, DL, XLenVT); 5058 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5059 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5060 CC = ISD::SETNE; 5061 BaseOpc = ISD::XOR; 5062 break; 5063 } 5064 } 5065 5066 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5067 5068 if (!IsVP) 5069 return SetCC; 5070 5071 // Now include the start value in the operation. 5072 // Note that we must return the start value when no elements are operated 5073 // upon. The vcpop instructions we've emitted in each case above will return 5074 // 0 for an inactive vector, and so we've already received the neutral value: 5075 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5076 // can simply include the start value. 5077 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5078 } 5079 5080 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5081 SelectionDAG &DAG) const { 5082 SDLoc DL(Op); 5083 SDValue Vec = Op.getOperand(0); 5084 EVT VecEVT = Vec.getValueType(); 5085 5086 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5087 5088 // Due to ordering in legalize types we may have a vector type that needs to 5089 // be split. Do that manually so we can get down to a legal type. 5090 while (getTypeAction(*DAG.getContext(), VecEVT) == 5091 TargetLowering::TypeSplitVector) { 5092 SDValue Lo, Hi; 5093 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5094 VecEVT = Lo.getValueType(); 5095 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5096 } 5097 5098 // TODO: The type may need to be widened rather than split. Or widened before 5099 // it can be split. 5100 if (!isTypeLegal(VecEVT)) 5101 return SDValue(); 5102 5103 MVT VecVT = VecEVT.getSimpleVT(); 5104 MVT VecEltVT = VecVT.getVectorElementType(); 5105 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5106 5107 MVT ContainerVT = VecVT; 5108 if (VecVT.isFixedLengthVector()) { 5109 ContainerVT = getContainerForFixedLengthVector(VecVT); 5110 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5111 } 5112 5113 MVT M1VT = getLMUL1VT(ContainerVT); 5114 MVT XLenVT = Subtarget.getXLenVT(); 5115 5116 SDValue Mask, VL; 5117 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5118 5119 SDValue NeutralElem = 5120 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5121 SDValue IdentitySplat = 5122 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5123 M1VT, DL, DAG, Subtarget); 5124 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5125 IdentitySplat, Mask, VL); 5126 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5127 DAG.getConstant(0, DL, XLenVT)); 5128 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5129 } 5130 5131 // Given a reduction op, this function returns the matching reduction opcode, 5132 // the vector SDValue and the scalar SDValue required to lower this to a 5133 // RISCVISD node. 5134 static std::tuple<unsigned, SDValue, SDValue> 5135 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5136 SDLoc DL(Op); 5137 auto Flags = Op->getFlags(); 5138 unsigned Opcode = Op.getOpcode(); 5139 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5140 switch (Opcode) { 5141 default: 5142 llvm_unreachable("Unhandled reduction"); 5143 case ISD::VECREDUCE_FADD: { 5144 // Use positive zero if we can. It is cheaper to materialize. 5145 SDValue Zero = 5146 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5147 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5148 } 5149 case ISD::VECREDUCE_SEQ_FADD: 5150 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5151 Op.getOperand(0)); 5152 case ISD::VECREDUCE_FMIN: 5153 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5154 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5155 case ISD::VECREDUCE_FMAX: 5156 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5157 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5158 } 5159 } 5160 5161 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5162 SelectionDAG &DAG) const { 5163 SDLoc DL(Op); 5164 MVT VecEltVT = Op.getSimpleValueType(); 5165 5166 unsigned RVVOpcode; 5167 SDValue VectorVal, ScalarVal; 5168 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5169 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5170 MVT VecVT = VectorVal.getSimpleValueType(); 5171 5172 MVT ContainerVT = VecVT; 5173 if (VecVT.isFixedLengthVector()) { 5174 ContainerVT = getContainerForFixedLengthVector(VecVT); 5175 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5176 } 5177 5178 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5179 MVT XLenVT = Subtarget.getXLenVT(); 5180 5181 SDValue Mask, VL; 5182 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5183 5184 SDValue ScalarSplat = 5185 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5186 M1VT, DL, DAG, Subtarget); 5187 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5188 VectorVal, ScalarSplat, Mask, VL); 5189 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5190 DAG.getConstant(0, DL, XLenVT)); 5191 } 5192 5193 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5194 switch (ISDOpcode) { 5195 default: 5196 llvm_unreachable("Unhandled reduction"); 5197 case ISD::VP_REDUCE_ADD: 5198 return RISCVISD::VECREDUCE_ADD_VL; 5199 case ISD::VP_REDUCE_UMAX: 5200 return RISCVISD::VECREDUCE_UMAX_VL; 5201 case ISD::VP_REDUCE_SMAX: 5202 return RISCVISD::VECREDUCE_SMAX_VL; 5203 case ISD::VP_REDUCE_UMIN: 5204 return RISCVISD::VECREDUCE_UMIN_VL; 5205 case ISD::VP_REDUCE_SMIN: 5206 return RISCVISD::VECREDUCE_SMIN_VL; 5207 case ISD::VP_REDUCE_AND: 5208 return RISCVISD::VECREDUCE_AND_VL; 5209 case ISD::VP_REDUCE_OR: 5210 return RISCVISD::VECREDUCE_OR_VL; 5211 case ISD::VP_REDUCE_XOR: 5212 return RISCVISD::VECREDUCE_XOR_VL; 5213 case ISD::VP_REDUCE_FADD: 5214 return RISCVISD::VECREDUCE_FADD_VL; 5215 case ISD::VP_REDUCE_SEQ_FADD: 5216 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5217 case ISD::VP_REDUCE_FMAX: 5218 return RISCVISD::VECREDUCE_FMAX_VL; 5219 case ISD::VP_REDUCE_FMIN: 5220 return RISCVISD::VECREDUCE_FMIN_VL; 5221 } 5222 } 5223 5224 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5225 SelectionDAG &DAG) const { 5226 SDLoc DL(Op); 5227 SDValue Vec = Op.getOperand(1); 5228 EVT VecEVT = Vec.getValueType(); 5229 5230 // TODO: The type may need to be widened rather than split. Or widened before 5231 // it can be split. 5232 if (!isTypeLegal(VecEVT)) 5233 return SDValue(); 5234 5235 MVT VecVT = VecEVT.getSimpleVT(); 5236 MVT VecEltVT = VecVT.getVectorElementType(); 5237 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5238 5239 MVT ContainerVT = VecVT; 5240 if (VecVT.isFixedLengthVector()) { 5241 ContainerVT = getContainerForFixedLengthVector(VecVT); 5242 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5243 } 5244 5245 SDValue VL = Op.getOperand(3); 5246 SDValue Mask = Op.getOperand(2); 5247 5248 MVT M1VT = getLMUL1VT(ContainerVT); 5249 MVT XLenVT = Subtarget.getXLenVT(); 5250 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5251 5252 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5253 DAG.getConstant(1, DL, XLenVT), M1VT, 5254 DL, DAG, Subtarget); 5255 SDValue Reduction = 5256 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5257 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5258 DAG.getConstant(0, DL, XLenVT)); 5259 if (!VecVT.isInteger()) 5260 return Elt0; 5261 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5262 } 5263 5264 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5265 SelectionDAG &DAG) const { 5266 SDValue Vec = Op.getOperand(0); 5267 SDValue SubVec = Op.getOperand(1); 5268 MVT VecVT = Vec.getSimpleValueType(); 5269 MVT SubVecVT = SubVec.getSimpleValueType(); 5270 5271 SDLoc DL(Op); 5272 MVT XLenVT = Subtarget.getXLenVT(); 5273 unsigned OrigIdx = Op.getConstantOperandVal(2); 5274 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5275 5276 // We don't have the ability to slide mask vectors up indexed by their i1 5277 // elements; the smallest we can do is i8. Often we are able to bitcast to 5278 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5279 // into a scalable one, we might not necessarily have enough scalable 5280 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5281 if (SubVecVT.getVectorElementType() == MVT::i1 && 5282 (OrigIdx != 0 || !Vec.isUndef())) { 5283 if (VecVT.getVectorMinNumElements() >= 8 && 5284 SubVecVT.getVectorMinNumElements() >= 8) { 5285 assert(OrigIdx % 8 == 0 && "Invalid index"); 5286 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5287 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5288 "Unexpected mask vector lowering"); 5289 OrigIdx /= 8; 5290 SubVecVT = 5291 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5292 SubVecVT.isScalableVector()); 5293 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5294 VecVT.isScalableVector()); 5295 Vec = DAG.getBitcast(VecVT, Vec); 5296 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5297 } else { 5298 // We can't slide this mask vector up indexed by its i1 elements. 5299 // This poses a problem when we wish to insert a scalable vector which 5300 // can't be re-expressed as a larger type. Just choose the slow path and 5301 // extend to a larger type, then truncate back down. 5302 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5303 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5304 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5305 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5306 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5307 Op.getOperand(2)); 5308 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5309 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5310 } 5311 } 5312 5313 // If the subvector vector is a fixed-length type, we cannot use subregister 5314 // manipulation to simplify the codegen; we don't know which register of a 5315 // LMUL group contains the specific subvector as we only know the minimum 5316 // register size. Therefore we must slide the vector group up the full 5317 // amount. 5318 if (SubVecVT.isFixedLengthVector()) { 5319 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5320 return Op; 5321 MVT ContainerVT = VecVT; 5322 if (VecVT.isFixedLengthVector()) { 5323 ContainerVT = getContainerForFixedLengthVector(VecVT); 5324 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5325 } 5326 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5327 DAG.getUNDEF(ContainerVT), SubVec, 5328 DAG.getConstant(0, DL, XLenVT)); 5329 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5330 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5331 return DAG.getBitcast(Op.getValueType(), SubVec); 5332 } 5333 SDValue Mask = 5334 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5335 // Set the vector length to only the number of elements we care about. Note 5336 // that for slideup this includes the offset. 5337 SDValue VL = 5338 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5339 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5340 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5341 SubVec, SlideupAmt, Mask, VL); 5342 if (VecVT.isFixedLengthVector()) 5343 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5344 return DAG.getBitcast(Op.getValueType(), Slideup); 5345 } 5346 5347 unsigned SubRegIdx, RemIdx; 5348 std::tie(SubRegIdx, RemIdx) = 5349 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5350 VecVT, SubVecVT, OrigIdx, TRI); 5351 5352 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5353 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5354 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5355 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5356 5357 // 1. If the Idx has been completely eliminated and this subvector's size is 5358 // a vector register or a multiple thereof, or the surrounding elements are 5359 // undef, then this is a subvector insert which naturally aligns to a vector 5360 // register. These can easily be handled using subregister manipulation. 5361 // 2. If the subvector is smaller than a vector register, then the insertion 5362 // must preserve the undisturbed elements of the register. We do this by 5363 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5364 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5365 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5366 // LMUL=1 type back into the larger vector (resolving to another subregister 5367 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5368 // to avoid allocating a large register group to hold our subvector. 5369 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5370 return Op; 5371 5372 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5373 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5374 // (in our case undisturbed). This means we can set up a subvector insertion 5375 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5376 // size of the subvector. 5377 MVT InterSubVT = VecVT; 5378 SDValue AlignedExtract = Vec; 5379 unsigned AlignedIdx = OrigIdx - RemIdx; 5380 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5381 InterSubVT = getLMUL1VT(VecVT); 5382 // Extract a subvector equal to the nearest full vector register type. This 5383 // should resolve to a EXTRACT_SUBREG instruction. 5384 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5385 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5386 } 5387 5388 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5389 // For scalable vectors this must be further multiplied by vscale. 5390 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5391 5392 SDValue Mask, VL; 5393 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5394 5395 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5396 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5397 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5398 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5399 5400 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5401 DAG.getUNDEF(InterSubVT), SubVec, 5402 DAG.getConstant(0, DL, XLenVT)); 5403 5404 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5405 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5406 5407 // If required, insert this subvector back into the correct vector register. 5408 // This should resolve to an INSERT_SUBREG instruction. 5409 if (VecVT.bitsGT(InterSubVT)) 5410 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5411 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5412 5413 // We might have bitcast from a mask type: cast back to the original type if 5414 // required. 5415 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5416 } 5417 5418 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5419 SelectionDAG &DAG) const { 5420 SDValue Vec = Op.getOperand(0); 5421 MVT SubVecVT = Op.getSimpleValueType(); 5422 MVT VecVT = Vec.getSimpleValueType(); 5423 5424 SDLoc DL(Op); 5425 MVT XLenVT = Subtarget.getXLenVT(); 5426 unsigned OrigIdx = Op.getConstantOperandVal(1); 5427 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5428 5429 // We don't have the ability to slide mask vectors down indexed by their i1 5430 // elements; the smallest we can do is i8. Often we are able to bitcast to 5431 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5432 // from a scalable one, we might not necessarily have enough scalable 5433 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5434 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5435 if (VecVT.getVectorMinNumElements() >= 8 && 5436 SubVecVT.getVectorMinNumElements() >= 8) { 5437 assert(OrigIdx % 8 == 0 && "Invalid index"); 5438 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5439 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5440 "Unexpected mask vector lowering"); 5441 OrigIdx /= 8; 5442 SubVecVT = 5443 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5444 SubVecVT.isScalableVector()); 5445 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5446 VecVT.isScalableVector()); 5447 Vec = DAG.getBitcast(VecVT, Vec); 5448 } else { 5449 // We can't slide this mask vector down, indexed by its i1 elements. 5450 // This poses a problem when we wish to extract a scalable vector which 5451 // can't be re-expressed as a larger type. Just choose the slow path and 5452 // extend to a larger type, then truncate back down. 5453 // TODO: We could probably improve this when extracting certain fixed 5454 // from fixed, where we can extract as i8 and shift the correct element 5455 // right to reach the desired subvector? 5456 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5457 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5458 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5459 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5460 Op.getOperand(1)); 5461 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5462 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5463 } 5464 } 5465 5466 // If the subvector vector is a fixed-length type, we cannot use subregister 5467 // manipulation to simplify the codegen; we don't know which register of a 5468 // LMUL group contains the specific subvector as we only know the minimum 5469 // register size. Therefore we must slide the vector group down the full 5470 // amount. 5471 if (SubVecVT.isFixedLengthVector()) { 5472 // With an index of 0 this is a cast-like subvector, which can be performed 5473 // with subregister operations. 5474 if (OrigIdx == 0) 5475 return Op; 5476 MVT ContainerVT = VecVT; 5477 if (VecVT.isFixedLengthVector()) { 5478 ContainerVT = getContainerForFixedLengthVector(VecVT); 5479 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5480 } 5481 SDValue Mask = 5482 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5483 // Set the vector length to only the number of elements we care about. This 5484 // avoids sliding down elements we're going to discard straight away. 5485 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5486 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5487 SDValue Slidedown = 5488 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5489 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5490 // Now we can use a cast-like subvector extract to get the result. 5491 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5492 DAG.getConstant(0, DL, XLenVT)); 5493 return DAG.getBitcast(Op.getValueType(), Slidedown); 5494 } 5495 5496 unsigned SubRegIdx, RemIdx; 5497 std::tie(SubRegIdx, RemIdx) = 5498 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5499 VecVT, SubVecVT, OrigIdx, TRI); 5500 5501 // If the Idx has been completely eliminated then this is a subvector extract 5502 // which naturally aligns to a vector register. These can easily be handled 5503 // using subregister manipulation. 5504 if (RemIdx == 0) 5505 return Op; 5506 5507 // Else we must shift our vector register directly to extract the subvector. 5508 // Do this using VSLIDEDOWN. 5509 5510 // If the vector type is an LMUL-group type, extract a subvector equal to the 5511 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5512 // instruction. 5513 MVT InterSubVT = VecVT; 5514 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5515 InterSubVT = getLMUL1VT(VecVT); 5516 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5517 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5518 } 5519 5520 // Slide this vector register down by the desired number of elements in order 5521 // to place the desired subvector starting at element 0. 5522 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5523 // For scalable vectors this must be further multiplied by vscale. 5524 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5525 5526 SDValue Mask, VL; 5527 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5528 SDValue Slidedown = 5529 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5530 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5531 5532 // Now the vector is in the right position, extract our final subvector. This 5533 // should resolve to a COPY. 5534 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5535 DAG.getConstant(0, DL, XLenVT)); 5536 5537 // We might have bitcast from a mask type: cast back to the original type if 5538 // required. 5539 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5540 } 5541 5542 // Lower step_vector to the vid instruction. Any non-identity step value must 5543 // be accounted for my manual expansion. 5544 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5545 SelectionDAG &DAG) const { 5546 SDLoc DL(Op); 5547 MVT VT = Op.getSimpleValueType(); 5548 MVT XLenVT = Subtarget.getXLenVT(); 5549 SDValue Mask, VL; 5550 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5551 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5552 uint64_t StepValImm = Op.getConstantOperandVal(0); 5553 if (StepValImm != 1) { 5554 if (isPowerOf2_64(StepValImm)) { 5555 SDValue StepVal = 5556 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5557 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5558 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5559 } else { 5560 SDValue StepVal = lowerScalarSplat( 5561 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5562 VL, VT, DL, DAG, Subtarget); 5563 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5564 } 5565 } 5566 return StepVec; 5567 } 5568 5569 // Implement vector_reverse using vrgather.vv with indices determined by 5570 // subtracting the id of each element from (VLMAX-1). This will convert 5571 // the indices like so: 5572 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5573 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5574 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5575 SelectionDAG &DAG) const { 5576 SDLoc DL(Op); 5577 MVT VecVT = Op.getSimpleValueType(); 5578 unsigned EltSize = VecVT.getScalarSizeInBits(); 5579 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5580 5581 unsigned MaxVLMAX = 0; 5582 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5583 if (VectorBitsMax != 0) 5584 MaxVLMAX = 5585 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5586 5587 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5588 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5589 5590 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5591 // to use vrgatherei16.vv. 5592 // TODO: It's also possible to use vrgatherei16.vv for other types to 5593 // decrease register width for the index calculation. 5594 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5595 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5596 // Reverse each half, then reassemble them in reverse order. 5597 // NOTE: It's also possible that after splitting that VLMAX no longer 5598 // requires vrgatherei16.vv. 5599 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5600 SDValue Lo, Hi; 5601 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5602 EVT LoVT, HiVT; 5603 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5604 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5605 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5606 // Reassemble the low and high pieces reversed. 5607 // FIXME: This is a CONCAT_VECTORS. 5608 SDValue Res = 5609 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5610 DAG.getIntPtrConstant(0, DL)); 5611 return DAG.getNode( 5612 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5613 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5614 } 5615 5616 // Just promote the int type to i16 which will double the LMUL. 5617 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5618 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5619 } 5620 5621 MVT XLenVT = Subtarget.getXLenVT(); 5622 SDValue Mask, VL; 5623 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5624 5625 // Calculate VLMAX-1 for the desired SEW. 5626 unsigned MinElts = VecVT.getVectorMinNumElements(); 5627 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5628 DAG.getConstant(MinElts, DL, XLenVT)); 5629 SDValue VLMinus1 = 5630 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5631 5632 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5633 bool IsRV32E64 = 5634 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5635 SDValue SplatVL; 5636 if (!IsRV32E64) 5637 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5638 else 5639 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5640 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5641 5642 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5643 SDValue Indices = 5644 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5645 5646 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5647 } 5648 5649 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5650 SelectionDAG &DAG) const { 5651 SDLoc DL(Op); 5652 SDValue V1 = Op.getOperand(0); 5653 SDValue V2 = Op.getOperand(1); 5654 MVT XLenVT = Subtarget.getXLenVT(); 5655 MVT VecVT = Op.getSimpleValueType(); 5656 5657 unsigned MinElts = VecVT.getVectorMinNumElements(); 5658 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5659 DAG.getConstant(MinElts, DL, XLenVT)); 5660 5661 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5662 SDValue DownOffset, UpOffset; 5663 if (ImmValue >= 0) { 5664 // The operand is a TargetConstant, we need to rebuild it as a regular 5665 // constant. 5666 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5667 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5668 } else { 5669 // The operand is a TargetConstant, we need to rebuild it as a regular 5670 // constant rather than negating the original operand. 5671 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5672 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5673 } 5674 5675 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5676 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5677 5678 SDValue SlideDown = 5679 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5680 DownOffset, TrueMask, UpOffset); 5681 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5682 TrueMask, 5683 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5684 } 5685 5686 SDValue 5687 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5688 SelectionDAG &DAG) const { 5689 SDLoc DL(Op); 5690 auto *Load = cast<LoadSDNode>(Op); 5691 5692 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5693 Load->getMemoryVT(), 5694 *Load->getMemOperand()) && 5695 "Expecting a correctly-aligned load"); 5696 5697 MVT VT = Op.getSimpleValueType(); 5698 MVT XLenVT = Subtarget.getXLenVT(); 5699 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5700 5701 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5702 5703 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5704 SDValue IntID = DAG.getTargetConstant( 5705 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5706 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5707 if (!IsMaskOp) 5708 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5709 Ops.push_back(Load->getBasePtr()); 5710 Ops.push_back(VL); 5711 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5712 SDValue NewLoad = 5713 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5714 Load->getMemoryVT(), Load->getMemOperand()); 5715 5716 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5717 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5718 } 5719 5720 SDValue 5721 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5722 SelectionDAG &DAG) const { 5723 SDLoc DL(Op); 5724 auto *Store = cast<StoreSDNode>(Op); 5725 5726 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5727 Store->getMemoryVT(), 5728 *Store->getMemOperand()) && 5729 "Expecting a correctly-aligned store"); 5730 5731 SDValue StoreVal = Store->getValue(); 5732 MVT VT = StoreVal.getSimpleValueType(); 5733 MVT XLenVT = Subtarget.getXLenVT(); 5734 5735 // If the size less than a byte, we need to pad with zeros to make a byte. 5736 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5737 VT = MVT::v8i1; 5738 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5739 DAG.getConstant(0, DL, VT), StoreVal, 5740 DAG.getIntPtrConstant(0, DL)); 5741 } 5742 5743 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5744 5745 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5746 5747 SDValue NewValue = 5748 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5749 5750 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5751 SDValue IntID = DAG.getTargetConstant( 5752 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5753 return DAG.getMemIntrinsicNode( 5754 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5755 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5756 Store->getMemoryVT(), Store->getMemOperand()); 5757 } 5758 5759 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5760 SelectionDAG &DAG) const { 5761 SDLoc DL(Op); 5762 MVT VT = Op.getSimpleValueType(); 5763 5764 const auto *MemSD = cast<MemSDNode>(Op); 5765 EVT MemVT = MemSD->getMemoryVT(); 5766 MachineMemOperand *MMO = MemSD->getMemOperand(); 5767 SDValue Chain = MemSD->getChain(); 5768 SDValue BasePtr = MemSD->getBasePtr(); 5769 5770 SDValue Mask, PassThru, VL; 5771 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5772 Mask = VPLoad->getMask(); 5773 PassThru = DAG.getUNDEF(VT); 5774 VL = VPLoad->getVectorLength(); 5775 } else { 5776 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5777 Mask = MLoad->getMask(); 5778 PassThru = MLoad->getPassThru(); 5779 } 5780 5781 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5782 5783 MVT XLenVT = Subtarget.getXLenVT(); 5784 5785 MVT ContainerVT = VT; 5786 if (VT.isFixedLengthVector()) { 5787 ContainerVT = getContainerForFixedLengthVector(VT); 5788 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5789 if (!IsUnmasked) { 5790 MVT MaskVT = 5791 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5792 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5793 } 5794 } 5795 5796 if (!VL) 5797 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5798 5799 unsigned IntID = 5800 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5801 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5802 if (IsUnmasked) 5803 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5804 else 5805 Ops.push_back(PassThru); 5806 Ops.push_back(BasePtr); 5807 if (!IsUnmasked) 5808 Ops.push_back(Mask); 5809 Ops.push_back(VL); 5810 if (!IsUnmasked) 5811 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5812 5813 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5814 5815 SDValue Result = 5816 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5817 Chain = Result.getValue(1); 5818 5819 if (VT.isFixedLengthVector()) 5820 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5821 5822 return DAG.getMergeValues({Result, Chain}, DL); 5823 } 5824 5825 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5826 SelectionDAG &DAG) const { 5827 SDLoc DL(Op); 5828 5829 const auto *MemSD = cast<MemSDNode>(Op); 5830 EVT MemVT = MemSD->getMemoryVT(); 5831 MachineMemOperand *MMO = MemSD->getMemOperand(); 5832 SDValue Chain = MemSD->getChain(); 5833 SDValue BasePtr = MemSD->getBasePtr(); 5834 SDValue Val, Mask, VL; 5835 5836 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5837 Val = VPStore->getValue(); 5838 Mask = VPStore->getMask(); 5839 VL = VPStore->getVectorLength(); 5840 } else { 5841 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5842 Val = MStore->getValue(); 5843 Mask = MStore->getMask(); 5844 } 5845 5846 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5847 5848 MVT VT = Val.getSimpleValueType(); 5849 MVT XLenVT = Subtarget.getXLenVT(); 5850 5851 MVT ContainerVT = VT; 5852 if (VT.isFixedLengthVector()) { 5853 ContainerVT = getContainerForFixedLengthVector(VT); 5854 5855 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5856 if (!IsUnmasked) { 5857 MVT MaskVT = 5858 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5859 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5860 } 5861 } 5862 5863 if (!VL) 5864 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5865 5866 unsigned IntID = 5867 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5868 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5869 Ops.push_back(Val); 5870 Ops.push_back(BasePtr); 5871 if (!IsUnmasked) 5872 Ops.push_back(Mask); 5873 Ops.push_back(VL); 5874 5875 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5876 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5877 } 5878 5879 SDValue 5880 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5881 SelectionDAG &DAG) const { 5882 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5883 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5884 5885 MVT VT = Op.getSimpleValueType(); 5886 5887 SDValue Op1 = 5888 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5889 SDValue Op2 = 5890 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5891 5892 SDLoc DL(Op); 5893 SDValue VL = 5894 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5895 5896 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5897 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5898 5899 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5900 Op.getOperand(2), Mask, VL); 5901 5902 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5903 } 5904 5905 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5906 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5907 MVT VT = Op.getSimpleValueType(); 5908 5909 if (VT.getVectorElementType() == MVT::i1) 5910 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5911 5912 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5913 } 5914 5915 SDValue 5916 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5917 SelectionDAG &DAG) const { 5918 unsigned Opc; 5919 switch (Op.getOpcode()) { 5920 default: llvm_unreachable("Unexpected opcode!"); 5921 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5922 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5923 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5924 } 5925 5926 return lowerToScalableOp(Op, DAG, Opc); 5927 } 5928 5929 // Lower vector ABS to smax(X, sub(0, X)). 5930 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5931 SDLoc DL(Op); 5932 MVT VT = Op.getSimpleValueType(); 5933 SDValue X = Op.getOperand(0); 5934 5935 assert(VT.isFixedLengthVector() && "Unexpected type"); 5936 5937 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5938 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5939 5940 SDValue Mask, VL; 5941 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5942 5943 SDValue SplatZero = DAG.getNode( 5944 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5945 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5946 SDValue NegX = 5947 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5948 SDValue Max = 5949 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5950 5951 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5952 } 5953 5954 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5955 SDValue Op, SelectionDAG &DAG) const { 5956 SDLoc DL(Op); 5957 MVT VT = Op.getSimpleValueType(); 5958 SDValue Mag = Op.getOperand(0); 5959 SDValue Sign = Op.getOperand(1); 5960 assert(Mag.getValueType() == Sign.getValueType() && 5961 "Can only handle COPYSIGN with matching types."); 5962 5963 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5964 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5965 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5966 5967 SDValue Mask, VL; 5968 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5969 5970 SDValue CopySign = 5971 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5972 5973 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5974 } 5975 5976 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5977 SDValue Op, SelectionDAG &DAG) const { 5978 MVT VT = Op.getSimpleValueType(); 5979 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5980 5981 MVT I1ContainerVT = 5982 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5983 5984 SDValue CC = 5985 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5986 SDValue Op1 = 5987 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5988 SDValue Op2 = 5989 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5990 5991 SDLoc DL(Op); 5992 SDValue Mask, VL; 5993 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5994 5995 SDValue Select = 5996 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5997 5998 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5999 } 6000 6001 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6002 unsigned NewOpc, 6003 bool HasMask) const { 6004 MVT VT = Op.getSimpleValueType(); 6005 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6006 6007 // Create list of operands by converting existing ones to scalable types. 6008 SmallVector<SDValue, 6> Ops; 6009 for (const SDValue &V : Op->op_values()) { 6010 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6011 6012 // Pass through non-vector operands. 6013 if (!V.getValueType().isVector()) { 6014 Ops.push_back(V); 6015 continue; 6016 } 6017 6018 // "cast" fixed length vector to a scalable vector. 6019 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6020 "Only fixed length vectors are supported!"); 6021 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6022 } 6023 6024 SDLoc DL(Op); 6025 SDValue Mask, VL; 6026 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6027 if (HasMask) 6028 Ops.push_back(Mask); 6029 Ops.push_back(VL); 6030 6031 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6032 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6033 } 6034 6035 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6036 // * Operands of each node are assumed to be in the same order. 6037 // * The EVL operand is promoted from i32 to i64 on RV64. 6038 // * Fixed-length vectors are converted to their scalable-vector container 6039 // types. 6040 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6041 unsigned RISCVISDOpc) const { 6042 SDLoc DL(Op); 6043 MVT VT = Op.getSimpleValueType(); 6044 SmallVector<SDValue, 4> Ops; 6045 6046 for (const auto &OpIdx : enumerate(Op->ops())) { 6047 SDValue V = OpIdx.value(); 6048 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6049 // Pass through operands which aren't fixed-length vectors. 6050 if (!V.getValueType().isFixedLengthVector()) { 6051 Ops.push_back(V); 6052 continue; 6053 } 6054 // "cast" fixed length vector to a scalable vector. 6055 MVT OpVT = V.getSimpleValueType(); 6056 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6057 assert(useRVVForFixedLengthVectorVT(OpVT) && 6058 "Only fixed length vectors are supported!"); 6059 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6060 } 6061 6062 if (!VT.isFixedLengthVector()) 6063 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6064 6065 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6066 6067 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6068 6069 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6070 } 6071 6072 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6073 SelectionDAG &DAG) const { 6074 SDLoc DL(Op); 6075 MVT VT = Op.getSimpleValueType(); 6076 6077 SDValue Src = Op.getOperand(0); 6078 // NOTE: Mask is dropped. 6079 SDValue VL = Op.getOperand(2); 6080 6081 MVT ContainerVT = VT; 6082 if (VT.isFixedLengthVector()) { 6083 ContainerVT = getContainerForFixedLengthVector(VT); 6084 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6085 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6086 } 6087 6088 MVT XLenVT = Subtarget.getXLenVT(); 6089 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6090 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6091 DAG.getUNDEF(ContainerVT), Zero, VL); 6092 6093 SDValue SplatValue = 6094 DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT); 6095 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6096 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6097 6098 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6099 Splat, ZeroSplat, VL); 6100 if (!VT.isFixedLengthVector()) 6101 return Result; 6102 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6103 } 6104 6105 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6106 SelectionDAG &DAG) const { 6107 SDLoc DL(Op); 6108 MVT VT = Op.getSimpleValueType(); 6109 6110 SDValue Op1 = Op.getOperand(0); 6111 SDValue Op2 = Op.getOperand(1); 6112 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6113 // NOTE: Mask is dropped. 6114 SDValue VL = Op.getOperand(4); 6115 6116 MVT ContainerVT = VT; 6117 if (VT.isFixedLengthVector()) { 6118 ContainerVT = getContainerForFixedLengthVector(VT); 6119 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6120 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6121 } 6122 6123 SDValue Result; 6124 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6125 6126 switch (Condition) { 6127 default: 6128 break; 6129 // X != Y --> (X^Y) 6130 case ISD::SETNE: 6131 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6132 break; 6133 // X == Y --> ~(X^Y) 6134 case ISD::SETEQ: { 6135 SDValue Temp = 6136 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6137 Result = 6138 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6139 break; 6140 } 6141 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6142 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6143 case ISD::SETGT: 6144 case ISD::SETULT: { 6145 SDValue Temp = 6146 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6147 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6148 break; 6149 } 6150 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6151 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6152 case ISD::SETLT: 6153 case ISD::SETUGT: { 6154 SDValue Temp = 6155 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6156 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6157 break; 6158 } 6159 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6160 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6161 case ISD::SETGE: 6162 case ISD::SETULE: { 6163 SDValue Temp = 6164 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6165 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6166 break; 6167 } 6168 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6169 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6170 case ISD::SETLE: 6171 case ISD::SETUGE: { 6172 SDValue Temp = 6173 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6174 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6175 break; 6176 } 6177 } 6178 6179 if (!VT.isFixedLengthVector()) 6180 return Result; 6181 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6182 } 6183 6184 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6185 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6186 unsigned RISCVISDOpc) const { 6187 SDLoc DL(Op); 6188 6189 SDValue Src = Op.getOperand(0); 6190 SDValue Mask = Op.getOperand(1); 6191 SDValue VL = Op.getOperand(2); 6192 6193 MVT DstVT = Op.getSimpleValueType(); 6194 MVT SrcVT = Src.getSimpleValueType(); 6195 if (DstVT.isFixedLengthVector()) { 6196 DstVT = getContainerForFixedLengthVector(DstVT); 6197 SrcVT = getContainerForFixedLengthVector(SrcVT); 6198 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6199 MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount()); 6200 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6201 } 6202 6203 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6204 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6205 ? RISCVISD::VSEXT_VL 6206 : RISCVISD::VZEXT_VL; 6207 6208 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6209 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6210 6211 SDValue Result; 6212 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6213 if (SrcVT.isInteger()) { 6214 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6215 6216 // Do we need to do any pre-widening before converting? 6217 if (SrcEltSize == 1) { 6218 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6219 MVT XLenVT = Subtarget.getXLenVT(); 6220 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6221 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6222 DAG.getUNDEF(IntVT), Zero, VL); 6223 SDValue One = DAG.getConstant( 6224 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6225 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6226 DAG.getUNDEF(IntVT), One, VL); 6227 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6228 ZeroSplat, VL); 6229 } else if (DstEltSize > (2 * SrcEltSize)) { 6230 // Widen before converting. 6231 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6232 DstVT.getVectorElementCount()); 6233 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6234 } 6235 6236 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6237 } else { 6238 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6239 "Wrong input/output vector types"); 6240 6241 // Convert f16 to f32 then convert f32 to i64. 6242 if (DstEltSize > (2 * SrcEltSize)) { 6243 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6244 MVT InterimFVT = 6245 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6246 Src = 6247 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6248 } 6249 6250 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6251 } 6252 } else { // Narrowing + Conversion 6253 if (SrcVT.isInteger()) { 6254 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6255 // First do a narrowing convert to an FP type half the size, then round 6256 // the FP type to a small FP type if needed. 6257 6258 MVT InterimFVT = DstVT; 6259 if (SrcEltSize > (2 * DstEltSize)) { 6260 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6261 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6262 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6263 } 6264 6265 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6266 6267 if (InterimFVT != DstVT) { 6268 Src = Result; 6269 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6270 } 6271 } else { 6272 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6273 "Wrong input/output vector types"); 6274 // First do a narrowing conversion to an integer half the size, then 6275 // truncate if needed. 6276 6277 if (DstEltSize == 1) { 6278 // First convert to the same size integer, then convert to mask using 6279 // setcc. 6280 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6281 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6282 DstVT.getVectorElementCount()); 6283 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6284 6285 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6286 // otherwise the conversion was undefined. 6287 MVT XLenVT = Subtarget.getXLenVT(); 6288 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6289 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6290 DAG.getUNDEF(InterimIVT), SplatZero); 6291 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6292 DAG.getCondCode(ISD::SETNE), Mask, VL); 6293 } else { 6294 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6295 DstVT.getVectorElementCount()); 6296 6297 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6298 6299 while (InterimIVT != DstVT) { 6300 SrcEltSize /= 2; 6301 Src = Result; 6302 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6303 DstVT.getVectorElementCount()); 6304 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6305 Src, Mask, VL); 6306 } 6307 } 6308 } 6309 } 6310 6311 MVT VT = Op.getSimpleValueType(); 6312 if (!VT.isFixedLengthVector()) 6313 return Result; 6314 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6315 } 6316 6317 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6318 unsigned MaskOpc, 6319 unsigned VecOpc) const { 6320 MVT VT = Op.getSimpleValueType(); 6321 if (VT.getVectorElementType() != MVT::i1) 6322 return lowerVPOp(Op, DAG, VecOpc); 6323 6324 // It is safe to drop mask parameter as masked-off elements are undef. 6325 SDValue Op1 = Op->getOperand(0); 6326 SDValue Op2 = Op->getOperand(1); 6327 SDValue VL = Op->getOperand(3); 6328 6329 MVT ContainerVT = VT; 6330 const bool IsFixed = VT.isFixedLengthVector(); 6331 if (IsFixed) { 6332 ContainerVT = getContainerForFixedLengthVector(VT); 6333 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6334 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6335 } 6336 6337 SDLoc DL(Op); 6338 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6339 if (!IsFixed) 6340 return Val; 6341 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6342 } 6343 6344 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6345 // matched to a RVV indexed load. The RVV indexed load instructions only 6346 // support the "unsigned unscaled" addressing mode; indices are implicitly 6347 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6348 // signed or scaled indexing is extended to the XLEN value type and scaled 6349 // accordingly. 6350 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6351 SelectionDAG &DAG) const { 6352 SDLoc DL(Op); 6353 MVT VT = Op.getSimpleValueType(); 6354 6355 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6356 EVT MemVT = MemSD->getMemoryVT(); 6357 MachineMemOperand *MMO = MemSD->getMemOperand(); 6358 SDValue Chain = MemSD->getChain(); 6359 SDValue BasePtr = MemSD->getBasePtr(); 6360 6361 ISD::LoadExtType LoadExtType; 6362 SDValue Index, Mask, PassThru, VL; 6363 6364 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6365 Index = VPGN->getIndex(); 6366 Mask = VPGN->getMask(); 6367 PassThru = DAG.getUNDEF(VT); 6368 VL = VPGN->getVectorLength(); 6369 // VP doesn't support extending loads. 6370 LoadExtType = ISD::NON_EXTLOAD; 6371 } else { 6372 // Else it must be a MGATHER. 6373 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6374 Index = MGN->getIndex(); 6375 Mask = MGN->getMask(); 6376 PassThru = MGN->getPassThru(); 6377 LoadExtType = MGN->getExtensionType(); 6378 } 6379 6380 MVT IndexVT = Index.getSimpleValueType(); 6381 MVT XLenVT = Subtarget.getXLenVT(); 6382 6383 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6384 "Unexpected VTs!"); 6385 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6386 // Targets have to explicitly opt-in for extending vector loads. 6387 assert(LoadExtType == ISD::NON_EXTLOAD && 6388 "Unexpected extending MGATHER/VP_GATHER"); 6389 (void)LoadExtType; 6390 6391 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6392 // the selection of the masked intrinsics doesn't do this for us. 6393 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6394 6395 MVT ContainerVT = VT; 6396 if (VT.isFixedLengthVector()) { 6397 // We need to use the larger of the result and index type to determine the 6398 // scalable type to use so we don't increase LMUL for any operand/result. 6399 if (VT.bitsGE(IndexVT)) { 6400 ContainerVT = getContainerForFixedLengthVector(VT); 6401 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6402 ContainerVT.getVectorElementCount()); 6403 } else { 6404 IndexVT = getContainerForFixedLengthVector(IndexVT); 6405 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6406 IndexVT.getVectorElementCount()); 6407 } 6408 6409 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6410 6411 if (!IsUnmasked) { 6412 MVT MaskVT = 6413 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6414 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6415 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6416 } 6417 } 6418 6419 if (!VL) 6420 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6421 6422 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6423 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6424 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6425 VL); 6426 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6427 TrueMask, VL); 6428 } 6429 6430 unsigned IntID = 6431 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6432 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6433 if (IsUnmasked) 6434 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6435 else 6436 Ops.push_back(PassThru); 6437 Ops.push_back(BasePtr); 6438 Ops.push_back(Index); 6439 if (!IsUnmasked) 6440 Ops.push_back(Mask); 6441 Ops.push_back(VL); 6442 if (!IsUnmasked) 6443 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6444 6445 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6446 SDValue Result = 6447 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6448 Chain = Result.getValue(1); 6449 6450 if (VT.isFixedLengthVector()) 6451 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6452 6453 return DAG.getMergeValues({Result, Chain}, DL); 6454 } 6455 6456 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6457 // matched to a RVV indexed store. The RVV indexed store instructions only 6458 // support the "unsigned unscaled" addressing mode; indices are implicitly 6459 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6460 // signed or scaled indexing is extended to the XLEN value type and scaled 6461 // accordingly. 6462 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6463 SelectionDAG &DAG) const { 6464 SDLoc DL(Op); 6465 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6466 EVT MemVT = MemSD->getMemoryVT(); 6467 MachineMemOperand *MMO = MemSD->getMemOperand(); 6468 SDValue Chain = MemSD->getChain(); 6469 SDValue BasePtr = MemSD->getBasePtr(); 6470 6471 bool IsTruncatingStore = false; 6472 SDValue Index, Mask, Val, VL; 6473 6474 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6475 Index = VPSN->getIndex(); 6476 Mask = VPSN->getMask(); 6477 Val = VPSN->getValue(); 6478 VL = VPSN->getVectorLength(); 6479 // VP doesn't support truncating stores. 6480 IsTruncatingStore = false; 6481 } else { 6482 // Else it must be a MSCATTER. 6483 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6484 Index = MSN->getIndex(); 6485 Mask = MSN->getMask(); 6486 Val = MSN->getValue(); 6487 IsTruncatingStore = MSN->isTruncatingStore(); 6488 } 6489 6490 MVT VT = Val.getSimpleValueType(); 6491 MVT IndexVT = Index.getSimpleValueType(); 6492 MVT XLenVT = Subtarget.getXLenVT(); 6493 6494 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6495 "Unexpected VTs!"); 6496 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6497 // Targets have to explicitly opt-in for extending vector loads and 6498 // truncating vector stores. 6499 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6500 (void)IsTruncatingStore; 6501 6502 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6503 // the selection of the masked intrinsics doesn't do this for us. 6504 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6505 6506 MVT ContainerVT = VT; 6507 if (VT.isFixedLengthVector()) { 6508 // We need to use the larger of the value and index type to determine the 6509 // scalable type to use so we don't increase LMUL for any operand/result. 6510 if (VT.bitsGE(IndexVT)) { 6511 ContainerVT = getContainerForFixedLengthVector(VT); 6512 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6513 ContainerVT.getVectorElementCount()); 6514 } else { 6515 IndexVT = getContainerForFixedLengthVector(IndexVT); 6516 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6517 IndexVT.getVectorElementCount()); 6518 } 6519 6520 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6521 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6522 6523 if (!IsUnmasked) { 6524 MVT MaskVT = 6525 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6526 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6527 } 6528 } 6529 6530 if (!VL) 6531 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6532 6533 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6534 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6535 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6536 VL); 6537 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6538 TrueMask, VL); 6539 } 6540 6541 unsigned IntID = 6542 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6543 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6544 Ops.push_back(Val); 6545 Ops.push_back(BasePtr); 6546 Ops.push_back(Index); 6547 if (!IsUnmasked) 6548 Ops.push_back(Mask); 6549 Ops.push_back(VL); 6550 6551 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6552 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6553 } 6554 6555 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6556 SelectionDAG &DAG) const { 6557 const MVT XLenVT = Subtarget.getXLenVT(); 6558 SDLoc DL(Op); 6559 SDValue Chain = Op->getOperand(0); 6560 SDValue SysRegNo = DAG.getTargetConstant( 6561 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6562 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6563 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6564 6565 // Encoding used for rounding mode in RISCV differs from that used in 6566 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6567 // table, which consists of a sequence of 4-bit fields, each representing 6568 // corresponding FLT_ROUNDS mode. 6569 static const int Table = 6570 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6571 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6572 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6573 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6574 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6575 6576 SDValue Shift = 6577 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6578 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6579 DAG.getConstant(Table, DL, XLenVT), Shift); 6580 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6581 DAG.getConstant(7, DL, XLenVT)); 6582 6583 return DAG.getMergeValues({Masked, Chain}, DL); 6584 } 6585 6586 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6587 SelectionDAG &DAG) const { 6588 const MVT XLenVT = Subtarget.getXLenVT(); 6589 SDLoc DL(Op); 6590 SDValue Chain = Op->getOperand(0); 6591 SDValue RMValue = Op->getOperand(1); 6592 SDValue SysRegNo = DAG.getTargetConstant( 6593 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6594 6595 // Encoding used for rounding mode in RISCV differs from that used in 6596 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6597 // a table, which consists of a sequence of 4-bit fields, each representing 6598 // corresponding RISCV mode. 6599 static const unsigned Table = 6600 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6601 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6602 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6603 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6604 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6605 6606 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6607 DAG.getConstant(2, DL, XLenVT)); 6608 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6609 DAG.getConstant(Table, DL, XLenVT), Shift); 6610 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6611 DAG.getConstant(0x7, DL, XLenVT)); 6612 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6613 RMValue); 6614 } 6615 6616 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6617 switch (IntNo) { 6618 default: 6619 llvm_unreachable("Unexpected Intrinsic"); 6620 case Intrinsic::riscv_bcompress: 6621 return RISCVISD::BCOMPRESSW; 6622 case Intrinsic::riscv_bdecompress: 6623 return RISCVISD::BDECOMPRESSW; 6624 case Intrinsic::riscv_bfp: 6625 return RISCVISD::BFPW; 6626 case Intrinsic::riscv_fsl: 6627 return RISCVISD::FSLW; 6628 case Intrinsic::riscv_fsr: 6629 return RISCVISD::FSRW; 6630 } 6631 } 6632 6633 // Converts the given intrinsic to a i64 operation with any extension. 6634 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6635 unsigned IntNo) { 6636 SDLoc DL(N); 6637 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6638 // Deal with the Instruction Operands 6639 SmallVector<SDValue, 3> NewOps; 6640 for (SDValue Op : drop_begin(N->ops())) 6641 // Promote the operand to i64 type 6642 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6643 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6644 // ReplaceNodeResults requires we maintain the same type for the return value. 6645 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6646 } 6647 6648 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6649 // form of the given Opcode. 6650 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6651 switch (Opcode) { 6652 default: 6653 llvm_unreachable("Unexpected opcode"); 6654 case ISD::SHL: 6655 return RISCVISD::SLLW; 6656 case ISD::SRA: 6657 return RISCVISD::SRAW; 6658 case ISD::SRL: 6659 return RISCVISD::SRLW; 6660 case ISD::SDIV: 6661 return RISCVISD::DIVW; 6662 case ISD::UDIV: 6663 return RISCVISD::DIVUW; 6664 case ISD::UREM: 6665 return RISCVISD::REMUW; 6666 case ISD::ROTL: 6667 return RISCVISD::ROLW; 6668 case ISD::ROTR: 6669 return RISCVISD::RORW; 6670 } 6671 } 6672 6673 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6674 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6675 // otherwise be promoted to i64, making it difficult to select the 6676 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6677 // type i8/i16/i32 is lost. 6678 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6679 unsigned ExtOpc = ISD::ANY_EXTEND) { 6680 SDLoc DL(N); 6681 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6682 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6683 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6684 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6685 // ReplaceNodeResults requires we maintain the same type for the return value. 6686 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6687 } 6688 6689 // Converts the given 32-bit operation to a i64 operation with signed extension 6690 // semantic to reduce the signed extension instructions. 6691 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6692 SDLoc DL(N); 6693 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6694 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6695 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6696 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6697 DAG.getValueType(MVT::i32)); 6698 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6699 } 6700 6701 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6702 SmallVectorImpl<SDValue> &Results, 6703 SelectionDAG &DAG) const { 6704 SDLoc DL(N); 6705 switch (N->getOpcode()) { 6706 default: 6707 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6708 case ISD::STRICT_FP_TO_SINT: 6709 case ISD::STRICT_FP_TO_UINT: 6710 case ISD::FP_TO_SINT: 6711 case ISD::FP_TO_UINT: { 6712 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6713 "Unexpected custom legalisation"); 6714 bool IsStrict = N->isStrictFPOpcode(); 6715 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6716 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6717 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6718 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6719 TargetLowering::TypeSoftenFloat) { 6720 if (!isTypeLegal(Op0.getValueType())) 6721 return; 6722 if (IsStrict) { 6723 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6724 : RISCVISD::STRICT_FCVT_WU_RV64; 6725 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6726 SDValue Res = DAG.getNode( 6727 Opc, DL, VTs, N->getOperand(0), Op0, 6728 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6729 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6730 Results.push_back(Res.getValue(1)); 6731 return; 6732 } 6733 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6734 SDValue Res = 6735 DAG.getNode(Opc, DL, MVT::i64, Op0, 6736 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6737 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6738 return; 6739 } 6740 // If the FP type needs to be softened, emit a library call using the 'si' 6741 // version. If we left it to default legalization we'd end up with 'di'. If 6742 // the FP type doesn't need to be softened just let generic type 6743 // legalization promote the result type. 6744 RTLIB::Libcall LC; 6745 if (IsSigned) 6746 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6747 else 6748 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6749 MakeLibCallOptions CallOptions; 6750 EVT OpVT = Op0.getValueType(); 6751 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6752 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6753 SDValue Result; 6754 std::tie(Result, Chain) = 6755 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6756 Results.push_back(Result); 6757 if (IsStrict) 6758 Results.push_back(Chain); 6759 break; 6760 } 6761 case ISD::READCYCLECOUNTER: { 6762 assert(!Subtarget.is64Bit() && 6763 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6764 6765 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6766 SDValue RCW = 6767 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6768 6769 Results.push_back( 6770 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6771 Results.push_back(RCW.getValue(2)); 6772 break; 6773 } 6774 case ISD::MUL: { 6775 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6776 unsigned XLen = Subtarget.getXLen(); 6777 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6778 if (Size > XLen) { 6779 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6780 SDValue LHS = N->getOperand(0); 6781 SDValue RHS = N->getOperand(1); 6782 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6783 6784 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6785 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6786 // We need exactly one side to be unsigned. 6787 if (LHSIsU == RHSIsU) 6788 return; 6789 6790 auto MakeMULPair = [&](SDValue S, SDValue U) { 6791 MVT XLenVT = Subtarget.getXLenVT(); 6792 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6793 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6794 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6795 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6796 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6797 }; 6798 6799 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6800 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6801 6802 // The other operand should be signed, but still prefer MULH when 6803 // possible. 6804 if (RHSIsU && LHSIsS && !RHSIsS) 6805 Results.push_back(MakeMULPair(LHS, RHS)); 6806 else if (LHSIsU && RHSIsS && !LHSIsS) 6807 Results.push_back(MakeMULPair(RHS, LHS)); 6808 6809 return; 6810 } 6811 LLVM_FALLTHROUGH; 6812 } 6813 case ISD::ADD: 6814 case ISD::SUB: 6815 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6816 "Unexpected custom legalisation"); 6817 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6818 break; 6819 case ISD::SHL: 6820 case ISD::SRA: 6821 case ISD::SRL: 6822 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6823 "Unexpected custom legalisation"); 6824 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6825 Results.push_back(customLegalizeToWOp(N, DAG)); 6826 break; 6827 } 6828 6829 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6830 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6831 // shift amount. 6832 if (N->getOpcode() == ISD::SHL) { 6833 SDLoc DL(N); 6834 SDValue NewOp0 = 6835 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6836 SDValue NewOp1 = 6837 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6838 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6839 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6840 DAG.getValueType(MVT::i32)); 6841 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6842 } 6843 6844 break; 6845 case ISD::ROTL: 6846 case ISD::ROTR: 6847 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6848 "Unexpected custom legalisation"); 6849 Results.push_back(customLegalizeToWOp(N, DAG)); 6850 break; 6851 case ISD::CTTZ: 6852 case ISD::CTTZ_ZERO_UNDEF: 6853 case ISD::CTLZ: 6854 case ISD::CTLZ_ZERO_UNDEF: { 6855 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6856 "Unexpected custom legalisation"); 6857 6858 SDValue NewOp0 = 6859 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6860 bool IsCTZ = 6861 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6862 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6863 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6864 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6865 return; 6866 } 6867 case ISD::SDIV: 6868 case ISD::UDIV: 6869 case ISD::UREM: { 6870 MVT VT = N->getSimpleValueType(0); 6871 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6872 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6873 "Unexpected custom legalisation"); 6874 // Don't promote division/remainder by constant since we should expand those 6875 // to multiply by magic constant. 6876 // FIXME: What if the expansion is disabled for minsize. 6877 if (N->getOperand(1).getOpcode() == ISD::Constant) 6878 return; 6879 6880 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6881 // the upper 32 bits. For other types we need to sign or zero extend 6882 // based on the opcode. 6883 unsigned ExtOpc = ISD::ANY_EXTEND; 6884 if (VT != MVT::i32) 6885 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6886 : ISD::ZERO_EXTEND; 6887 6888 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6889 break; 6890 } 6891 case ISD::UADDO: 6892 case ISD::USUBO: { 6893 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6894 "Unexpected custom legalisation"); 6895 bool IsAdd = N->getOpcode() == ISD::UADDO; 6896 // Create an ADDW or SUBW. 6897 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6898 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6899 SDValue Res = 6900 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6901 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6902 DAG.getValueType(MVT::i32)); 6903 6904 SDValue Overflow; 6905 if (IsAdd && isOneConstant(RHS)) { 6906 // Special case uaddo X, 1 overflowed if the addition result is 0. 6907 // FIXME: We can do this for any constant RHS by using (X + C) < C. 6908 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6909 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6910 } else { 6911 // Sign extend the LHS and perform an unsigned compare with the ADDW 6912 // result. Since the inputs are sign extended from i32, this is equivalent 6913 // to comparing the lower 32 bits. 6914 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6915 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6916 IsAdd ? ISD::SETULT : ISD::SETUGT); 6917 } 6918 6919 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6920 Results.push_back(Overflow); 6921 return; 6922 } 6923 case ISD::UADDSAT: 6924 case ISD::USUBSAT: { 6925 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6926 "Unexpected custom legalisation"); 6927 if (Subtarget.hasStdExtZbb()) { 6928 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6929 // sign extend allows overflow of the lower 32 bits to be detected on 6930 // the promoted size. 6931 SDValue LHS = 6932 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6933 SDValue RHS = 6934 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6935 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6936 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6937 return; 6938 } 6939 6940 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6941 // promotion for UADDO/USUBO. 6942 Results.push_back(expandAddSubSat(N, DAG)); 6943 return; 6944 } 6945 case ISD::ABS: { 6946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6947 "Unexpected custom legalisation"); 6948 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6949 6950 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6951 6952 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6953 6954 // Freeze the source so we can increase it's use count. 6955 Src = DAG.getFreeze(Src); 6956 6957 // Copy sign bit to all bits using the sraiw pattern. 6958 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6959 DAG.getValueType(MVT::i32)); 6960 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6961 DAG.getConstant(31, DL, MVT::i64)); 6962 6963 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6964 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6965 6966 // NOTE: The result is only required to be anyextended, but sext is 6967 // consistent with type legalization of sub. 6968 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6969 DAG.getValueType(MVT::i32)); 6970 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6971 return; 6972 } 6973 case ISD::BITCAST: { 6974 EVT VT = N->getValueType(0); 6975 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6976 SDValue Op0 = N->getOperand(0); 6977 EVT Op0VT = Op0.getValueType(); 6978 MVT XLenVT = Subtarget.getXLenVT(); 6979 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6980 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6981 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6982 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6983 Subtarget.hasStdExtF()) { 6984 SDValue FPConv = 6985 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6986 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6987 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6988 isTypeLegal(Op0VT)) { 6989 // Custom-legalize bitcasts from fixed-length vector types to illegal 6990 // scalar types in order to improve codegen. Bitcast the vector to a 6991 // one-element vector type whose element type is the same as the result 6992 // type, and extract the first element. 6993 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6994 if (isTypeLegal(BVT)) { 6995 SDValue BVec = DAG.getBitcast(BVT, Op0); 6996 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6997 DAG.getConstant(0, DL, XLenVT))); 6998 } 6999 } 7000 break; 7001 } 7002 case RISCVISD::GREV: 7003 case RISCVISD::GORC: 7004 case RISCVISD::SHFL: { 7005 MVT VT = N->getSimpleValueType(0); 7006 MVT XLenVT = Subtarget.getXLenVT(); 7007 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7008 "Unexpected custom legalisation"); 7009 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7010 assert((Subtarget.hasStdExtZbp() || 7011 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7012 N->getConstantOperandVal(1) == 7)) && 7013 "Unexpected extension"); 7014 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7015 SDValue NewOp1 = 7016 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7017 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7018 // ReplaceNodeResults requires we maintain the same type for the return 7019 // value. 7020 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7021 break; 7022 } 7023 case ISD::BSWAP: 7024 case ISD::BITREVERSE: { 7025 MVT VT = N->getSimpleValueType(0); 7026 MVT XLenVT = Subtarget.getXLenVT(); 7027 assert((VT == MVT::i8 || VT == MVT::i16 || 7028 (VT == MVT::i32 && Subtarget.is64Bit())) && 7029 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7030 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7031 unsigned Imm = VT.getSizeInBits() - 1; 7032 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7033 if (N->getOpcode() == ISD::BSWAP) 7034 Imm &= ~0x7U; 7035 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7036 DAG.getConstant(Imm, DL, XLenVT)); 7037 // ReplaceNodeResults requires we maintain the same type for the return 7038 // value. 7039 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7040 break; 7041 } 7042 case ISD::FSHL: 7043 case ISD::FSHR: { 7044 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7045 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7046 SDValue NewOp0 = 7047 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7048 SDValue NewOp1 = 7049 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7050 SDValue NewShAmt = 7051 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7052 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7053 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7054 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7055 DAG.getConstant(0x1f, DL, MVT::i64)); 7056 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7057 // instruction use different orders. fshl will return its first operand for 7058 // shift of zero, fshr will return its second operand. fsl and fsr both 7059 // return rs1 so the ISD nodes need to have different operand orders. 7060 // Shift amount is in rs2. 7061 unsigned Opc = RISCVISD::FSLW; 7062 if (N->getOpcode() == ISD::FSHR) { 7063 std::swap(NewOp0, NewOp1); 7064 Opc = RISCVISD::FSRW; 7065 } 7066 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7067 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7068 break; 7069 } 7070 case ISD::EXTRACT_VECTOR_ELT: { 7071 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7072 // type is illegal (currently only vXi64 RV32). 7073 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7074 // transferred to the destination register. We issue two of these from the 7075 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7076 // first element. 7077 SDValue Vec = N->getOperand(0); 7078 SDValue Idx = N->getOperand(1); 7079 7080 // The vector type hasn't been legalized yet so we can't issue target 7081 // specific nodes if it needs legalization. 7082 // FIXME: We would manually legalize if it's important. 7083 if (!isTypeLegal(Vec.getValueType())) 7084 return; 7085 7086 MVT VecVT = Vec.getSimpleValueType(); 7087 7088 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7089 VecVT.getVectorElementType() == MVT::i64 && 7090 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7091 7092 // If this is a fixed vector, we need to convert it to a scalable vector. 7093 MVT ContainerVT = VecVT; 7094 if (VecVT.isFixedLengthVector()) { 7095 ContainerVT = getContainerForFixedLengthVector(VecVT); 7096 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7097 } 7098 7099 MVT XLenVT = Subtarget.getXLenVT(); 7100 7101 // Use a VL of 1 to avoid processing more elements than we need. 7102 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 7103 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7104 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7105 7106 // Unless the index is known to be 0, we must slide the vector down to get 7107 // the desired element into index 0. 7108 if (!isNullConstant(Idx)) { 7109 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7110 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7111 } 7112 7113 // Extract the lower XLEN bits of the correct vector element. 7114 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7115 7116 // To extract the upper XLEN bits of the vector element, shift the first 7117 // element right by 32 bits and re-extract the lower XLEN bits. 7118 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7119 DAG.getUNDEF(ContainerVT), 7120 DAG.getConstant(32, DL, XLenVT), VL); 7121 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7122 ThirtyTwoV, Mask, VL); 7123 7124 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7125 7126 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7127 break; 7128 } 7129 case ISD::INTRINSIC_WO_CHAIN: { 7130 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7131 switch (IntNo) { 7132 default: 7133 llvm_unreachable( 7134 "Don't know how to custom type legalize this intrinsic!"); 7135 case Intrinsic::riscv_grev: 7136 case Intrinsic::riscv_gorc: { 7137 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7138 "Unexpected custom legalisation"); 7139 SDValue NewOp1 = 7140 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7141 SDValue NewOp2 = 7142 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7143 unsigned Opc = 7144 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7145 // If the control is a constant, promote the node by clearing any extra 7146 // bits bits in the control. isel will form greviw/gorciw if the result is 7147 // sign extended. 7148 if (isa<ConstantSDNode>(NewOp2)) { 7149 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7150 DAG.getConstant(0x1f, DL, MVT::i64)); 7151 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7152 } 7153 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7154 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7155 break; 7156 } 7157 case Intrinsic::riscv_bcompress: 7158 case Intrinsic::riscv_bdecompress: 7159 case Intrinsic::riscv_bfp: 7160 case Intrinsic::riscv_fsl: 7161 case Intrinsic::riscv_fsr: { 7162 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7163 "Unexpected custom legalisation"); 7164 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7165 break; 7166 } 7167 case Intrinsic::riscv_orc_b: { 7168 // Lower to the GORCI encoding for orc.b with the operand extended. 7169 SDValue NewOp = 7170 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7171 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7172 DAG.getConstant(7, DL, MVT::i64)); 7173 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7174 return; 7175 } 7176 case Intrinsic::riscv_shfl: 7177 case Intrinsic::riscv_unshfl: { 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_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7186 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7187 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7188 // will be shuffled the same way as the lower 32 bit half, but the two 7189 // halves won't cross. 7190 if (isa<ConstantSDNode>(NewOp2)) { 7191 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7192 DAG.getConstant(0xf, DL, MVT::i64)); 7193 Opc = 7194 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7195 } 7196 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7197 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7198 break; 7199 } 7200 case Intrinsic::riscv_vmv_x_s: { 7201 EVT VT = N->getValueType(0); 7202 MVT XLenVT = Subtarget.getXLenVT(); 7203 if (VT.bitsLT(XLenVT)) { 7204 // Simple case just extract using vmv.x.s and truncate. 7205 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7206 Subtarget.getXLenVT(), N->getOperand(1)); 7207 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7208 return; 7209 } 7210 7211 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7212 "Unexpected custom legalization"); 7213 7214 // We need to do the move in two steps. 7215 SDValue Vec = N->getOperand(1); 7216 MVT VecVT = Vec.getSimpleValueType(); 7217 7218 // First extract the lower XLEN bits of the element. 7219 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7220 7221 // To extract the upper XLEN bits of the vector element, shift the first 7222 // element right by 32 bits and re-extract the lower XLEN bits. 7223 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7224 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7225 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7226 SDValue ThirtyTwoV = 7227 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7228 DAG.getConstant(32, DL, XLenVT), VL); 7229 SDValue LShr32 = 7230 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7231 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7232 7233 Results.push_back( 7234 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7235 break; 7236 } 7237 } 7238 break; 7239 } 7240 case ISD::VECREDUCE_ADD: 7241 case ISD::VECREDUCE_AND: 7242 case ISD::VECREDUCE_OR: 7243 case ISD::VECREDUCE_XOR: 7244 case ISD::VECREDUCE_SMAX: 7245 case ISD::VECREDUCE_UMAX: 7246 case ISD::VECREDUCE_SMIN: 7247 case ISD::VECREDUCE_UMIN: 7248 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7249 Results.push_back(V); 7250 break; 7251 case ISD::VP_REDUCE_ADD: 7252 case ISD::VP_REDUCE_AND: 7253 case ISD::VP_REDUCE_OR: 7254 case ISD::VP_REDUCE_XOR: 7255 case ISD::VP_REDUCE_SMAX: 7256 case ISD::VP_REDUCE_UMAX: 7257 case ISD::VP_REDUCE_SMIN: 7258 case ISD::VP_REDUCE_UMIN: 7259 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7260 Results.push_back(V); 7261 break; 7262 case ISD::FLT_ROUNDS_: { 7263 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7264 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7265 Results.push_back(Res.getValue(0)); 7266 Results.push_back(Res.getValue(1)); 7267 break; 7268 } 7269 } 7270 } 7271 7272 // A structure to hold one of the bit-manipulation patterns below. Together, a 7273 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7274 // (or (and (shl x, 1), 0xAAAAAAAA), 7275 // (and (srl x, 1), 0x55555555)) 7276 struct RISCVBitmanipPat { 7277 SDValue Op; 7278 unsigned ShAmt; 7279 bool IsSHL; 7280 7281 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7282 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7283 } 7284 }; 7285 7286 // Matches patterns of the form 7287 // (and (shl x, C2), (C1 << C2)) 7288 // (and (srl x, C2), C1) 7289 // (shl (and x, C1), C2) 7290 // (srl (and x, (C1 << C2)), C2) 7291 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7292 // The expected masks for each shift amount are specified in BitmanipMasks where 7293 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7294 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7295 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7296 // XLen is 64. 7297 static Optional<RISCVBitmanipPat> 7298 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7299 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7300 "Unexpected number of masks"); 7301 Optional<uint64_t> Mask; 7302 // Optionally consume a mask around the shift operation. 7303 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7304 Mask = Op.getConstantOperandVal(1); 7305 Op = Op.getOperand(0); 7306 } 7307 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7308 return None; 7309 bool IsSHL = Op.getOpcode() == ISD::SHL; 7310 7311 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7312 return None; 7313 uint64_t ShAmt = Op.getConstantOperandVal(1); 7314 7315 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7316 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7317 return None; 7318 // If we don't have enough masks for 64 bit, then we must be trying to 7319 // match SHFL so we're only allowed to shift 1/4 of the width. 7320 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7321 return None; 7322 7323 SDValue Src = Op.getOperand(0); 7324 7325 // The expected mask is shifted left when the AND is found around SHL 7326 // patterns. 7327 // ((x >> 1) & 0x55555555) 7328 // ((x << 1) & 0xAAAAAAAA) 7329 bool SHLExpMask = IsSHL; 7330 7331 if (!Mask) { 7332 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7333 // the mask is all ones: consume that now. 7334 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7335 Mask = Src.getConstantOperandVal(1); 7336 Src = Src.getOperand(0); 7337 // The expected mask is now in fact shifted left for SRL, so reverse the 7338 // decision. 7339 // ((x & 0xAAAAAAAA) >> 1) 7340 // ((x & 0x55555555) << 1) 7341 SHLExpMask = !SHLExpMask; 7342 } else { 7343 // Use a default shifted mask of all-ones if there's no AND, truncated 7344 // down to the expected width. This simplifies the logic later on. 7345 Mask = maskTrailingOnes<uint64_t>(Width); 7346 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7347 } 7348 } 7349 7350 unsigned MaskIdx = Log2_32(ShAmt); 7351 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7352 7353 if (SHLExpMask) 7354 ExpMask <<= ShAmt; 7355 7356 if (Mask != ExpMask) 7357 return None; 7358 7359 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7360 } 7361 7362 // Matches any of the following bit-manipulation patterns: 7363 // (and (shl x, 1), (0x55555555 << 1)) 7364 // (and (srl x, 1), 0x55555555) 7365 // (shl (and x, 0x55555555), 1) 7366 // (srl (and x, (0x55555555 << 1)), 1) 7367 // where the shift amount and mask may vary thus: 7368 // [1] = 0x55555555 / 0xAAAAAAAA 7369 // [2] = 0x33333333 / 0xCCCCCCCC 7370 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7371 // [8] = 0x00FF00FF / 0xFF00FF00 7372 // [16] = 0x0000FFFF / 0xFFFFFFFF 7373 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7374 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7375 // These are the unshifted masks which we use to match bit-manipulation 7376 // patterns. They may be shifted left in certain circumstances. 7377 static const uint64_t BitmanipMasks[] = { 7378 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7379 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7380 7381 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7382 } 7383 7384 // Match the following pattern as a GREVI(W) operation 7385 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7386 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7387 const RISCVSubtarget &Subtarget) { 7388 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7389 EVT VT = Op.getValueType(); 7390 7391 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7392 auto LHS = matchGREVIPat(Op.getOperand(0)); 7393 auto RHS = matchGREVIPat(Op.getOperand(1)); 7394 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7395 SDLoc DL(Op); 7396 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7397 DAG.getConstant(LHS->ShAmt, DL, VT)); 7398 } 7399 } 7400 return SDValue(); 7401 } 7402 7403 // Matches any the following pattern as a GORCI(W) operation 7404 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7405 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7406 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7407 // Note that with the variant of 3., 7408 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7409 // the inner pattern will first be matched as GREVI and then the outer 7410 // pattern will be matched to GORC via the first rule above. 7411 // 4. (or (rotl/rotr x, bitwidth/2), x) 7412 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7413 const RISCVSubtarget &Subtarget) { 7414 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7415 EVT VT = Op.getValueType(); 7416 7417 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7418 SDLoc DL(Op); 7419 SDValue Op0 = Op.getOperand(0); 7420 SDValue Op1 = Op.getOperand(1); 7421 7422 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7423 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7424 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7425 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7426 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7427 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7428 if ((Reverse.getOpcode() == ISD::ROTL || 7429 Reverse.getOpcode() == ISD::ROTR) && 7430 Reverse.getOperand(0) == X && 7431 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7432 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7433 if (RotAmt == (VT.getSizeInBits() / 2)) 7434 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7435 DAG.getConstant(RotAmt, DL, VT)); 7436 } 7437 return SDValue(); 7438 }; 7439 7440 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7441 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7442 return V; 7443 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7444 return V; 7445 7446 // OR is commutable so canonicalize its OR operand to the left 7447 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7448 std::swap(Op0, Op1); 7449 if (Op0.getOpcode() != ISD::OR) 7450 return SDValue(); 7451 SDValue OrOp0 = Op0.getOperand(0); 7452 SDValue OrOp1 = Op0.getOperand(1); 7453 auto LHS = matchGREVIPat(OrOp0); 7454 // OR is commutable so swap the operands and try again: x might have been 7455 // on the left 7456 if (!LHS) { 7457 std::swap(OrOp0, OrOp1); 7458 LHS = matchGREVIPat(OrOp0); 7459 } 7460 auto RHS = matchGREVIPat(Op1); 7461 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7462 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7463 DAG.getConstant(LHS->ShAmt, DL, VT)); 7464 } 7465 } 7466 return SDValue(); 7467 } 7468 7469 // Matches any of the following bit-manipulation patterns: 7470 // (and (shl x, 1), (0x22222222 << 1)) 7471 // (and (srl x, 1), 0x22222222) 7472 // (shl (and x, 0x22222222), 1) 7473 // (srl (and x, (0x22222222 << 1)), 1) 7474 // where the shift amount and mask may vary thus: 7475 // [1] = 0x22222222 / 0x44444444 7476 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7477 // [4] = 0x00F000F0 / 0x0F000F00 7478 // [8] = 0x0000FF00 / 0x00FF0000 7479 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7480 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7481 // These are the unshifted masks which we use to match bit-manipulation 7482 // patterns. They may be shifted left in certain circumstances. 7483 static const uint64_t BitmanipMasks[] = { 7484 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7485 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7486 7487 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7488 } 7489 7490 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7491 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7492 const RISCVSubtarget &Subtarget) { 7493 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7494 EVT VT = Op.getValueType(); 7495 7496 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7497 return SDValue(); 7498 7499 SDValue Op0 = Op.getOperand(0); 7500 SDValue Op1 = Op.getOperand(1); 7501 7502 // Or is commutable so canonicalize the second OR to the LHS. 7503 if (Op0.getOpcode() != ISD::OR) 7504 std::swap(Op0, Op1); 7505 if (Op0.getOpcode() != ISD::OR) 7506 return SDValue(); 7507 7508 // We found an inner OR, so our operands are the operands of the inner OR 7509 // and the other operand of the outer OR. 7510 SDValue A = Op0.getOperand(0); 7511 SDValue B = Op0.getOperand(1); 7512 SDValue C = Op1; 7513 7514 auto Match1 = matchSHFLPat(A); 7515 auto Match2 = matchSHFLPat(B); 7516 7517 // If neither matched, we failed. 7518 if (!Match1 && !Match2) 7519 return SDValue(); 7520 7521 // We had at least one match. if one failed, try the remaining C operand. 7522 if (!Match1) { 7523 std::swap(A, C); 7524 Match1 = matchSHFLPat(A); 7525 if (!Match1) 7526 return SDValue(); 7527 } else if (!Match2) { 7528 std::swap(B, C); 7529 Match2 = matchSHFLPat(B); 7530 if (!Match2) 7531 return SDValue(); 7532 } 7533 assert(Match1 && Match2); 7534 7535 // Make sure our matches pair up. 7536 if (!Match1->formsPairWith(*Match2)) 7537 return SDValue(); 7538 7539 // All the remains is to make sure C is an AND with the same input, that masks 7540 // out the bits that are being shuffled. 7541 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7542 C.getOperand(0) != Match1->Op) 7543 return SDValue(); 7544 7545 uint64_t Mask = C.getConstantOperandVal(1); 7546 7547 static const uint64_t BitmanipMasks[] = { 7548 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7549 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7550 }; 7551 7552 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7553 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7554 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7555 7556 if (Mask != ExpMask) 7557 return SDValue(); 7558 7559 SDLoc DL(Op); 7560 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7561 DAG.getConstant(Match1->ShAmt, DL, VT)); 7562 } 7563 7564 // Optimize (add (shl x, c0), (shl y, c1)) -> 7565 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7566 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7567 const RISCVSubtarget &Subtarget) { 7568 // Perform this optimization only in the zba extension. 7569 if (!Subtarget.hasStdExtZba()) 7570 return SDValue(); 7571 7572 // Skip for vector types and larger types. 7573 EVT VT = N->getValueType(0); 7574 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7575 return SDValue(); 7576 7577 // The two operand nodes must be SHL and have no other use. 7578 SDValue N0 = N->getOperand(0); 7579 SDValue N1 = N->getOperand(1); 7580 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7581 !N0->hasOneUse() || !N1->hasOneUse()) 7582 return SDValue(); 7583 7584 // Check c0 and c1. 7585 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7586 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7587 if (!N0C || !N1C) 7588 return SDValue(); 7589 int64_t C0 = N0C->getSExtValue(); 7590 int64_t C1 = N1C->getSExtValue(); 7591 if (C0 <= 0 || C1 <= 0) 7592 return SDValue(); 7593 7594 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7595 int64_t Bits = std::min(C0, C1); 7596 int64_t Diff = std::abs(C0 - C1); 7597 if (Diff != 1 && Diff != 2 && Diff != 3) 7598 return SDValue(); 7599 7600 // Build nodes. 7601 SDLoc DL(N); 7602 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7603 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7604 SDValue NA0 = 7605 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7606 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7607 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7608 } 7609 7610 // Combine 7611 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7612 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7613 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7614 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7615 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7616 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7617 // The grev patterns represents BSWAP. 7618 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7619 // off the grev. 7620 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7621 const RISCVSubtarget &Subtarget) { 7622 bool IsWInstruction = 7623 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7624 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7625 IsWInstruction) && 7626 "Unexpected opcode!"); 7627 SDValue Src = N->getOperand(0); 7628 EVT VT = N->getValueType(0); 7629 SDLoc DL(N); 7630 7631 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7632 return SDValue(); 7633 7634 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7635 !isa<ConstantSDNode>(Src.getOperand(1))) 7636 return SDValue(); 7637 7638 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7639 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7640 7641 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7642 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7643 unsigned ShAmt1 = N->getConstantOperandVal(1); 7644 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7645 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7646 return SDValue(); 7647 7648 Src = Src.getOperand(0); 7649 7650 // Toggle bit the MSB of the shift. 7651 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7652 if (CombinedShAmt == 0) 7653 return Src; 7654 7655 SDValue Res = DAG.getNode( 7656 RISCVISD::GREV, DL, VT, Src, 7657 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7658 if (!IsWInstruction) 7659 return Res; 7660 7661 // Sign extend the result to match the behavior of the rotate. This will be 7662 // selected to GREVIW in isel. 7663 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7664 DAG.getValueType(MVT::i32)); 7665 } 7666 7667 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7668 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7669 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7670 // not undo itself, but they are redundant. 7671 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7672 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7673 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7674 SDValue Src = N->getOperand(0); 7675 7676 if (Src.getOpcode() != N->getOpcode()) 7677 return SDValue(); 7678 7679 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7680 !isa<ConstantSDNode>(Src.getOperand(1))) 7681 return SDValue(); 7682 7683 unsigned ShAmt1 = N->getConstantOperandVal(1); 7684 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7685 Src = Src.getOperand(0); 7686 7687 unsigned CombinedShAmt; 7688 if (IsGORC) 7689 CombinedShAmt = ShAmt1 | ShAmt2; 7690 else 7691 CombinedShAmt = ShAmt1 ^ ShAmt2; 7692 7693 if (CombinedShAmt == 0) 7694 return Src; 7695 7696 SDLoc DL(N); 7697 return DAG.getNode( 7698 N->getOpcode(), DL, N->getValueType(0), Src, 7699 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7700 } 7701 7702 // Combine a constant select operand into its use: 7703 // 7704 // (and (select cond, -1, c), x) 7705 // -> (select cond, x, (and x, c)) [AllOnes=1] 7706 // (or (select cond, 0, c), x) 7707 // -> (select cond, x, (or x, c)) [AllOnes=0] 7708 // (xor (select cond, 0, c), x) 7709 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7710 // (add (select cond, 0, c), x) 7711 // -> (select cond, x, (add x, c)) [AllOnes=0] 7712 // (sub x, (select cond, 0, c)) 7713 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7714 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7715 SelectionDAG &DAG, bool AllOnes) { 7716 EVT VT = N->getValueType(0); 7717 7718 // Skip vectors. 7719 if (VT.isVector()) 7720 return SDValue(); 7721 7722 if ((Slct.getOpcode() != ISD::SELECT && 7723 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7724 !Slct.hasOneUse()) 7725 return SDValue(); 7726 7727 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7728 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7729 }; 7730 7731 bool SwapSelectOps; 7732 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7733 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7734 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7735 SDValue NonConstantVal; 7736 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7737 SwapSelectOps = false; 7738 NonConstantVal = FalseVal; 7739 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7740 SwapSelectOps = true; 7741 NonConstantVal = TrueVal; 7742 } else 7743 return SDValue(); 7744 7745 // Slct is now know to be the desired identity constant when CC is true. 7746 TrueVal = OtherOp; 7747 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7748 // Unless SwapSelectOps says the condition should be false. 7749 if (SwapSelectOps) 7750 std::swap(TrueVal, FalseVal); 7751 7752 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7753 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7754 {Slct.getOperand(0), Slct.getOperand(1), 7755 Slct.getOperand(2), TrueVal, FalseVal}); 7756 7757 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7758 {Slct.getOperand(0), TrueVal, FalseVal}); 7759 } 7760 7761 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7762 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7763 bool AllOnes) { 7764 SDValue N0 = N->getOperand(0); 7765 SDValue N1 = N->getOperand(1); 7766 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7767 return Result; 7768 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7769 return Result; 7770 return SDValue(); 7771 } 7772 7773 // Transform (add (mul x, c0), c1) -> 7774 // (add (mul (add x, c1/c0), c0), c1%c0). 7775 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7776 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7777 // to an infinite loop in DAGCombine if transformed. 7778 // Or transform (add (mul x, c0), c1) -> 7779 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7780 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7781 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7782 // lead to an infinite loop in DAGCombine if transformed. 7783 // Or transform (add (mul x, c0), c1) -> 7784 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7785 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7786 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7787 // lead to an infinite loop in DAGCombine if transformed. 7788 // Or transform (add (mul x, c0), c1) -> 7789 // (mul (add x, c1/c0), c0). 7790 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7791 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7792 const RISCVSubtarget &Subtarget) { 7793 // Skip for vector types and larger types. 7794 EVT VT = N->getValueType(0); 7795 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7796 return SDValue(); 7797 // The first operand node must be a MUL and has no other use. 7798 SDValue N0 = N->getOperand(0); 7799 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7800 return SDValue(); 7801 // Check if c0 and c1 match above conditions. 7802 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7803 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7804 if (!N0C || !N1C) 7805 return SDValue(); 7806 // If N0C has multiple uses it's possible one of the cases in 7807 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7808 // in an infinite loop. 7809 if (!N0C->hasOneUse()) 7810 return SDValue(); 7811 int64_t C0 = N0C->getSExtValue(); 7812 int64_t C1 = N1C->getSExtValue(); 7813 int64_t CA, CB; 7814 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7815 return SDValue(); 7816 // Search for proper CA (non-zero) and CB that both are simm12. 7817 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7818 !isInt<12>(C0 * (C1 / C0))) { 7819 CA = C1 / C0; 7820 CB = C1 % C0; 7821 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7822 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7823 CA = C1 / C0 + 1; 7824 CB = C1 % C0 - C0; 7825 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7826 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7827 CA = C1 / C0 - 1; 7828 CB = C1 % C0 + C0; 7829 } else 7830 return SDValue(); 7831 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7832 SDLoc DL(N); 7833 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7834 DAG.getConstant(CA, DL, VT)); 7835 SDValue New1 = 7836 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7837 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7838 } 7839 7840 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7841 const RISCVSubtarget &Subtarget) { 7842 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7843 return V; 7844 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7845 return V; 7846 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7847 // (select lhs, rhs, cc, x, (add x, y)) 7848 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7849 } 7850 7851 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7852 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7853 // (select lhs, rhs, cc, x, (sub x, y)) 7854 SDValue N0 = N->getOperand(0); 7855 SDValue N1 = N->getOperand(1); 7856 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7857 } 7858 7859 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7860 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7861 // (select lhs, rhs, cc, x, (and x, y)) 7862 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7863 } 7864 7865 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7866 const RISCVSubtarget &Subtarget) { 7867 if (Subtarget.hasStdExtZbp()) { 7868 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7869 return GREV; 7870 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7871 return GORC; 7872 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7873 return SHFL; 7874 } 7875 7876 // fold (or (select cond, 0, y), x) -> 7877 // (select cond, x, (or x, y)) 7878 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7879 } 7880 7881 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7882 SDValue N0 = N->getOperand(0); 7883 SDValue N1 = N->getOperand(1); 7884 7885 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 7886 // NOTE: Assumes ROL being legal means ROLW is legal. 7887 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7888 if (N0.getOpcode() == RISCVISD::SLLW && 7889 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 7890 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 7891 SDLoc DL(N); 7892 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 7893 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 7894 } 7895 7896 // fold (xor (select cond, 0, y), x) -> 7897 // (select cond, x, (xor x, y)) 7898 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7899 } 7900 7901 static SDValue 7902 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7903 const RISCVSubtarget &Subtarget) { 7904 SDValue Src = N->getOperand(0); 7905 EVT VT = N->getValueType(0); 7906 7907 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7908 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7909 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7910 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7911 Src.getOperand(0)); 7912 7913 // Fold (i64 (sext_inreg (abs X), i32)) -> 7914 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7915 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7916 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7917 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7918 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7919 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7920 // may get combined into an earlier operation so we need to use 7921 // ComputeNumSignBits. 7922 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7923 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7924 // we can't assume that X has 33 sign bits. We must check. 7925 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7926 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7927 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7928 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7929 SDLoc DL(N); 7930 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7931 SDValue Neg = 7932 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7933 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7934 DAG.getValueType(MVT::i32)); 7935 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7936 } 7937 7938 return SDValue(); 7939 } 7940 7941 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7942 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7943 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7944 bool Commute = false) { 7945 assert((N->getOpcode() == RISCVISD::ADD_VL || 7946 N->getOpcode() == RISCVISD::SUB_VL) && 7947 "Unexpected opcode"); 7948 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7949 SDValue Op0 = N->getOperand(0); 7950 SDValue Op1 = N->getOperand(1); 7951 if (Commute) 7952 std::swap(Op0, Op1); 7953 7954 MVT VT = N->getSimpleValueType(0); 7955 7956 // Determine the narrow size for a widening add/sub. 7957 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7958 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7959 VT.getVectorElementCount()); 7960 7961 SDValue Mask = N->getOperand(2); 7962 SDValue VL = N->getOperand(3); 7963 7964 SDLoc DL(N); 7965 7966 // If the RHS is a sext or zext, we can form a widening op. 7967 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7968 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7969 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7970 unsigned ExtOpc = Op1.getOpcode(); 7971 Op1 = Op1.getOperand(0); 7972 // Re-introduce narrower extends if needed. 7973 if (Op1.getValueType() != NarrowVT) 7974 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7975 7976 unsigned WOpc; 7977 if (ExtOpc == RISCVISD::VSEXT_VL) 7978 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7979 else 7980 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7981 7982 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7983 } 7984 7985 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7986 // sext/zext? 7987 7988 return SDValue(); 7989 } 7990 7991 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7992 // vwsub(u).vv/vx. 7993 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7994 SDValue Op0 = N->getOperand(0); 7995 SDValue Op1 = N->getOperand(1); 7996 SDValue Mask = N->getOperand(2); 7997 SDValue VL = N->getOperand(3); 7998 7999 MVT VT = N->getSimpleValueType(0); 8000 MVT NarrowVT = Op1.getSimpleValueType(); 8001 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8002 8003 unsigned VOpc; 8004 switch (N->getOpcode()) { 8005 default: llvm_unreachable("Unexpected opcode"); 8006 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8007 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8008 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8009 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8010 } 8011 8012 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8013 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8014 8015 SDLoc DL(N); 8016 8017 // If the LHS is a sext or zext, we can narrow this op to the same size as 8018 // the RHS. 8019 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8020 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8021 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8022 unsigned ExtOpc = Op0.getOpcode(); 8023 Op0 = Op0.getOperand(0); 8024 // Re-introduce narrower extends if needed. 8025 if (Op0.getValueType() != NarrowVT) 8026 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8027 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8028 } 8029 8030 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8031 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8032 8033 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8034 // to commute and use a vwadd(u).vx instead. 8035 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8036 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8037 Op0 = Op0.getOperand(1); 8038 8039 // See if have enough sign bits or zero bits in the scalar to use a 8040 // widening add/sub by splatting to smaller element size. 8041 unsigned EltBits = VT.getScalarSizeInBits(); 8042 unsigned ScalarBits = Op0.getValueSizeInBits(); 8043 // Make sure we're getting all element bits from the scalar register. 8044 // FIXME: Support implicit sign extension of vmv.v.x? 8045 if (ScalarBits < EltBits) 8046 return SDValue(); 8047 8048 if (IsSigned) { 8049 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8050 return SDValue(); 8051 } else { 8052 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8053 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8054 return SDValue(); 8055 } 8056 8057 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8058 DAG.getUNDEF(NarrowVT), Op0, VL); 8059 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8060 } 8061 8062 return SDValue(); 8063 } 8064 8065 // Try to form VWMUL, VWMULU or VWMULSU. 8066 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8067 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8068 bool Commute) { 8069 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8070 SDValue Op0 = N->getOperand(0); 8071 SDValue Op1 = N->getOperand(1); 8072 if (Commute) 8073 std::swap(Op0, Op1); 8074 8075 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8076 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8077 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8078 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8079 return SDValue(); 8080 8081 SDValue Mask = N->getOperand(2); 8082 SDValue VL = N->getOperand(3); 8083 8084 // Make sure the mask and VL match. 8085 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8086 return SDValue(); 8087 8088 MVT VT = N->getSimpleValueType(0); 8089 8090 // Determine the narrow size for a widening multiply. 8091 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8092 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8093 VT.getVectorElementCount()); 8094 8095 SDLoc DL(N); 8096 8097 // See if the other operand is the same opcode. 8098 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8099 if (!Op1.hasOneUse()) 8100 return SDValue(); 8101 8102 // Make sure the mask and VL match. 8103 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8104 return SDValue(); 8105 8106 Op1 = Op1.getOperand(0); 8107 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8108 // The operand is a splat of a scalar. 8109 8110 // The pasthru must be undef for tail agnostic 8111 if (!Op1.getOperand(0).isUndef()) 8112 return SDValue(); 8113 // The VL must be the same. 8114 if (Op1.getOperand(2) != VL) 8115 return SDValue(); 8116 8117 // Get the scalar value. 8118 Op1 = Op1.getOperand(1); 8119 8120 // See if have enough sign bits or zero bits in the scalar to use a 8121 // widening multiply by splatting to smaller element size. 8122 unsigned EltBits = VT.getScalarSizeInBits(); 8123 unsigned ScalarBits = Op1.getValueSizeInBits(); 8124 // Make sure we're getting all element bits from the scalar register. 8125 // FIXME: Support implicit sign extension of vmv.v.x? 8126 if (ScalarBits < EltBits) 8127 return SDValue(); 8128 8129 // If the LHS is a sign extend, try to use vwmul. 8130 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8131 // Can use vwmul. 8132 } else { 8133 // Otherwise try to use vwmulu or vwmulsu. 8134 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8135 if (DAG.MaskedValueIsZero(Op1, Mask)) 8136 IsVWMULSU = IsSignExt; 8137 else 8138 return SDValue(); 8139 } 8140 8141 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8142 DAG.getUNDEF(NarrowVT), Op1, VL); 8143 } else 8144 return SDValue(); 8145 8146 Op0 = Op0.getOperand(0); 8147 8148 // Re-introduce narrower extends if needed. 8149 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8150 if (Op0.getValueType() != NarrowVT) 8151 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8152 // vwmulsu requires second operand to be zero extended. 8153 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8154 if (Op1.getValueType() != NarrowVT) 8155 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8156 8157 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8158 if (!IsVWMULSU) 8159 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8160 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8161 } 8162 8163 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8164 switch (Op.getOpcode()) { 8165 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8166 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8167 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8168 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8169 case ISD::FROUND: return RISCVFPRndMode::RMM; 8170 } 8171 8172 return RISCVFPRndMode::Invalid; 8173 } 8174 8175 // Fold 8176 // (fp_to_int (froundeven X)) -> fcvt X, rne 8177 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8178 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8179 // (fp_to_int (fceil X)) -> fcvt X, rup 8180 // (fp_to_int (fround X)) -> fcvt X, rmm 8181 static SDValue performFP_TO_INTCombine(SDNode *N, 8182 TargetLowering::DAGCombinerInfo &DCI, 8183 const RISCVSubtarget &Subtarget) { 8184 SelectionDAG &DAG = DCI.DAG; 8185 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8186 MVT XLenVT = Subtarget.getXLenVT(); 8187 8188 // Only handle XLen or i32 types. Other types narrower than XLen will 8189 // eventually be legalized to XLenVT. 8190 EVT VT = N->getValueType(0); 8191 if (VT != MVT::i32 && VT != XLenVT) 8192 return SDValue(); 8193 8194 SDValue Src = N->getOperand(0); 8195 8196 // Ensure the FP type is also legal. 8197 if (!TLI.isTypeLegal(Src.getValueType())) 8198 return SDValue(); 8199 8200 // Don't do this for f16 with Zfhmin and not Zfh. 8201 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8202 return SDValue(); 8203 8204 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8205 if (FRM == RISCVFPRndMode::Invalid) 8206 return SDValue(); 8207 8208 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8209 8210 unsigned Opc; 8211 if (VT == XLenVT) 8212 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8213 else 8214 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8215 8216 SDLoc DL(N); 8217 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8218 DAG.getTargetConstant(FRM, DL, XLenVT)); 8219 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8220 } 8221 8222 // Fold 8223 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8224 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8225 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8226 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8227 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8228 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8229 TargetLowering::DAGCombinerInfo &DCI, 8230 const RISCVSubtarget &Subtarget) { 8231 SelectionDAG &DAG = DCI.DAG; 8232 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8233 MVT XLenVT = Subtarget.getXLenVT(); 8234 8235 // Only handle XLen types. Other types narrower than XLen will eventually be 8236 // legalized to XLenVT. 8237 EVT DstVT = N->getValueType(0); 8238 if (DstVT != XLenVT) 8239 return SDValue(); 8240 8241 SDValue Src = N->getOperand(0); 8242 8243 // Ensure the FP type is also legal. 8244 if (!TLI.isTypeLegal(Src.getValueType())) 8245 return SDValue(); 8246 8247 // Don't do this for f16 with Zfhmin and not Zfh. 8248 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8249 return SDValue(); 8250 8251 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8252 8253 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8254 if (FRM == RISCVFPRndMode::Invalid) 8255 return SDValue(); 8256 8257 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8258 8259 unsigned Opc; 8260 if (SatVT == DstVT) 8261 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8262 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8263 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8264 else 8265 return SDValue(); 8266 // FIXME: Support other SatVTs by clamping before or after the conversion. 8267 8268 Src = Src.getOperand(0); 8269 8270 SDLoc DL(N); 8271 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8272 DAG.getTargetConstant(FRM, DL, XLenVT)); 8273 8274 // RISCV FP-to-int conversions saturate to the destination register size, but 8275 // don't produce 0 for nan. 8276 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8277 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8278 } 8279 8280 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8281 // smaller than XLenVT. 8282 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8283 const RISCVSubtarget &Subtarget) { 8284 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8285 8286 SDValue Src = N->getOperand(0); 8287 if (Src.getOpcode() != ISD::BSWAP) 8288 return SDValue(); 8289 8290 EVT VT = N->getValueType(0); 8291 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8292 !isPowerOf2_32(VT.getSizeInBits())) 8293 return SDValue(); 8294 8295 SDLoc DL(N); 8296 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8297 DAG.getConstant(7, DL, VT)); 8298 } 8299 8300 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8301 DAGCombinerInfo &DCI) const { 8302 SelectionDAG &DAG = DCI.DAG; 8303 8304 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8305 // bits are demanded. N will be added to the Worklist if it was not deleted. 8306 // Caller should return SDValue(N, 0) if this returns true. 8307 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8308 SDValue Op = N->getOperand(OpNo); 8309 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8310 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8311 return false; 8312 8313 if (N->getOpcode() != ISD::DELETED_NODE) 8314 DCI.AddToWorklist(N); 8315 return true; 8316 }; 8317 8318 switch (N->getOpcode()) { 8319 default: 8320 break; 8321 case RISCVISD::SplitF64: { 8322 SDValue Op0 = N->getOperand(0); 8323 // If the input to SplitF64 is just BuildPairF64 then the operation is 8324 // redundant. Instead, use BuildPairF64's operands directly. 8325 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8326 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8327 8328 if (Op0->isUndef()) { 8329 SDValue Lo = DAG.getUNDEF(MVT::i32); 8330 SDValue Hi = DAG.getUNDEF(MVT::i32); 8331 return DCI.CombineTo(N, Lo, Hi); 8332 } 8333 8334 SDLoc DL(N); 8335 8336 // It's cheaper to materialise two 32-bit integers than to load a double 8337 // from the constant pool and transfer it to integer registers through the 8338 // stack. 8339 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8340 APInt V = C->getValueAPF().bitcastToAPInt(); 8341 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8342 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8343 return DCI.CombineTo(N, Lo, Hi); 8344 } 8345 8346 // This is a target-specific version of a DAGCombine performed in 8347 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8348 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8349 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8350 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8351 !Op0.getNode()->hasOneUse()) 8352 break; 8353 SDValue NewSplitF64 = 8354 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8355 Op0.getOperand(0)); 8356 SDValue Lo = NewSplitF64.getValue(0); 8357 SDValue Hi = NewSplitF64.getValue(1); 8358 APInt SignBit = APInt::getSignMask(32); 8359 if (Op0.getOpcode() == ISD::FNEG) { 8360 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8361 DAG.getConstant(SignBit, DL, MVT::i32)); 8362 return DCI.CombineTo(N, Lo, NewHi); 8363 } 8364 assert(Op0.getOpcode() == ISD::FABS); 8365 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8366 DAG.getConstant(~SignBit, DL, MVT::i32)); 8367 return DCI.CombineTo(N, Lo, NewHi); 8368 } 8369 case RISCVISD::SLLW: 8370 case RISCVISD::SRAW: 8371 case RISCVISD::SRLW: { 8372 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8373 if (SimplifyDemandedLowBitsHelper(0, 32) || 8374 SimplifyDemandedLowBitsHelper(1, 5)) 8375 return SDValue(N, 0); 8376 8377 break; 8378 } 8379 case ISD::ROTR: 8380 case ISD::ROTL: 8381 case RISCVISD::RORW: 8382 case RISCVISD::ROLW: { 8383 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8384 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8385 if (SimplifyDemandedLowBitsHelper(0, 32) || 8386 SimplifyDemandedLowBitsHelper(1, 5)) 8387 return SDValue(N, 0); 8388 } 8389 8390 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8391 } 8392 case RISCVISD::CLZW: 8393 case RISCVISD::CTZW: { 8394 // Only the lower 32 bits of the first operand are read 8395 if (SimplifyDemandedLowBitsHelper(0, 32)) 8396 return SDValue(N, 0); 8397 break; 8398 } 8399 case RISCVISD::GREV: 8400 case RISCVISD::GORC: { 8401 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8402 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8403 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8404 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8405 return SDValue(N, 0); 8406 8407 return combineGREVI_GORCI(N, DAG); 8408 } 8409 case RISCVISD::GREVW: 8410 case RISCVISD::GORCW: { 8411 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8412 if (SimplifyDemandedLowBitsHelper(0, 32) || 8413 SimplifyDemandedLowBitsHelper(1, 5)) 8414 return SDValue(N, 0); 8415 8416 break; 8417 } 8418 case RISCVISD::SHFL: 8419 case RISCVISD::UNSHFL: { 8420 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8421 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8422 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8423 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8424 return SDValue(N, 0); 8425 8426 break; 8427 } 8428 case RISCVISD::SHFLW: 8429 case RISCVISD::UNSHFLW: { 8430 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8431 if (SimplifyDemandedLowBitsHelper(0, 32) || 8432 SimplifyDemandedLowBitsHelper(1, 4)) 8433 return SDValue(N, 0); 8434 8435 break; 8436 } 8437 case RISCVISD::BCOMPRESSW: 8438 case RISCVISD::BDECOMPRESSW: { 8439 // Only the lower 32 bits of LHS and RHS are read. 8440 if (SimplifyDemandedLowBitsHelper(0, 32) || 8441 SimplifyDemandedLowBitsHelper(1, 32)) 8442 return SDValue(N, 0); 8443 8444 break; 8445 } 8446 case RISCVISD::FSR: 8447 case RISCVISD::FSL: 8448 case RISCVISD::FSRW: 8449 case RISCVISD::FSLW: { 8450 bool IsWInstruction = 8451 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8452 unsigned BitWidth = 8453 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8454 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8455 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8456 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8457 return SDValue(N, 0); 8458 8459 break; 8460 } 8461 case RISCVISD::FMV_X_ANYEXTH: 8462 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8463 SDLoc DL(N); 8464 SDValue Op0 = N->getOperand(0); 8465 MVT VT = N->getSimpleValueType(0); 8466 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8467 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8468 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8469 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8470 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8471 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8472 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8473 assert(Op0.getOperand(0).getValueType() == VT && 8474 "Unexpected value type!"); 8475 return Op0.getOperand(0); 8476 } 8477 8478 // This is a target-specific version of a DAGCombine performed in 8479 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8480 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8481 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8482 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8483 !Op0.getNode()->hasOneUse()) 8484 break; 8485 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8486 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8487 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8488 if (Op0.getOpcode() == ISD::FNEG) 8489 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8490 DAG.getConstant(SignBit, DL, VT)); 8491 8492 assert(Op0.getOpcode() == ISD::FABS); 8493 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8494 DAG.getConstant(~SignBit, DL, VT)); 8495 } 8496 case ISD::ADD: 8497 return performADDCombine(N, DAG, Subtarget); 8498 case ISD::SUB: 8499 return performSUBCombine(N, DAG); 8500 case ISD::AND: 8501 return performANDCombine(N, DAG); 8502 case ISD::OR: 8503 return performORCombine(N, DAG, Subtarget); 8504 case ISD::XOR: 8505 return performXORCombine(N, DAG); 8506 case ISD::SIGN_EXTEND_INREG: 8507 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8508 case ISD::ZERO_EXTEND: 8509 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8510 // type legalization. This is safe because fp_to_uint produces poison if 8511 // it overflows. 8512 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8513 SDValue Src = N->getOperand(0); 8514 if (Src.getOpcode() == ISD::FP_TO_UINT && 8515 isTypeLegal(Src.getOperand(0).getValueType())) 8516 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8517 Src.getOperand(0)); 8518 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8519 isTypeLegal(Src.getOperand(1).getValueType())) { 8520 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8521 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8522 Src.getOperand(0), Src.getOperand(1)); 8523 DCI.CombineTo(N, Res); 8524 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8525 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8526 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8527 } 8528 } 8529 return SDValue(); 8530 case RISCVISD::SELECT_CC: { 8531 // Transform 8532 SDValue LHS = N->getOperand(0); 8533 SDValue RHS = N->getOperand(1); 8534 SDValue TrueV = N->getOperand(3); 8535 SDValue FalseV = N->getOperand(4); 8536 8537 // If the True and False values are the same, we don't need a select_cc. 8538 if (TrueV == FalseV) 8539 return TrueV; 8540 8541 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8542 if (!ISD::isIntEqualitySetCC(CCVal)) 8543 break; 8544 8545 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8546 // (select_cc X, Y, lt, trueV, falseV) 8547 // Sometimes the setcc is introduced after select_cc has been formed. 8548 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8549 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8550 // If we're looking for eq 0 instead of ne 0, we need to invert the 8551 // condition. 8552 bool Invert = CCVal == ISD::SETEQ; 8553 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8554 if (Invert) 8555 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8556 8557 SDLoc DL(N); 8558 RHS = LHS.getOperand(1); 8559 LHS = LHS.getOperand(0); 8560 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8561 8562 SDValue TargetCC = DAG.getCondCode(CCVal); 8563 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8564 {LHS, RHS, TargetCC, TrueV, FalseV}); 8565 } 8566 8567 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8568 // (select_cc X, Y, eq/ne, trueV, falseV) 8569 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8570 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8571 {LHS.getOperand(0), LHS.getOperand(1), 8572 N->getOperand(2), TrueV, FalseV}); 8573 // (select_cc X, 1, setne, trueV, falseV) -> 8574 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8575 // This can occur when legalizing some floating point comparisons. 8576 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8577 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8578 SDLoc DL(N); 8579 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8580 SDValue TargetCC = DAG.getCondCode(CCVal); 8581 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8582 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8583 {LHS, RHS, TargetCC, TrueV, FalseV}); 8584 } 8585 8586 break; 8587 } 8588 case RISCVISD::BR_CC: { 8589 SDValue LHS = N->getOperand(1); 8590 SDValue RHS = N->getOperand(2); 8591 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8592 if (!ISD::isIntEqualitySetCC(CCVal)) 8593 break; 8594 8595 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8596 // (br_cc X, Y, lt, dest) 8597 // Sometimes the setcc is introduced after br_cc has been formed. 8598 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8599 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8600 // If we're looking for eq 0 instead of ne 0, we need to invert the 8601 // condition. 8602 bool Invert = CCVal == ISD::SETEQ; 8603 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8604 if (Invert) 8605 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8606 8607 SDLoc DL(N); 8608 RHS = LHS.getOperand(1); 8609 LHS = LHS.getOperand(0); 8610 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8611 8612 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8613 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8614 N->getOperand(4)); 8615 } 8616 8617 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8618 // (br_cc X, Y, eq/ne, trueV, falseV) 8619 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8620 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8621 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8622 N->getOperand(3), N->getOperand(4)); 8623 8624 // (br_cc X, 1, setne, br_cc) -> 8625 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8626 // This can occur when legalizing some floating point comparisons. 8627 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8628 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8629 SDLoc DL(N); 8630 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8631 SDValue TargetCC = DAG.getCondCode(CCVal); 8632 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8633 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8634 N->getOperand(0), LHS, RHS, TargetCC, 8635 N->getOperand(4)); 8636 } 8637 break; 8638 } 8639 case ISD::BITREVERSE: 8640 return performBITREVERSECombine(N, DAG, Subtarget); 8641 case ISD::FP_TO_SINT: 8642 case ISD::FP_TO_UINT: 8643 return performFP_TO_INTCombine(N, DCI, Subtarget); 8644 case ISD::FP_TO_SINT_SAT: 8645 case ISD::FP_TO_UINT_SAT: 8646 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8647 case ISD::FCOPYSIGN: { 8648 EVT VT = N->getValueType(0); 8649 if (!VT.isVector()) 8650 break; 8651 // There is a form of VFSGNJ which injects the negated sign of its second 8652 // operand. Try and bubble any FNEG up after the extend/round to produce 8653 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8654 // TRUNC=1. 8655 SDValue In2 = N->getOperand(1); 8656 // Avoid cases where the extend/round has multiple uses, as duplicating 8657 // those is typically more expensive than removing a fneg. 8658 if (!In2.hasOneUse()) 8659 break; 8660 if (In2.getOpcode() != ISD::FP_EXTEND && 8661 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8662 break; 8663 In2 = In2.getOperand(0); 8664 if (In2.getOpcode() != ISD::FNEG) 8665 break; 8666 SDLoc DL(N); 8667 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8668 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8669 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8670 } 8671 case ISD::MGATHER: 8672 case ISD::MSCATTER: 8673 case ISD::VP_GATHER: 8674 case ISD::VP_SCATTER: { 8675 if (!DCI.isBeforeLegalize()) 8676 break; 8677 SDValue Index, ScaleOp; 8678 bool IsIndexScaled = false; 8679 bool IsIndexSigned = false; 8680 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8681 Index = VPGSN->getIndex(); 8682 ScaleOp = VPGSN->getScale(); 8683 IsIndexScaled = VPGSN->isIndexScaled(); 8684 IsIndexSigned = VPGSN->isIndexSigned(); 8685 } else { 8686 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8687 Index = MGSN->getIndex(); 8688 ScaleOp = MGSN->getScale(); 8689 IsIndexScaled = MGSN->isIndexScaled(); 8690 IsIndexSigned = MGSN->isIndexSigned(); 8691 } 8692 EVT IndexVT = Index.getValueType(); 8693 MVT XLenVT = Subtarget.getXLenVT(); 8694 // RISCV indexed loads only support the "unsigned unscaled" addressing 8695 // mode, so anything else must be manually legalized. 8696 bool NeedsIdxLegalization = 8697 IsIndexScaled || 8698 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8699 if (!NeedsIdxLegalization) 8700 break; 8701 8702 SDLoc DL(N); 8703 8704 // Any index legalization should first promote to XLenVT, so we don't lose 8705 // bits when scaling. This may create an illegal index type so we let 8706 // LLVM's legalization take care of the splitting. 8707 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8708 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8709 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8710 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8711 DL, IndexVT, Index); 8712 } 8713 8714 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8715 if (IsIndexScaled && Scale != 1) { 8716 // Manually scale the indices by the element size. 8717 // TODO: Sanitize the scale operand here? 8718 // TODO: For VP nodes, should we use VP_SHL here? 8719 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8720 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8721 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8722 } 8723 8724 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8725 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8726 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8727 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8728 VPGN->getScale(), VPGN->getMask(), 8729 VPGN->getVectorLength()}, 8730 VPGN->getMemOperand(), NewIndexTy); 8731 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8732 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8733 {VPSN->getChain(), VPSN->getValue(), 8734 VPSN->getBasePtr(), Index, VPSN->getScale(), 8735 VPSN->getMask(), VPSN->getVectorLength()}, 8736 VPSN->getMemOperand(), NewIndexTy); 8737 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8738 return DAG.getMaskedGather( 8739 N->getVTList(), MGN->getMemoryVT(), DL, 8740 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8741 MGN->getBasePtr(), Index, MGN->getScale()}, 8742 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8743 const auto *MSN = cast<MaskedScatterSDNode>(N); 8744 return DAG.getMaskedScatter( 8745 N->getVTList(), MSN->getMemoryVT(), DL, 8746 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8747 Index, MSN->getScale()}, 8748 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8749 } 8750 case RISCVISD::SRA_VL: 8751 case RISCVISD::SRL_VL: 8752 case RISCVISD::SHL_VL: { 8753 SDValue ShAmt = N->getOperand(1); 8754 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8755 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8756 SDLoc DL(N); 8757 SDValue VL = N->getOperand(3); 8758 EVT VT = N->getValueType(0); 8759 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8760 ShAmt.getOperand(1), VL); 8761 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8762 N->getOperand(2), N->getOperand(3)); 8763 } 8764 break; 8765 } 8766 case ISD::SRA: 8767 case ISD::SRL: 8768 case ISD::SHL: { 8769 SDValue ShAmt = N->getOperand(1); 8770 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8771 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8772 SDLoc DL(N); 8773 EVT VT = N->getValueType(0); 8774 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8775 ShAmt.getOperand(1), 8776 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8777 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8778 } 8779 break; 8780 } 8781 case RISCVISD::ADD_VL: 8782 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8783 return V; 8784 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8785 case RISCVISD::SUB_VL: 8786 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8787 case RISCVISD::VWADD_W_VL: 8788 case RISCVISD::VWADDU_W_VL: 8789 case RISCVISD::VWSUB_W_VL: 8790 case RISCVISD::VWSUBU_W_VL: 8791 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8792 case RISCVISD::MUL_VL: 8793 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8794 return V; 8795 // Mul is commutative. 8796 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8797 case ISD::STORE: { 8798 auto *Store = cast<StoreSDNode>(N); 8799 SDValue Val = Store->getValue(); 8800 // Combine store of vmv.x.s to vse with VL of 1. 8801 // FIXME: Support FP. 8802 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8803 SDValue Src = Val.getOperand(0); 8804 EVT VecVT = Src.getValueType(); 8805 EVT MemVT = Store->getMemoryVT(); 8806 // The memory VT and the element type must match. 8807 if (VecVT.getVectorElementType() == MemVT) { 8808 SDLoc DL(N); 8809 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8810 return DAG.getStoreVP( 8811 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8812 DAG.getConstant(1, DL, MaskVT), 8813 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8814 Store->getMemOperand(), Store->getAddressingMode(), 8815 Store->isTruncatingStore(), /*IsCompress*/ false); 8816 } 8817 } 8818 8819 break; 8820 } 8821 case ISD::SPLAT_VECTOR: { 8822 EVT VT = N->getValueType(0); 8823 // Only perform this combine on legal MVT types. 8824 if (!isTypeLegal(VT)) 8825 break; 8826 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8827 DAG, Subtarget)) 8828 return Gather; 8829 break; 8830 } 8831 case RISCVISD::VMV_V_X_VL: { 8832 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8833 // scalar input. 8834 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8835 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8836 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8837 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8838 return SDValue(N, 0); 8839 8840 break; 8841 } 8842 case ISD::INTRINSIC_WO_CHAIN: { 8843 unsigned IntNo = N->getConstantOperandVal(0); 8844 switch (IntNo) { 8845 // By default we do not combine any intrinsic. 8846 default: 8847 return SDValue(); 8848 case Intrinsic::riscv_vcpop: 8849 case Intrinsic::riscv_vcpop_mask: 8850 case Intrinsic::riscv_vfirst: 8851 case Intrinsic::riscv_vfirst_mask: { 8852 SDValue VL = N->getOperand(2); 8853 if (IntNo == Intrinsic::riscv_vcpop_mask || 8854 IntNo == Intrinsic::riscv_vfirst_mask) 8855 VL = N->getOperand(3); 8856 if (!isNullConstant(VL)) 8857 return SDValue(); 8858 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8859 SDLoc DL(N); 8860 EVT VT = N->getValueType(0); 8861 if (IntNo == Intrinsic::riscv_vfirst || 8862 IntNo == Intrinsic::riscv_vfirst_mask) 8863 return DAG.getConstant(-1, DL, VT); 8864 return DAG.getConstant(0, DL, VT); 8865 } 8866 } 8867 } 8868 } 8869 8870 return SDValue(); 8871 } 8872 8873 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8874 const SDNode *N, CombineLevel Level) const { 8875 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8876 // materialised in fewer instructions than `(OP _, c1)`: 8877 // 8878 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8879 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8880 SDValue N0 = N->getOperand(0); 8881 EVT Ty = N0.getValueType(); 8882 if (Ty.isScalarInteger() && 8883 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8884 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8885 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8886 if (C1 && C2) { 8887 const APInt &C1Int = C1->getAPIntValue(); 8888 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8889 8890 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8891 // and the combine should happen, to potentially allow further combines 8892 // later. 8893 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8894 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8895 return true; 8896 8897 // We can materialise `c1` in an add immediate, so it's "free", and the 8898 // combine should be prevented. 8899 if (C1Int.getMinSignedBits() <= 64 && 8900 isLegalAddImmediate(C1Int.getSExtValue())) 8901 return false; 8902 8903 // Neither constant will fit into an immediate, so find materialisation 8904 // costs. 8905 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8906 Subtarget.getFeatureBits(), 8907 /*CompressionCost*/true); 8908 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8909 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8910 /*CompressionCost*/true); 8911 8912 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8913 // combine should be prevented. 8914 if (C1Cost < ShiftedC1Cost) 8915 return false; 8916 } 8917 } 8918 return true; 8919 } 8920 8921 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8922 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8923 TargetLoweringOpt &TLO) const { 8924 // Delay this optimization as late as possible. 8925 if (!TLO.LegalOps) 8926 return false; 8927 8928 EVT VT = Op.getValueType(); 8929 if (VT.isVector()) 8930 return false; 8931 8932 // Only handle AND for now. 8933 if (Op.getOpcode() != ISD::AND) 8934 return false; 8935 8936 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8937 if (!C) 8938 return false; 8939 8940 const APInt &Mask = C->getAPIntValue(); 8941 8942 // Clear all non-demanded bits initially. 8943 APInt ShrunkMask = Mask & DemandedBits; 8944 8945 // Try to make a smaller immediate by setting undemanded bits. 8946 8947 APInt ExpandedMask = Mask | ~DemandedBits; 8948 8949 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8950 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8951 }; 8952 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8953 if (NewMask == Mask) 8954 return true; 8955 SDLoc DL(Op); 8956 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8957 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8958 return TLO.CombineTo(Op, NewOp); 8959 }; 8960 8961 // If the shrunk mask fits in sign extended 12 bits, let the target 8962 // independent code apply it. 8963 if (ShrunkMask.isSignedIntN(12)) 8964 return false; 8965 8966 // Preserve (and X, 0xffff) when zext.h is supported. 8967 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8968 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8969 if (IsLegalMask(NewMask)) 8970 return UseMask(NewMask); 8971 } 8972 8973 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8974 if (VT == MVT::i64) { 8975 APInt NewMask = APInt(64, 0xffffffff); 8976 if (IsLegalMask(NewMask)) 8977 return UseMask(NewMask); 8978 } 8979 8980 // For the remaining optimizations, we need to be able to make a negative 8981 // number through a combination of mask and undemanded bits. 8982 if (!ExpandedMask.isNegative()) 8983 return false; 8984 8985 // What is the fewest number of bits we need to represent the negative number. 8986 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8987 8988 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8989 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8990 APInt NewMask = ShrunkMask; 8991 if (MinSignedBits <= 12) 8992 NewMask.setBitsFrom(11); 8993 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8994 NewMask.setBitsFrom(31); 8995 else 8996 return false; 8997 8998 // Check that our new mask is a subset of the demanded mask. 8999 assert(IsLegalMask(NewMask)); 9000 return UseMask(NewMask); 9001 } 9002 9003 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9004 static const uint64_t GREVMasks[] = { 9005 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9006 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9007 9008 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9009 unsigned Shift = 1 << Stage; 9010 if (ShAmt & Shift) { 9011 uint64_t Mask = GREVMasks[Stage]; 9012 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9013 if (IsGORC) 9014 Res |= x; 9015 x = Res; 9016 } 9017 } 9018 9019 return x; 9020 } 9021 9022 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9023 KnownBits &Known, 9024 const APInt &DemandedElts, 9025 const SelectionDAG &DAG, 9026 unsigned Depth) const { 9027 unsigned BitWidth = Known.getBitWidth(); 9028 unsigned Opc = Op.getOpcode(); 9029 assert((Opc >= ISD::BUILTIN_OP_END || 9030 Opc == ISD::INTRINSIC_WO_CHAIN || 9031 Opc == ISD::INTRINSIC_W_CHAIN || 9032 Opc == ISD::INTRINSIC_VOID) && 9033 "Should use MaskedValueIsZero if you don't know whether Op" 9034 " is a target node!"); 9035 9036 Known.resetAll(); 9037 switch (Opc) { 9038 default: break; 9039 case RISCVISD::SELECT_CC: { 9040 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9041 // If we don't know any bits, early out. 9042 if (Known.isUnknown()) 9043 break; 9044 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9045 9046 // Only known if known in both the LHS and RHS. 9047 Known = KnownBits::commonBits(Known, Known2); 9048 break; 9049 } 9050 case RISCVISD::REMUW: { 9051 KnownBits Known2; 9052 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9053 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9054 // We only care about the lower 32 bits. 9055 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9056 // Restore the original width by sign extending. 9057 Known = Known.sext(BitWidth); 9058 break; 9059 } 9060 case RISCVISD::DIVUW: { 9061 KnownBits Known2; 9062 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9063 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9064 // We only care about the lower 32 bits. 9065 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9066 // Restore the original width by sign extending. 9067 Known = Known.sext(BitWidth); 9068 break; 9069 } 9070 case RISCVISD::CTZW: { 9071 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9072 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9073 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9074 Known.Zero.setBitsFrom(LowBits); 9075 break; 9076 } 9077 case RISCVISD::CLZW: { 9078 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9079 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9080 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9081 Known.Zero.setBitsFrom(LowBits); 9082 break; 9083 } 9084 case RISCVISD::GREV: 9085 case RISCVISD::GORC: { 9086 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9087 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9088 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9089 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9090 // To compute zeros, we need to invert the value and invert it back after. 9091 Known.Zero = 9092 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9093 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9094 } 9095 break; 9096 } 9097 case RISCVISD::READ_VLENB: { 9098 // If we know the minimum VLen from Zvl extensions, we can use that to 9099 // determine the trailing zeros of VLENB. 9100 // FIXME: Limit to 128 bit vectors until we have more testing. 9101 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9102 if (MinVLenB > 0) 9103 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9104 // We assume VLENB is no more than 65536 / 8 bytes. 9105 Known.Zero.setBitsFrom(14); 9106 break; 9107 } 9108 case ISD::INTRINSIC_W_CHAIN: 9109 case ISD::INTRINSIC_WO_CHAIN: { 9110 unsigned IntNo = 9111 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9112 switch (IntNo) { 9113 default: 9114 // We can't do anything for most intrinsics. 9115 break; 9116 case Intrinsic::riscv_vsetvli: 9117 case Intrinsic::riscv_vsetvlimax: 9118 case Intrinsic::riscv_vsetvli_opt: 9119 case Intrinsic::riscv_vsetvlimax_opt: 9120 // Assume that VL output is positive and would fit in an int32_t. 9121 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9122 if (BitWidth >= 32) 9123 Known.Zero.setBitsFrom(31); 9124 break; 9125 } 9126 break; 9127 } 9128 } 9129 } 9130 9131 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9132 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9133 unsigned Depth) const { 9134 switch (Op.getOpcode()) { 9135 default: 9136 break; 9137 case RISCVISD::SELECT_CC: { 9138 unsigned Tmp = 9139 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9140 if (Tmp == 1) return 1; // Early out. 9141 unsigned Tmp2 = 9142 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9143 return std::min(Tmp, Tmp2); 9144 } 9145 case RISCVISD::SLLW: 9146 case RISCVISD::SRAW: 9147 case RISCVISD::SRLW: 9148 case RISCVISD::DIVW: 9149 case RISCVISD::DIVUW: 9150 case RISCVISD::REMUW: 9151 case RISCVISD::ROLW: 9152 case RISCVISD::RORW: 9153 case RISCVISD::GREVW: 9154 case RISCVISD::GORCW: 9155 case RISCVISD::FSLW: 9156 case RISCVISD::FSRW: 9157 case RISCVISD::SHFLW: 9158 case RISCVISD::UNSHFLW: 9159 case RISCVISD::BCOMPRESSW: 9160 case RISCVISD::BDECOMPRESSW: 9161 case RISCVISD::BFPW: 9162 case RISCVISD::FCVT_W_RV64: 9163 case RISCVISD::FCVT_WU_RV64: 9164 case RISCVISD::STRICT_FCVT_W_RV64: 9165 case RISCVISD::STRICT_FCVT_WU_RV64: 9166 // TODO: As the result is sign-extended, this is conservatively correct. A 9167 // more precise answer could be calculated for SRAW depending on known 9168 // bits in the shift amount. 9169 return 33; 9170 case RISCVISD::SHFL: 9171 case RISCVISD::UNSHFL: { 9172 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9173 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9174 // will stay within the upper 32 bits. If there were more than 32 sign bits 9175 // before there will be at least 33 sign bits after. 9176 if (Op.getValueType() == MVT::i64 && 9177 isa<ConstantSDNode>(Op.getOperand(1)) && 9178 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9179 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9180 if (Tmp > 32) 9181 return 33; 9182 } 9183 break; 9184 } 9185 case RISCVISD::VMV_X_S: { 9186 // The number of sign bits of the scalar result is computed by obtaining the 9187 // element type of the input vector operand, subtracting its width from the 9188 // XLEN, and then adding one (sign bit within the element type). If the 9189 // element type is wider than XLen, the least-significant XLEN bits are 9190 // taken. 9191 unsigned XLen = Subtarget.getXLen(); 9192 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9193 if (EltBits <= XLen) 9194 return XLen - EltBits + 1; 9195 break; 9196 } 9197 } 9198 9199 return 1; 9200 } 9201 9202 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9203 MachineBasicBlock *BB) { 9204 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9205 9206 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9207 // Should the count have wrapped while it was being read, we need to try 9208 // again. 9209 // ... 9210 // read: 9211 // rdcycleh x3 # load high word of cycle 9212 // rdcycle x2 # load low word of cycle 9213 // rdcycleh x4 # load high word of cycle 9214 // bne x3, x4, read # check if high word reads match, otherwise try again 9215 // ... 9216 9217 MachineFunction &MF = *BB->getParent(); 9218 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9219 MachineFunction::iterator It = ++BB->getIterator(); 9220 9221 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9222 MF.insert(It, LoopMBB); 9223 9224 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9225 MF.insert(It, DoneMBB); 9226 9227 // Transfer the remainder of BB and its successor edges to DoneMBB. 9228 DoneMBB->splice(DoneMBB->begin(), BB, 9229 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9230 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9231 9232 BB->addSuccessor(LoopMBB); 9233 9234 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9235 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9236 Register LoReg = MI.getOperand(0).getReg(); 9237 Register HiReg = MI.getOperand(1).getReg(); 9238 DebugLoc DL = MI.getDebugLoc(); 9239 9240 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9241 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9242 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9243 .addReg(RISCV::X0); 9244 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9245 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9246 .addReg(RISCV::X0); 9247 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9248 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9249 .addReg(RISCV::X0); 9250 9251 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9252 .addReg(HiReg) 9253 .addReg(ReadAgainReg) 9254 .addMBB(LoopMBB); 9255 9256 LoopMBB->addSuccessor(LoopMBB); 9257 LoopMBB->addSuccessor(DoneMBB); 9258 9259 MI.eraseFromParent(); 9260 9261 return DoneMBB; 9262 } 9263 9264 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9265 MachineBasicBlock *BB) { 9266 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9267 9268 MachineFunction &MF = *BB->getParent(); 9269 DebugLoc DL = MI.getDebugLoc(); 9270 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9271 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9272 Register LoReg = MI.getOperand(0).getReg(); 9273 Register HiReg = MI.getOperand(1).getReg(); 9274 Register SrcReg = MI.getOperand(2).getReg(); 9275 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9276 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9277 9278 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9279 RI); 9280 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9281 MachineMemOperand *MMOLo = 9282 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9283 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9284 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9285 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9286 .addFrameIndex(FI) 9287 .addImm(0) 9288 .addMemOperand(MMOLo); 9289 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9290 .addFrameIndex(FI) 9291 .addImm(4) 9292 .addMemOperand(MMOHi); 9293 MI.eraseFromParent(); // The pseudo instruction is gone now. 9294 return BB; 9295 } 9296 9297 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9298 MachineBasicBlock *BB) { 9299 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9300 "Unexpected instruction"); 9301 9302 MachineFunction &MF = *BB->getParent(); 9303 DebugLoc DL = MI.getDebugLoc(); 9304 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9305 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9306 Register DstReg = MI.getOperand(0).getReg(); 9307 Register LoReg = MI.getOperand(1).getReg(); 9308 Register HiReg = MI.getOperand(2).getReg(); 9309 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9310 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9311 9312 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9313 MachineMemOperand *MMOLo = 9314 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9315 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9316 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9317 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9318 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9319 .addFrameIndex(FI) 9320 .addImm(0) 9321 .addMemOperand(MMOLo); 9322 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9323 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9324 .addFrameIndex(FI) 9325 .addImm(4) 9326 .addMemOperand(MMOHi); 9327 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9328 MI.eraseFromParent(); // The pseudo instruction is gone now. 9329 return BB; 9330 } 9331 9332 static bool isSelectPseudo(MachineInstr &MI) { 9333 switch (MI.getOpcode()) { 9334 default: 9335 return false; 9336 case RISCV::Select_GPR_Using_CC_GPR: 9337 case RISCV::Select_FPR16_Using_CC_GPR: 9338 case RISCV::Select_FPR32_Using_CC_GPR: 9339 case RISCV::Select_FPR64_Using_CC_GPR: 9340 return true; 9341 } 9342 } 9343 9344 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9345 unsigned RelOpcode, unsigned EqOpcode, 9346 const RISCVSubtarget &Subtarget) { 9347 DebugLoc DL = MI.getDebugLoc(); 9348 Register DstReg = MI.getOperand(0).getReg(); 9349 Register Src1Reg = MI.getOperand(1).getReg(); 9350 Register Src2Reg = MI.getOperand(2).getReg(); 9351 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9352 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9353 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9354 9355 // Save the current FFLAGS. 9356 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9357 9358 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9359 .addReg(Src1Reg) 9360 .addReg(Src2Reg); 9361 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9362 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9363 9364 // Restore the FFLAGS. 9365 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9366 .addReg(SavedFFlags, RegState::Kill); 9367 9368 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9369 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9370 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9371 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9372 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9373 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9374 9375 // Erase the pseudoinstruction. 9376 MI.eraseFromParent(); 9377 return BB; 9378 } 9379 9380 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9381 MachineBasicBlock *BB, 9382 const RISCVSubtarget &Subtarget) { 9383 // To "insert" Select_* instructions, we actually have to insert the triangle 9384 // control-flow pattern. The incoming instructions know the destination vreg 9385 // to set, the condition code register to branch on, the true/false values to 9386 // select between, and the condcode to use to select the appropriate branch. 9387 // 9388 // We produce the following control flow: 9389 // HeadMBB 9390 // | \ 9391 // | IfFalseMBB 9392 // | / 9393 // TailMBB 9394 // 9395 // When we find a sequence of selects we attempt to optimize their emission 9396 // by sharing the control flow. Currently we only handle cases where we have 9397 // multiple selects with the exact same condition (same LHS, RHS and CC). 9398 // The selects may be interleaved with other instructions if the other 9399 // instructions meet some requirements we deem safe: 9400 // - They are debug instructions. Otherwise, 9401 // - They do not have side-effects, do not access memory and their inputs do 9402 // not depend on the results of the select pseudo-instructions. 9403 // The TrueV/FalseV operands of the selects cannot depend on the result of 9404 // previous selects in the sequence. 9405 // These conditions could be further relaxed. See the X86 target for a 9406 // related approach and more information. 9407 Register LHS = MI.getOperand(1).getReg(); 9408 Register RHS = MI.getOperand(2).getReg(); 9409 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9410 9411 SmallVector<MachineInstr *, 4> SelectDebugValues; 9412 SmallSet<Register, 4> SelectDests; 9413 SelectDests.insert(MI.getOperand(0).getReg()); 9414 9415 MachineInstr *LastSelectPseudo = &MI; 9416 9417 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9418 SequenceMBBI != E; ++SequenceMBBI) { 9419 if (SequenceMBBI->isDebugInstr()) 9420 continue; 9421 else if (isSelectPseudo(*SequenceMBBI)) { 9422 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9423 SequenceMBBI->getOperand(2).getReg() != RHS || 9424 SequenceMBBI->getOperand(3).getImm() != CC || 9425 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9426 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9427 break; 9428 LastSelectPseudo = &*SequenceMBBI; 9429 SequenceMBBI->collectDebugValues(SelectDebugValues); 9430 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9431 } else { 9432 if (SequenceMBBI->hasUnmodeledSideEffects() || 9433 SequenceMBBI->mayLoadOrStore()) 9434 break; 9435 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9436 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9437 })) 9438 break; 9439 } 9440 } 9441 9442 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9443 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9444 DebugLoc DL = MI.getDebugLoc(); 9445 MachineFunction::iterator I = ++BB->getIterator(); 9446 9447 MachineBasicBlock *HeadMBB = BB; 9448 MachineFunction *F = BB->getParent(); 9449 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9450 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9451 9452 F->insert(I, IfFalseMBB); 9453 F->insert(I, TailMBB); 9454 9455 // Transfer debug instructions associated with the selects to TailMBB. 9456 for (MachineInstr *DebugInstr : SelectDebugValues) { 9457 TailMBB->push_back(DebugInstr->removeFromParent()); 9458 } 9459 9460 // Move all instructions after the sequence to TailMBB. 9461 TailMBB->splice(TailMBB->end(), HeadMBB, 9462 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9463 // Update machine-CFG edges by transferring all successors of the current 9464 // block to the new block which will contain the Phi nodes for the selects. 9465 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9466 // Set the successors for HeadMBB. 9467 HeadMBB->addSuccessor(IfFalseMBB); 9468 HeadMBB->addSuccessor(TailMBB); 9469 9470 // Insert appropriate branch. 9471 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9472 .addReg(LHS) 9473 .addReg(RHS) 9474 .addMBB(TailMBB); 9475 9476 // IfFalseMBB just falls through to TailMBB. 9477 IfFalseMBB->addSuccessor(TailMBB); 9478 9479 // Create PHIs for all of the select pseudo-instructions. 9480 auto SelectMBBI = MI.getIterator(); 9481 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9482 auto InsertionPoint = TailMBB->begin(); 9483 while (SelectMBBI != SelectEnd) { 9484 auto Next = std::next(SelectMBBI); 9485 if (isSelectPseudo(*SelectMBBI)) { 9486 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9487 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9488 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9489 .addReg(SelectMBBI->getOperand(4).getReg()) 9490 .addMBB(HeadMBB) 9491 .addReg(SelectMBBI->getOperand(5).getReg()) 9492 .addMBB(IfFalseMBB); 9493 SelectMBBI->eraseFromParent(); 9494 } 9495 SelectMBBI = Next; 9496 } 9497 9498 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9499 return TailMBB; 9500 } 9501 9502 MachineBasicBlock * 9503 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9504 MachineBasicBlock *BB) const { 9505 switch (MI.getOpcode()) { 9506 default: 9507 llvm_unreachable("Unexpected instr type to insert"); 9508 case RISCV::ReadCycleWide: 9509 assert(!Subtarget.is64Bit() && 9510 "ReadCycleWrite is only to be used on riscv32"); 9511 return emitReadCycleWidePseudo(MI, BB); 9512 case RISCV::Select_GPR_Using_CC_GPR: 9513 case RISCV::Select_FPR16_Using_CC_GPR: 9514 case RISCV::Select_FPR32_Using_CC_GPR: 9515 case RISCV::Select_FPR64_Using_CC_GPR: 9516 return emitSelectPseudo(MI, BB, Subtarget); 9517 case RISCV::BuildPairF64Pseudo: 9518 return emitBuildPairF64Pseudo(MI, BB); 9519 case RISCV::SplitF64Pseudo: 9520 return emitSplitF64Pseudo(MI, BB); 9521 case RISCV::PseudoQuietFLE_H: 9522 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9523 case RISCV::PseudoQuietFLT_H: 9524 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9525 case RISCV::PseudoQuietFLE_S: 9526 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9527 case RISCV::PseudoQuietFLT_S: 9528 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9529 case RISCV::PseudoQuietFLE_D: 9530 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9531 case RISCV::PseudoQuietFLT_D: 9532 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9533 } 9534 } 9535 9536 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9537 SDNode *Node) const { 9538 // Add FRM dependency to any instructions with dynamic rounding mode. 9539 unsigned Opc = MI.getOpcode(); 9540 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9541 if (Idx < 0) 9542 return; 9543 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9544 return; 9545 // If the instruction already reads FRM, don't add another read. 9546 if (MI.readsRegister(RISCV::FRM)) 9547 return; 9548 MI.addOperand( 9549 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9550 } 9551 9552 // Calling Convention Implementation. 9553 // The expectations for frontend ABI lowering vary from target to target. 9554 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9555 // details, but this is a longer term goal. For now, we simply try to keep the 9556 // role of the frontend as simple and well-defined as possible. The rules can 9557 // be summarised as: 9558 // * Never split up large scalar arguments. We handle them here. 9559 // * If a hardfloat calling convention is being used, and the struct may be 9560 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9561 // available, then pass as two separate arguments. If either the GPRs or FPRs 9562 // are exhausted, then pass according to the rule below. 9563 // * If a struct could never be passed in registers or directly in a stack 9564 // slot (as it is larger than 2*XLEN and the floating point rules don't 9565 // apply), then pass it using a pointer with the byval attribute. 9566 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9567 // word-sized array or a 2*XLEN scalar (depending on alignment). 9568 // * The frontend can determine whether a struct is returned by reference or 9569 // not based on its size and fields. If it will be returned by reference, the 9570 // frontend must modify the prototype so a pointer with the sret annotation is 9571 // passed as the first argument. This is not necessary for large scalar 9572 // returns. 9573 // * Struct return values and varargs should be coerced to structs containing 9574 // register-size fields in the same situations they would be for fixed 9575 // arguments. 9576 9577 static const MCPhysReg ArgGPRs[] = { 9578 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9579 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9580 }; 9581 static const MCPhysReg ArgFPR16s[] = { 9582 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9583 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9584 }; 9585 static const MCPhysReg ArgFPR32s[] = { 9586 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9587 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9588 }; 9589 static const MCPhysReg ArgFPR64s[] = { 9590 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9591 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9592 }; 9593 // This is an interim calling convention and it may be changed in the future. 9594 static const MCPhysReg ArgVRs[] = { 9595 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9596 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9597 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9598 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9599 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9600 RISCV::V20M2, RISCV::V22M2}; 9601 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9602 RISCV::V20M4}; 9603 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9604 9605 // Pass a 2*XLEN argument that has been split into two XLEN values through 9606 // registers or the stack as necessary. 9607 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9608 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9609 MVT ValVT2, MVT LocVT2, 9610 ISD::ArgFlagsTy ArgFlags2) { 9611 unsigned XLenInBytes = XLen / 8; 9612 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9613 // At least one half can be passed via register. 9614 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9615 VA1.getLocVT(), CCValAssign::Full)); 9616 } else { 9617 // Both halves must be passed on the stack, with proper alignment. 9618 Align StackAlign = 9619 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9620 State.addLoc( 9621 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9622 State.AllocateStack(XLenInBytes, StackAlign), 9623 VA1.getLocVT(), CCValAssign::Full)); 9624 State.addLoc(CCValAssign::getMem( 9625 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9626 LocVT2, CCValAssign::Full)); 9627 return false; 9628 } 9629 9630 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9631 // The second half can also be passed via register. 9632 State.addLoc( 9633 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9634 } else { 9635 // The second half is passed via the stack, without additional alignment. 9636 State.addLoc(CCValAssign::getMem( 9637 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9638 LocVT2, CCValAssign::Full)); 9639 } 9640 9641 return false; 9642 } 9643 9644 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9645 Optional<unsigned> FirstMaskArgument, 9646 CCState &State, const RISCVTargetLowering &TLI) { 9647 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9648 if (RC == &RISCV::VRRegClass) { 9649 // Assign the first mask argument to V0. 9650 // This is an interim calling convention and it may be changed in the 9651 // future. 9652 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9653 return State.AllocateReg(RISCV::V0); 9654 return State.AllocateReg(ArgVRs); 9655 } 9656 if (RC == &RISCV::VRM2RegClass) 9657 return State.AllocateReg(ArgVRM2s); 9658 if (RC == &RISCV::VRM4RegClass) 9659 return State.AllocateReg(ArgVRM4s); 9660 if (RC == &RISCV::VRM8RegClass) 9661 return State.AllocateReg(ArgVRM8s); 9662 llvm_unreachable("Unhandled register class for ValueType"); 9663 } 9664 9665 // Implements the RISC-V calling convention. Returns true upon failure. 9666 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9667 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9668 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9669 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9670 Optional<unsigned> FirstMaskArgument) { 9671 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9672 assert(XLen == 32 || XLen == 64); 9673 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9674 9675 // Any return value split in to more than two values can't be returned 9676 // directly. Vectors are returned via the available vector registers. 9677 if (!LocVT.isVector() && IsRet && ValNo > 1) 9678 return true; 9679 9680 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9681 // variadic argument, or if no F16/F32 argument registers are available. 9682 bool UseGPRForF16_F32 = true; 9683 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9684 // variadic argument, or if no F64 argument registers are available. 9685 bool UseGPRForF64 = true; 9686 9687 switch (ABI) { 9688 default: 9689 llvm_unreachable("Unexpected ABI"); 9690 case RISCVABI::ABI_ILP32: 9691 case RISCVABI::ABI_LP64: 9692 break; 9693 case RISCVABI::ABI_ILP32F: 9694 case RISCVABI::ABI_LP64F: 9695 UseGPRForF16_F32 = !IsFixed; 9696 break; 9697 case RISCVABI::ABI_ILP32D: 9698 case RISCVABI::ABI_LP64D: 9699 UseGPRForF16_F32 = !IsFixed; 9700 UseGPRForF64 = !IsFixed; 9701 break; 9702 } 9703 9704 // FPR16, FPR32, and FPR64 alias each other. 9705 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9706 UseGPRForF16_F32 = true; 9707 UseGPRForF64 = true; 9708 } 9709 9710 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9711 // similar local variables rather than directly checking against the target 9712 // ABI. 9713 9714 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9715 LocVT = XLenVT; 9716 LocInfo = CCValAssign::BCvt; 9717 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9718 LocVT = MVT::i64; 9719 LocInfo = CCValAssign::BCvt; 9720 } 9721 9722 // If this is a variadic argument, the RISC-V calling convention requires 9723 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9724 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9725 // be used regardless of whether the original argument was split during 9726 // legalisation or not. The argument will not be passed by registers if the 9727 // original type is larger than 2*XLEN, so the register alignment rule does 9728 // not apply. 9729 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9730 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9731 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9732 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9733 // Skip 'odd' register if necessary. 9734 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9735 State.AllocateReg(ArgGPRs); 9736 } 9737 9738 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9739 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9740 State.getPendingArgFlags(); 9741 9742 assert(PendingLocs.size() == PendingArgFlags.size() && 9743 "PendingLocs and PendingArgFlags out of sync"); 9744 9745 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9746 // registers are exhausted. 9747 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9748 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9749 "Can't lower f64 if it is split"); 9750 // Depending on available argument GPRS, f64 may be passed in a pair of 9751 // GPRs, split between a GPR and the stack, or passed completely on the 9752 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9753 // cases. 9754 Register Reg = State.AllocateReg(ArgGPRs); 9755 LocVT = MVT::i32; 9756 if (!Reg) { 9757 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9758 State.addLoc( 9759 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9760 return false; 9761 } 9762 if (!State.AllocateReg(ArgGPRs)) 9763 State.AllocateStack(4, Align(4)); 9764 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9765 return false; 9766 } 9767 9768 // Fixed-length vectors are located in the corresponding scalable-vector 9769 // container types. 9770 if (ValVT.isFixedLengthVector()) 9771 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9772 9773 // Split arguments might be passed indirectly, so keep track of the pending 9774 // values. Split vectors are passed via a mix of registers and indirectly, so 9775 // treat them as we would any other argument. 9776 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9777 LocVT = XLenVT; 9778 LocInfo = CCValAssign::Indirect; 9779 PendingLocs.push_back( 9780 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9781 PendingArgFlags.push_back(ArgFlags); 9782 if (!ArgFlags.isSplitEnd()) { 9783 return false; 9784 } 9785 } 9786 9787 // If the split argument only had two elements, it should be passed directly 9788 // in registers or on the stack. 9789 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9790 PendingLocs.size() <= 2) { 9791 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9792 // Apply the normal calling convention rules to the first half of the 9793 // split argument. 9794 CCValAssign VA = PendingLocs[0]; 9795 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9796 PendingLocs.clear(); 9797 PendingArgFlags.clear(); 9798 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9799 ArgFlags); 9800 } 9801 9802 // Allocate to a register if possible, or else a stack slot. 9803 Register Reg; 9804 unsigned StoreSizeBytes = XLen / 8; 9805 Align StackAlign = Align(XLen / 8); 9806 9807 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9808 Reg = State.AllocateReg(ArgFPR16s); 9809 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9810 Reg = State.AllocateReg(ArgFPR32s); 9811 else if (ValVT == MVT::f64 && !UseGPRForF64) 9812 Reg = State.AllocateReg(ArgFPR64s); 9813 else if (ValVT.isVector()) { 9814 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9815 if (!Reg) { 9816 // For return values, the vector must be passed fully via registers or 9817 // via the stack. 9818 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9819 // but we're using all of them. 9820 if (IsRet) 9821 return true; 9822 // Try using a GPR to pass the address 9823 if ((Reg = State.AllocateReg(ArgGPRs))) { 9824 LocVT = XLenVT; 9825 LocInfo = CCValAssign::Indirect; 9826 } else if (ValVT.isScalableVector()) { 9827 LocVT = XLenVT; 9828 LocInfo = CCValAssign::Indirect; 9829 } else { 9830 // Pass fixed-length vectors on the stack. 9831 LocVT = ValVT; 9832 StoreSizeBytes = ValVT.getStoreSize(); 9833 // Align vectors to their element sizes, being careful for vXi1 9834 // vectors. 9835 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9836 } 9837 } 9838 } else { 9839 Reg = State.AllocateReg(ArgGPRs); 9840 } 9841 9842 unsigned StackOffset = 9843 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9844 9845 // If we reach this point and PendingLocs is non-empty, we must be at the 9846 // end of a split argument that must be passed indirectly. 9847 if (!PendingLocs.empty()) { 9848 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9849 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9850 9851 for (auto &It : PendingLocs) { 9852 if (Reg) 9853 It.convertToReg(Reg); 9854 else 9855 It.convertToMem(StackOffset); 9856 State.addLoc(It); 9857 } 9858 PendingLocs.clear(); 9859 PendingArgFlags.clear(); 9860 return false; 9861 } 9862 9863 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9864 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9865 "Expected an XLenVT or vector types at this stage"); 9866 9867 if (Reg) { 9868 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9869 return false; 9870 } 9871 9872 // When a floating-point value is passed on the stack, no bit-conversion is 9873 // needed. 9874 if (ValVT.isFloatingPoint()) { 9875 LocVT = ValVT; 9876 LocInfo = CCValAssign::Full; 9877 } 9878 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9879 return false; 9880 } 9881 9882 template <typename ArgTy> 9883 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9884 for (const auto &ArgIdx : enumerate(Args)) { 9885 MVT ArgVT = ArgIdx.value().VT; 9886 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9887 return ArgIdx.index(); 9888 } 9889 return None; 9890 } 9891 9892 void RISCVTargetLowering::analyzeInputArgs( 9893 MachineFunction &MF, CCState &CCInfo, 9894 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9895 RISCVCCAssignFn Fn) const { 9896 unsigned NumArgs = Ins.size(); 9897 FunctionType *FType = MF.getFunction().getFunctionType(); 9898 9899 Optional<unsigned> FirstMaskArgument; 9900 if (Subtarget.hasVInstructions()) 9901 FirstMaskArgument = preAssignMask(Ins); 9902 9903 for (unsigned i = 0; i != NumArgs; ++i) { 9904 MVT ArgVT = Ins[i].VT; 9905 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9906 9907 Type *ArgTy = nullptr; 9908 if (IsRet) 9909 ArgTy = FType->getReturnType(); 9910 else if (Ins[i].isOrigArg()) 9911 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9912 9913 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9914 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9915 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9916 FirstMaskArgument)) { 9917 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9918 << EVT(ArgVT).getEVTString() << '\n'); 9919 llvm_unreachable(nullptr); 9920 } 9921 } 9922 } 9923 9924 void RISCVTargetLowering::analyzeOutputArgs( 9925 MachineFunction &MF, CCState &CCInfo, 9926 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9927 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9928 unsigned NumArgs = Outs.size(); 9929 9930 Optional<unsigned> FirstMaskArgument; 9931 if (Subtarget.hasVInstructions()) 9932 FirstMaskArgument = preAssignMask(Outs); 9933 9934 for (unsigned i = 0; i != NumArgs; i++) { 9935 MVT ArgVT = Outs[i].VT; 9936 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9937 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9938 9939 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9940 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9941 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9942 FirstMaskArgument)) { 9943 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9944 << EVT(ArgVT).getEVTString() << "\n"); 9945 llvm_unreachable(nullptr); 9946 } 9947 } 9948 } 9949 9950 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9951 // values. 9952 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9953 const CCValAssign &VA, const SDLoc &DL, 9954 const RISCVSubtarget &Subtarget) { 9955 switch (VA.getLocInfo()) { 9956 default: 9957 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9958 case CCValAssign::Full: 9959 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9960 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9961 break; 9962 case CCValAssign::BCvt: 9963 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9964 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9965 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9966 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9967 else 9968 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9969 break; 9970 } 9971 return Val; 9972 } 9973 9974 // The caller is responsible for loading the full value if the argument is 9975 // passed with CCValAssign::Indirect. 9976 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9977 const CCValAssign &VA, const SDLoc &DL, 9978 const RISCVTargetLowering &TLI) { 9979 MachineFunction &MF = DAG.getMachineFunction(); 9980 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9981 EVT LocVT = VA.getLocVT(); 9982 SDValue Val; 9983 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9984 Register VReg = RegInfo.createVirtualRegister(RC); 9985 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9986 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9987 9988 if (VA.getLocInfo() == CCValAssign::Indirect) 9989 return Val; 9990 9991 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9992 } 9993 9994 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9995 const CCValAssign &VA, const SDLoc &DL, 9996 const RISCVSubtarget &Subtarget) { 9997 EVT LocVT = VA.getLocVT(); 9998 9999 switch (VA.getLocInfo()) { 10000 default: 10001 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10002 case CCValAssign::Full: 10003 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10004 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10005 break; 10006 case CCValAssign::BCvt: 10007 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10008 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10009 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10010 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10011 else 10012 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10013 break; 10014 } 10015 return Val; 10016 } 10017 10018 // The caller is responsible for loading the full value if the argument is 10019 // passed with CCValAssign::Indirect. 10020 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10021 const CCValAssign &VA, const SDLoc &DL) { 10022 MachineFunction &MF = DAG.getMachineFunction(); 10023 MachineFrameInfo &MFI = MF.getFrameInfo(); 10024 EVT LocVT = VA.getLocVT(); 10025 EVT ValVT = VA.getValVT(); 10026 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10027 if (ValVT.isScalableVector()) { 10028 // When the value is a scalable vector, we save the pointer which points to 10029 // the scalable vector value in the stack. The ValVT will be the pointer 10030 // type, instead of the scalable vector type. 10031 ValVT = LocVT; 10032 } 10033 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10034 /*IsImmutable=*/true); 10035 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10036 SDValue Val; 10037 10038 ISD::LoadExtType ExtType; 10039 switch (VA.getLocInfo()) { 10040 default: 10041 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10042 case CCValAssign::Full: 10043 case CCValAssign::Indirect: 10044 case CCValAssign::BCvt: 10045 ExtType = ISD::NON_EXTLOAD; 10046 break; 10047 } 10048 Val = DAG.getExtLoad( 10049 ExtType, DL, LocVT, Chain, FIN, 10050 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10051 return Val; 10052 } 10053 10054 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10055 const CCValAssign &VA, const SDLoc &DL) { 10056 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10057 "Unexpected VA"); 10058 MachineFunction &MF = DAG.getMachineFunction(); 10059 MachineFrameInfo &MFI = MF.getFrameInfo(); 10060 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10061 10062 if (VA.isMemLoc()) { 10063 // f64 is passed on the stack. 10064 int FI = 10065 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10066 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10067 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10068 MachinePointerInfo::getFixedStack(MF, FI)); 10069 } 10070 10071 assert(VA.isRegLoc() && "Expected register VA assignment"); 10072 10073 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10074 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10075 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10076 SDValue Hi; 10077 if (VA.getLocReg() == RISCV::X17) { 10078 // Second half of f64 is passed on the stack. 10079 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10080 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10081 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10082 MachinePointerInfo::getFixedStack(MF, FI)); 10083 } else { 10084 // Second half of f64 is passed in another GPR. 10085 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10086 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10087 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10088 } 10089 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10090 } 10091 10092 // FastCC has less than 1% performance improvement for some particular 10093 // benchmark. But theoretically, it may has benenfit for some cases. 10094 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10095 unsigned ValNo, MVT ValVT, MVT LocVT, 10096 CCValAssign::LocInfo LocInfo, 10097 ISD::ArgFlagsTy ArgFlags, CCState &State, 10098 bool IsFixed, bool IsRet, Type *OrigTy, 10099 const RISCVTargetLowering &TLI, 10100 Optional<unsigned> FirstMaskArgument) { 10101 10102 // X5 and X6 might be used for save-restore libcall. 10103 static const MCPhysReg GPRList[] = { 10104 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10105 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10106 RISCV::X29, RISCV::X30, RISCV::X31}; 10107 10108 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10109 if (unsigned Reg = State.AllocateReg(GPRList)) { 10110 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10111 return false; 10112 } 10113 } 10114 10115 if (LocVT == MVT::f16) { 10116 static const MCPhysReg FPR16List[] = { 10117 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10118 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10119 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10120 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10121 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10122 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10123 return false; 10124 } 10125 } 10126 10127 if (LocVT == MVT::f32) { 10128 static const MCPhysReg FPR32List[] = { 10129 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10130 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10131 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10132 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10133 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10134 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10135 return false; 10136 } 10137 } 10138 10139 if (LocVT == MVT::f64) { 10140 static const MCPhysReg FPR64List[] = { 10141 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10142 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10143 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10144 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10145 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10146 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10147 return false; 10148 } 10149 } 10150 10151 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10152 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10153 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10154 return false; 10155 } 10156 10157 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10158 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10159 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10160 return false; 10161 } 10162 10163 if (LocVT.isVector()) { 10164 if (unsigned Reg = 10165 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10166 // Fixed-length vectors are located in the corresponding scalable-vector 10167 // container types. 10168 if (ValVT.isFixedLengthVector()) 10169 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10170 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10171 } else { 10172 // Try and pass the address via a "fast" GPR. 10173 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10174 LocInfo = CCValAssign::Indirect; 10175 LocVT = TLI.getSubtarget().getXLenVT(); 10176 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10177 } else if (ValVT.isFixedLengthVector()) { 10178 auto StackAlign = 10179 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10180 unsigned StackOffset = 10181 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10182 State.addLoc( 10183 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10184 } else { 10185 // Can't pass scalable vectors on the stack. 10186 return true; 10187 } 10188 } 10189 10190 return false; 10191 } 10192 10193 return true; // CC didn't match. 10194 } 10195 10196 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10197 CCValAssign::LocInfo LocInfo, 10198 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10199 10200 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10201 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10202 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10203 static const MCPhysReg GPRList[] = { 10204 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10205 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10206 if (unsigned Reg = State.AllocateReg(GPRList)) { 10207 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10208 return false; 10209 } 10210 } 10211 10212 if (LocVT == MVT::f32) { 10213 // Pass in STG registers: F1, ..., F6 10214 // fs0 ... fs5 10215 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10216 RISCV::F18_F, RISCV::F19_F, 10217 RISCV::F20_F, RISCV::F21_F}; 10218 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10219 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10220 return false; 10221 } 10222 } 10223 10224 if (LocVT == MVT::f64) { 10225 // Pass in STG registers: D1, ..., D6 10226 // fs6 ... fs11 10227 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10228 RISCV::F24_D, RISCV::F25_D, 10229 RISCV::F26_D, RISCV::F27_D}; 10230 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10231 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10232 return false; 10233 } 10234 } 10235 10236 report_fatal_error("No registers left in GHC calling convention"); 10237 return true; 10238 } 10239 10240 // Transform physical registers into virtual registers. 10241 SDValue RISCVTargetLowering::LowerFormalArguments( 10242 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10243 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10244 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10245 10246 MachineFunction &MF = DAG.getMachineFunction(); 10247 10248 switch (CallConv) { 10249 default: 10250 report_fatal_error("Unsupported calling convention"); 10251 case CallingConv::C: 10252 case CallingConv::Fast: 10253 break; 10254 case CallingConv::GHC: 10255 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10256 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10257 report_fatal_error( 10258 "GHC calling convention requires the F and D instruction set extensions"); 10259 } 10260 10261 const Function &Func = MF.getFunction(); 10262 if (Func.hasFnAttribute("interrupt")) { 10263 if (!Func.arg_empty()) 10264 report_fatal_error( 10265 "Functions with the interrupt attribute cannot have arguments!"); 10266 10267 StringRef Kind = 10268 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10269 10270 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10271 report_fatal_error( 10272 "Function interrupt attribute argument not supported!"); 10273 } 10274 10275 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10276 MVT XLenVT = Subtarget.getXLenVT(); 10277 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10278 // Used with vargs to acumulate store chains. 10279 std::vector<SDValue> OutChains; 10280 10281 // Assign locations to all of the incoming arguments. 10282 SmallVector<CCValAssign, 16> ArgLocs; 10283 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10284 10285 if (CallConv == CallingConv::GHC) 10286 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10287 else 10288 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10289 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10290 : CC_RISCV); 10291 10292 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10293 CCValAssign &VA = ArgLocs[i]; 10294 SDValue ArgValue; 10295 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10296 // case. 10297 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10298 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10299 else if (VA.isRegLoc()) 10300 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10301 else 10302 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10303 10304 if (VA.getLocInfo() == CCValAssign::Indirect) { 10305 // If the original argument was split and passed by reference (e.g. i128 10306 // on RV32), we need to load all parts of it here (using the same 10307 // address). Vectors may be partly split to registers and partly to the 10308 // stack, in which case the base address is partly offset and subsequent 10309 // stores are relative to that. 10310 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10311 MachinePointerInfo())); 10312 unsigned ArgIndex = Ins[i].OrigArgIndex; 10313 unsigned ArgPartOffset = Ins[i].PartOffset; 10314 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10315 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10316 CCValAssign &PartVA = ArgLocs[i + 1]; 10317 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10318 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10319 if (PartVA.getValVT().isScalableVector()) 10320 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10321 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10322 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10323 MachinePointerInfo())); 10324 ++i; 10325 } 10326 continue; 10327 } 10328 InVals.push_back(ArgValue); 10329 } 10330 10331 if (IsVarArg) { 10332 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10333 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10334 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10335 MachineFrameInfo &MFI = MF.getFrameInfo(); 10336 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10337 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10338 10339 // Offset of the first variable argument from stack pointer, and size of 10340 // the vararg save area. For now, the varargs save area is either zero or 10341 // large enough to hold a0-a7. 10342 int VaArgOffset, VarArgsSaveSize; 10343 10344 // If all registers are allocated, then all varargs must be passed on the 10345 // stack and we don't need to save any argregs. 10346 if (ArgRegs.size() == Idx) { 10347 VaArgOffset = CCInfo.getNextStackOffset(); 10348 VarArgsSaveSize = 0; 10349 } else { 10350 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10351 VaArgOffset = -VarArgsSaveSize; 10352 } 10353 10354 // Record the frame index of the first variable argument 10355 // which is a value necessary to VASTART. 10356 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10357 RVFI->setVarArgsFrameIndex(FI); 10358 10359 // If saving an odd number of registers then create an extra stack slot to 10360 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10361 // offsets to even-numbered registered remain 2*XLEN-aligned. 10362 if (Idx % 2) { 10363 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10364 VarArgsSaveSize += XLenInBytes; 10365 } 10366 10367 // Copy the integer registers that may have been used for passing varargs 10368 // to the vararg save area. 10369 for (unsigned I = Idx; I < ArgRegs.size(); 10370 ++I, VaArgOffset += XLenInBytes) { 10371 const Register Reg = RegInfo.createVirtualRegister(RC); 10372 RegInfo.addLiveIn(ArgRegs[I], Reg); 10373 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10374 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10375 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10376 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10377 MachinePointerInfo::getFixedStack(MF, FI)); 10378 cast<StoreSDNode>(Store.getNode()) 10379 ->getMemOperand() 10380 ->setValue((Value *)nullptr); 10381 OutChains.push_back(Store); 10382 } 10383 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10384 } 10385 10386 // All stores are grouped in one node to allow the matching between 10387 // the size of Ins and InVals. This only happens for vararg functions. 10388 if (!OutChains.empty()) { 10389 OutChains.push_back(Chain); 10390 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10391 } 10392 10393 return Chain; 10394 } 10395 10396 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10397 /// for tail call optimization. 10398 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10399 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10400 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10401 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10402 10403 auto &Callee = CLI.Callee; 10404 auto CalleeCC = CLI.CallConv; 10405 auto &Outs = CLI.Outs; 10406 auto &Caller = MF.getFunction(); 10407 auto CallerCC = Caller.getCallingConv(); 10408 10409 // Exception-handling functions need a special set of instructions to 10410 // indicate a return to the hardware. Tail-calling another function would 10411 // probably break this. 10412 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10413 // should be expanded as new function attributes are introduced. 10414 if (Caller.hasFnAttribute("interrupt")) 10415 return false; 10416 10417 // Do not tail call opt if the stack is used to pass parameters. 10418 if (CCInfo.getNextStackOffset() != 0) 10419 return false; 10420 10421 // Do not tail call opt if any parameters need to be passed indirectly. 10422 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10423 // passed indirectly. So the address of the value will be passed in a 10424 // register, or if not available, then the address is put on the stack. In 10425 // order to pass indirectly, space on the stack often needs to be allocated 10426 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10427 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10428 // are passed CCValAssign::Indirect. 10429 for (auto &VA : ArgLocs) 10430 if (VA.getLocInfo() == CCValAssign::Indirect) 10431 return false; 10432 10433 // Do not tail call opt if either caller or callee uses struct return 10434 // semantics. 10435 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10436 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10437 if (IsCallerStructRet || IsCalleeStructRet) 10438 return false; 10439 10440 // Externally-defined functions with weak linkage should not be 10441 // tail-called. The behaviour of branch instructions in this situation (as 10442 // used for tail calls) is implementation-defined, so we cannot rely on the 10443 // linker replacing the tail call with a return. 10444 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10445 const GlobalValue *GV = G->getGlobal(); 10446 if (GV->hasExternalWeakLinkage()) 10447 return false; 10448 } 10449 10450 // The callee has to preserve all registers the caller needs to preserve. 10451 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10452 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10453 if (CalleeCC != CallerCC) { 10454 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10455 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10456 return false; 10457 } 10458 10459 // Byval parameters hand the function a pointer directly into the stack area 10460 // we want to reuse during a tail call. Working around this *is* possible 10461 // but less efficient and uglier in LowerCall. 10462 for (auto &Arg : Outs) 10463 if (Arg.Flags.isByVal()) 10464 return false; 10465 10466 return true; 10467 } 10468 10469 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10470 return DAG.getDataLayout().getPrefTypeAlign( 10471 VT.getTypeForEVT(*DAG.getContext())); 10472 } 10473 10474 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10475 // and output parameter nodes. 10476 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10477 SmallVectorImpl<SDValue> &InVals) const { 10478 SelectionDAG &DAG = CLI.DAG; 10479 SDLoc &DL = CLI.DL; 10480 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10481 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10482 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10483 SDValue Chain = CLI.Chain; 10484 SDValue Callee = CLI.Callee; 10485 bool &IsTailCall = CLI.IsTailCall; 10486 CallingConv::ID CallConv = CLI.CallConv; 10487 bool IsVarArg = CLI.IsVarArg; 10488 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10489 MVT XLenVT = Subtarget.getXLenVT(); 10490 10491 MachineFunction &MF = DAG.getMachineFunction(); 10492 10493 // Analyze the operands of the call, assigning locations to each operand. 10494 SmallVector<CCValAssign, 16> ArgLocs; 10495 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10496 10497 if (CallConv == CallingConv::GHC) 10498 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10499 else 10500 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10501 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10502 : CC_RISCV); 10503 10504 // Check if it's really possible to do a tail call. 10505 if (IsTailCall) 10506 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10507 10508 if (IsTailCall) 10509 ++NumTailCalls; 10510 else if (CLI.CB && CLI.CB->isMustTailCall()) 10511 report_fatal_error("failed to perform tail call elimination on a call " 10512 "site marked musttail"); 10513 10514 // Get a count of how many bytes are to be pushed on the stack. 10515 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10516 10517 // Create local copies for byval args 10518 SmallVector<SDValue, 8> ByValArgs; 10519 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10520 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10521 if (!Flags.isByVal()) 10522 continue; 10523 10524 SDValue Arg = OutVals[i]; 10525 unsigned Size = Flags.getByValSize(); 10526 Align Alignment = Flags.getNonZeroByValAlign(); 10527 10528 int FI = 10529 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10530 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10531 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10532 10533 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10534 /*IsVolatile=*/false, 10535 /*AlwaysInline=*/false, IsTailCall, 10536 MachinePointerInfo(), MachinePointerInfo()); 10537 ByValArgs.push_back(FIPtr); 10538 } 10539 10540 if (!IsTailCall) 10541 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10542 10543 // Copy argument values to their designated locations. 10544 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10545 SmallVector<SDValue, 8> MemOpChains; 10546 SDValue StackPtr; 10547 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10548 CCValAssign &VA = ArgLocs[i]; 10549 SDValue ArgValue = OutVals[i]; 10550 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10551 10552 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10553 bool IsF64OnRV32DSoftABI = 10554 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10555 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10556 SDValue SplitF64 = DAG.getNode( 10557 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10558 SDValue Lo = SplitF64.getValue(0); 10559 SDValue Hi = SplitF64.getValue(1); 10560 10561 Register RegLo = VA.getLocReg(); 10562 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10563 10564 if (RegLo == RISCV::X17) { 10565 // Second half of f64 is passed on the stack. 10566 // Work out the address of the stack slot. 10567 if (!StackPtr.getNode()) 10568 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10569 // Emit the store. 10570 MemOpChains.push_back( 10571 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10572 } else { 10573 // Second half of f64 is passed in another GPR. 10574 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10575 Register RegHigh = RegLo + 1; 10576 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10577 } 10578 continue; 10579 } 10580 10581 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10582 // as any other MemLoc. 10583 10584 // Promote the value if needed. 10585 // For now, only handle fully promoted and indirect arguments. 10586 if (VA.getLocInfo() == CCValAssign::Indirect) { 10587 // Store the argument in a stack slot and pass its address. 10588 Align StackAlign = 10589 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10590 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10591 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10592 // If the original argument was split (e.g. i128), we need 10593 // to store the required parts of it here (and pass just one address). 10594 // Vectors may be partly split to registers and partly to the stack, in 10595 // which case the base address is partly offset and subsequent stores are 10596 // relative to that. 10597 unsigned ArgIndex = Outs[i].OrigArgIndex; 10598 unsigned ArgPartOffset = Outs[i].PartOffset; 10599 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10600 // Calculate the total size to store. We don't have access to what we're 10601 // actually storing other than performing the loop and collecting the 10602 // info. 10603 SmallVector<std::pair<SDValue, SDValue>> Parts; 10604 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10605 SDValue PartValue = OutVals[i + 1]; 10606 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10607 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10608 EVT PartVT = PartValue.getValueType(); 10609 if (PartVT.isScalableVector()) 10610 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10611 StoredSize += PartVT.getStoreSize(); 10612 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10613 Parts.push_back(std::make_pair(PartValue, Offset)); 10614 ++i; 10615 } 10616 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10617 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10618 MemOpChains.push_back( 10619 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10620 MachinePointerInfo::getFixedStack(MF, FI))); 10621 for (const auto &Part : Parts) { 10622 SDValue PartValue = Part.first; 10623 SDValue PartOffset = Part.second; 10624 SDValue Address = 10625 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10626 MemOpChains.push_back( 10627 DAG.getStore(Chain, DL, PartValue, Address, 10628 MachinePointerInfo::getFixedStack(MF, FI))); 10629 } 10630 ArgValue = SpillSlot; 10631 } else { 10632 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10633 } 10634 10635 // Use local copy if it is a byval arg. 10636 if (Flags.isByVal()) 10637 ArgValue = ByValArgs[j++]; 10638 10639 if (VA.isRegLoc()) { 10640 // Queue up the argument copies and emit them at the end. 10641 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10642 } else { 10643 assert(VA.isMemLoc() && "Argument not register or memory"); 10644 assert(!IsTailCall && "Tail call not allowed if stack is used " 10645 "for passing parameters"); 10646 10647 // Work out the address of the stack slot. 10648 if (!StackPtr.getNode()) 10649 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10650 SDValue Address = 10651 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10652 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10653 10654 // Emit the store. 10655 MemOpChains.push_back( 10656 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10657 } 10658 } 10659 10660 // Join the stores, which are independent of one another. 10661 if (!MemOpChains.empty()) 10662 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10663 10664 SDValue Glue; 10665 10666 // Build a sequence of copy-to-reg nodes, chained and glued together. 10667 for (auto &Reg : RegsToPass) { 10668 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10669 Glue = Chain.getValue(1); 10670 } 10671 10672 // Validate that none of the argument registers have been marked as 10673 // reserved, if so report an error. Do the same for the return address if this 10674 // is not a tailcall. 10675 validateCCReservedRegs(RegsToPass, MF); 10676 if (!IsTailCall && 10677 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10678 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10679 MF.getFunction(), 10680 "Return address register required, but has been reserved."}); 10681 10682 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10683 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10684 // split it and then direct call can be matched by PseudoCALL. 10685 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10686 const GlobalValue *GV = S->getGlobal(); 10687 10688 unsigned OpFlags = RISCVII::MO_CALL; 10689 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10690 OpFlags = RISCVII::MO_PLT; 10691 10692 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10693 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10694 unsigned OpFlags = RISCVII::MO_CALL; 10695 10696 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10697 nullptr)) 10698 OpFlags = RISCVII::MO_PLT; 10699 10700 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10701 } 10702 10703 // The first call operand is the chain and the second is the target address. 10704 SmallVector<SDValue, 8> Ops; 10705 Ops.push_back(Chain); 10706 Ops.push_back(Callee); 10707 10708 // Add argument registers to the end of the list so that they are 10709 // known live into the call. 10710 for (auto &Reg : RegsToPass) 10711 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10712 10713 if (!IsTailCall) { 10714 // Add a register mask operand representing the call-preserved registers. 10715 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10716 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10717 assert(Mask && "Missing call preserved mask for calling convention"); 10718 Ops.push_back(DAG.getRegisterMask(Mask)); 10719 } 10720 10721 // Glue the call to the argument copies, if any. 10722 if (Glue.getNode()) 10723 Ops.push_back(Glue); 10724 10725 // Emit the call. 10726 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10727 10728 if (IsTailCall) { 10729 MF.getFrameInfo().setHasTailCall(); 10730 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10731 } 10732 10733 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10734 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10735 Glue = Chain.getValue(1); 10736 10737 // Mark the end of the call, which is glued to the call itself. 10738 Chain = DAG.getCALLSEQ_END(Chain, 10739 DAG.getConstant(NumBytes, DL, PtrVT, true), 10740 DAG.getConstant(0, DL, PtrVT, true), 10741 Glue, DL); 10742 Glue = Chain.getValue(1); 10743 10744 // Assign locations to each value returned by this call. 10745 SmallVector<CCValAssign, 16> RVLocs; 10746 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10747 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10748 10749 // Copy all of the result registers out of their specified physreg. 10750 for (auto &VA : RVLocs) { 10751 // Copy the value out 10752 SDValue RetValue = 10753 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10754 // Glue the RetValue to the end of the call sequence 10755 Chain = RetValue.getValue(1); 10756 Glue = RetValue.getValue(2); 10757 10758 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10759 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10760 SDValue RetValue2 = 10761 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10762 Chain = RetValue2.getValue(1); 10763 Glue = RetValue2.getValue(2); 10764 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10765 RetValue2); 10766 } 10767 10768 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10769 10770 InVals.push_back(RetValue); 10771 } 10772 10773 return Chain; 10774 } 10775 10776 bool RISCVTargetLowering::CanLowerReturn( 10777 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10778 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10779 SmallVector<CCValAssign, 16> RVLocs; 10780 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10781 10782 Optional<unsigned> FirstMaskArgument; 10783 if (Subtarget.hasVInstructions()) 10784 FirstMaskArgument = preAssignMask(Outs); 10785 10786 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10787 MVT VT = Outs[i].VT; 10788 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10789 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10790 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10791 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10792 *this, FirstMaskArgument)) 10793 return false; 10794 } 10795 return true; 10796 } 10797 10798 SDValue 10799 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10800 bool IsVarArg, 10801 const SmallVectorImpl<ISD::OutputArg> &Outs, 10802 const SmallVectorImpl<SDValue> &OutVals, 10803 const SDLoc &DL, SelectionDAG &DAG) const { 10804 const MachineFunction &MF = DAG.getMachineFunction(); 10805 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10806 10807 // Stores the assignment of the return value to a location. 10808 SmallVector<CCValAssign, 16> RVLocs; 10809 10810 // Info about the registers and stack slot. 10811 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10812 *DAG.getContext()); 10813 10814 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10815 nullptr, CC_RISCV); 10816 10817 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10818 report_fatal_error("GHC functions return void only"); 10819 10820 SDValue Glue; 10821 SmallVector<SDValue, 4> RetOps(1, Chain); 10822 10823 // Copy the result values into the output registers. 10824 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10825 SDValue Val = OutVals[i]; 10826 CCValAssign &VA = RVLocs[i]; 10827 assert(VA.isRegLoc() && "Can only return in registers!"); 10828 10829 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10830 // Handle returning f64 on RV32D with a soft float ABI. 10831 assert(VA.isRegLoc() && "Expected return via registers"); 10832 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10833 DAG.getVTList(MVT::i32, MVT::i32), Val); 10834 SDValue Lo = SplitF64.getValue(0); 10835 SDValue Hi = SplitF64.getValue(1); 10836 Register RegLo = VA.getLocReg(); 10837 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10838 Register RegHi = RegLo + 1; 10839 10840 if (STI.isRegisterReservedByUser(RegLo) || 10841 STI.isRegisterReservedByUser(RegHi)) 10842 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10843 MF.getFunction(), 10844 "Return value register required, but has been reserved."}); 10845 10846 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10847 Glue = Chain.getValue(1); 10848 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10849 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10850 Glue = Chain.getValue(1); 10851 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10852 } else { 10853 // Handle a 'normal' return. 10854 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10855 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10856 10857 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10858 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10859 MF.getFunction(), 10860 "Return value register required, but has been reserved."}); 10861 10862 // Guarantee that all emitted copies are stuck together. 10863 Glue = Chain.getValue(1); 10864 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10865 } 10866 } 10867 10868 RetOps[0] = Chain; // Update chain. 10869 10870 // Add the glue node if we have it. 10871 if (Glue.getNode()) { 10872 RetOps.push_back(Glue); 10873 } 10874 10875 unsigned RetOpc = RISCVISD::RET_FLAG; 10876 // Interrupt service routines use different return instructions. 10877 const Function &Func = DAG.getMachineFunction().getFunction(); 10878 if (Func.hasFnAttribute("interrupt")) { 10879 if (!Func.getReturnType()->isVoidTy()) 10880 report_fatal_error( 10881 "Functions with the interrupt attribute must have void return type!"); 10882 10883 MachineFunction &MF = DAG.getMachineFunction(); 10884 StringRef Kind = 10885 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10886 10887 if (Kind == "user") 10888 RetOpc = RISCVISD::URET_FLAG; 10889 else if (Kind == "supervisor") 10890 RetOpc = RISCVISD::SRET_FLAG; 10891 else 10892 RetOpc = RISCVISD::MRET_FLAG; 10893 } 10894 10895 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10896 } 10897 10898 void RISCVTargetLowering::validateCCReservedRegs( 10899 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10900 MachineFunction &MF) const { 10901 const Function &F = MF.getFunction(); 10902 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10903 10904 if (llvm::any_of(Regs, [&STI](auto Reg) { 10905 return STI.isRegisterReservedByUser(Reg.first); 10906 })) 10907 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10908 F, "Argument register required, but has been reserved."}); 10909 } 10910 10911 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10912 return CI->isTailCall(); 10913 } 10914 10915 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10916 #define NODE_NAME_CASE(NODE) \ 10917 case RISCVISD::NODE: \ 10918 return "RISCVISD::" #NODE; 10919 // clang-format off 10920 switch ((RISCVISD::NodeType)Opcode) { 10921 case RISCVISD::FIRST_NUMBER: 10922 break; 10923 NODE_NAME_CASE(RET_FLAG) 10924 NODE_NAME_CASE(URET_FLAG) 10925 NODE_NAME_CASE(SRET_FLAG) 10926 NODE_NAME_CASE(MRET_FLAG) 10927 NODE_NAME_CASE(CALL) 10928 NODE_NAME_CASE(SELECT_CC) 10929 NODE_NAME_CASE(BR_CC) 10930 NODE_NAME_CASE(BuildPairF64) 10931 NODE_NAME_CASE(SplitF64) 10932 NODE_NAME_CASE(TAIL) 10933 NODE_NAME_CASE(MULHSU) 10934 NODE_NAME_CASE(SLLW) 10935 NODE_NAME_CASE(SRAW) 10936 NODE_NAME_CASE(SRLW) 10937 NODE_NAME_CASE(DIVW) 10938 NODE_NAME_CASE(DIVUW) 10939 NODE_NAME_CASE(REMUW) 10940 NODE_NAME_CASE(ROLW) 10941 NODE_NAME_CASE(RORW) 10942 NODE_NAME_CASE(CLZW) 10943 NODE_NAME_CASE(CTZW) 10944 NODE_NAME_CASE(FSLW) 10945 NODE_NAME_CASE(FSRW) 10946 NODE_NAME_CASE(FSL) 10947 NODE_NAME_CASE(FSR) 10948 NODE_NAME_CASE(FMV_H_X) 10949 NODE_NAME_CASE(FMV_X_ANYEXTH) 10950 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10951 NODE_NAME_CASE(FMV_W_X_RV64) 10952 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10953 NODE_NAME_CASE(FCVT_X) 10954 NODE_NAME_CASE(FCVT_XU) 10955 NODE_NAME_CASE(FCVT_W_RV64) 10956 NODE_NAME_CASE(FCVT_WU_RV64) 10957 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10958 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10959 NODE_NAME_CASE(READ_CYCLE_WIDE) 10960 NODE_NAME_CASE(GREV) 10961 NODE_NAME_CASE(GREVW) 10962 NODE_NAME_CASE(GORC) 10963 NODE_NAME_CASE(GORCW) 10964 NODE_NAME_CASE(SHFL) 10965 NODE_NAME_CASE(SHFLW) 10966 NODE_NAME_CASE(UNSHFL) 10967 NODE_NAME_CASE(UNSHFLW) 10968 NODE_NAME_CASE(BFP) 10969 NODE_NAME_CASE(BFPW) 10970 NODE_NAME_CASE(BCOMPRESS) 10971 NODE_NAME_CASE(BCOMPRESSW) 10972 NODE_NAME_CASE(BDECOMPRESS) 10973 NODE_NAME_CASE(BDECOMPRESSW) 10974 NODE_NAME_CASE(VMV_V_X_VL) 10975 NODE_NAME_CASE(VFMV_V_F_VL) 10976 NODE_NAME_CASE(VMV_X_S) 10977 NODE_NAME_CASE(VMV_S_X_VL) 10978 NODE_NAME_CASE(VFMV_S_F_VL) 10979 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10980 NODE_NAME_CASE(READ_VLENB) 10981 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10982 NODE_NAME_CASE(VSLIDEUP_VL) 10983 NODE_NAME_CASE(VSLIDE1UP_VL) 10984 NODE_NAME_CASE(VSLIDEDOWN_VL) 10985 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10986 NODE_NAME_CASE(VID_VL) 10987 NODE_NAME_CASE(VFNCVT_ROD_VL) 10988 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10989 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10990 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10991 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10992 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10993 NODE_NAME_CASE(VECREDUCE_AND_VL) 10994 NODE_NAME_CASE(VECREDUCE_OR_VL) 10995 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10996 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10997 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10998 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10999 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11000 NODE_NAME_CASE(ADD_VL) 11001 NODE_NAME_CASE(AND_VL) 11002 NODE_NAME_CASE(MUL_VL) 11003 NODE_NAME_CASE(OR_VL) 11004 NODE_NAME_CASE(SDIV_VL) 11005 NODE_NAME_CASE(SHL_VL) 11006 NODE_NAME_CASE(SREM_VL) 11007 NODE_NAME_CASE(SRA_VL) 11008 NODE_NAME_CASE(SRL_VL) 11009 NODE_NAME_CASE(SUB_VL) 11010 NODE_NAME_CASE(UDIV_VL) 11011 NODE_NAME_CASE(UREM_VL) 11012 NODE_NAME_CASE(XOR_VL) 11013 NODE_NAME_CASE(SADDSAT_VL) 11014 NODE_NAME_CASE(UADDSAT_VL) 11015 NODE_NAME_CASE(SSUBSAT_VL) 11016 NODE_NAME_CASE(USUBSAT_VL) 11017 NODE_NAME_CASE(FADD_VL) 11018 NODE_NAME_CASE(FSUB_VL) 11019 NODE_NAME_CASE(FMUL_VL) 11020 NODE_NAME_CASE(FDIV_VL) 11021 NODE_NAME_CASE(FNEG_VL) 11022 NODE_NAME_CASE(FABS_VL) 11023 NODE_NAME_CASE(FSQRT_VL) 11024 NODE_NAME_CASE(FMA_VL) 11025 NODE_NAME_CASE(FCOPYSIGN_VL) 11026 NODE_NAME_CASE(SMIN_VL) 11027 NODE_NAME_CASE(SMAX_VL) 11028 NODE_NAME_CASE(UMIN_VL) 11029 NODE_NAME_CASE(UMAX_VL) 11030 NODE_NAME_CASE(FMINNUM_VL) 11031 NODE_NAME_CASE(FMAXNUM_VL) 11032 NODE_NAME_CASE(MULHS_VL) 11033 NODE_NAME_CASE(MULHU_VL) 11034 NODE_NAME_CASE(FP_TO_SINT_VL) 11035 NODE_NAME_CASE(FP_TO_UINT_VL) 11036 NODE_NAME_CASE(SINT_TO_FP_VL) 11037 NODE_NAME_CASE(UINT_TO_FP_VL) 11038 NODE_NAME_CASE(FP_EXTEND_VL) 11039 NODE_NAME_CASE(FP_ROUND_VL) 11040 NODE_NAME_CASE(VWMUL_VL) 11041 NODE_NAME_CASE(VWMULU_VL) 11042 NODE_NAME_CASE(VWMULSU_VL) 11043 NODE_NAME_CASE(VWADD_VL) 11044 NODE_NAME_CASE(VWADDU_VL) 11045 NODE_NAME_CASE(VWSUB_VL) 11046 NODE_NAME_CASE(VWSUBU_VL) 11047 NODE_NAME_CASE(VWADD_W_VL) 11048 NODE_NAME_CASE(VWADDU_W_VL) 11049 NODE_NAME_CASE(VWSUB_W_VL) 11050 NODE_NAME_CASE(VWSUBU_W_VL) 11051 NODE_NAME_CASE(SETCC_VL) 11052 NODE_NAME_CASE(VSELECT_VL) 11053 NODE_NAME_CASE(VP_MERGE_VL) 11054 NODE_NAME_CASE(VMAND_VL) 11055 NODE_NAME_CASE(VMOR_VL) 11056 NODE_NAME_CASE(VMXOR_VL) 11057 NODE_NAME_CASE(VMCLR_VL) 11058 NODE_NAME_CASE(VMSET_VL) 11059 NODE_NAME_CASE(VRGATHER_VX_VL) 11060 NODE_NAME_CASE(VRGATHER_VV_VL) 11061 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11062 NODE_NAME_CASE(VSEXT_VL) 11063 NODE_NAME_CASE(VZEXT_VL) 11064 NODE_NAME_CASE(VCPOP_VL) 11065 NODE_NAME_CASE(READ_CSR) 11066 NODE_NAME_CASE(WRITE_CSR) 11067 NODE_NAME_CASE(SWAP_CSR) 11068 } 11069 // clang-format on 11070 return nullptr; 11071 #undef NODE_NAME_CASE 11072 } 11073 11074 /// getConstraintType - Given a constraint letter, return the type of 11075 /// constraint it is for this target. 11076 RISCVTargetLowering::ConstraintType 11077 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11078 if (Constraint.size() == 1) { 11079 switch (Constraint[0]) { 11080 default: 11081 break; 11082 case 'f': 11083 return C_RegisterClass; 11084 case 'I': 11085 case 'J': 11086 case 'K': 11087 return C_Immediate; 11088 case 'A': 11089 return C_Memory; 11090 case 'S': // A symbolic address 11091 return C_Other; 11092 } 11093 } else { 11094 if (Constraint == "vr" || Constraint == "vm") 11095 return C_RegisterClass; 11096 } 11097 return TargetLowering::getConstraintType(Constraint); 11098 } 11099 11100 std::pair<unsigned, const TargetRegisterClass *> 11101 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11102 StringRef Constraint, 11103 MVT VT) const { 11104 // First, see if this is a constraint that directly corresponds to a 11105 // RISCV register class. 11106 if (Constraint.size() == 1) { 11107 switch (Constraint[0]) { 11108 case 'r': 11109 // TODO: Support fixed vectors up to XLen for P extension? 11110 if (VT.isVector()) 11111 break; 11112 return std::make_pair(0U, &RISCV::GPRRegClass); 11113 case 'f': 11114 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11115 return std::make_pair(0U, &RISCV::FPR16RegClass); 11116 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11117 return std::make_pair(0U, &RISCV::FPR32RegClass); 11118 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11119 return std::make_pair(0U, &RISCV::FPR64RegClass); 11120 break; 11121 default: 11122 break; 11123 } 11124 } else if (Constraint == "vr") { 11125 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11126 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11127 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11128 return std::make_pair(0U, RC); 11129 } 11130 } else if (Constraint == "vm") { 11131 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11132 return std::make_pair(0U, &RISCV::VMV0RegClass); 11133 } 11134 11135 // Clang will correctly decode the usage of register name aliases into their 11136 // official names. However, other frontends like `rustc` do not. This allows 11137 // users of these frontends to use the ABI names for registers in LLVM-style 11138 // register constraints. 11139 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11140 .Case("{zero}", RISCV::X0) 11141 .Case("{ra}", RISCV::X1) 11142 .Case("{sp}", RISCV::X2) 11143 .Case("{gp}", RISCV::X3) 11144 .Case("{tp}", RISCV::X4) 11145 .Case("{t0}", RISCV::X5) 11146 .Case("{t1}", RISCV::X6) 11147 .Case("{t2}", RISCV::X7) 11148 .Cases("{s0}", "{fp}", RISCV::X8) 11149 .Case("{s1}", RISCV::X9) 11150 .Case("{a0}", RISCV::X10) 11151 .Case("{a1}", RISCV::X11) 11152 .Case("{a2}", RISCV::X12) 11153 .Case("{a3}", RISCV::X13) 11154 .Case("{a4}", RISCV::X14) 11155 .Case("{a5}", RISCV::X15) 11156 .Case("{a6}", RISCV::X16) 11157 .Case("{a7}", RISCV::X17) 11158 .Case("{s2}", RISCV::X18) 11159 .Case("{s3}", RISCV::X19) 11160 .Case("{s4}", RISCV::X20) 11161 .Case("{s5}", RISCV::X21) 11162 .Case("{s6}", RISCV::X22) 11163 .Case("{s7}", RISCV::X23) 11164 .Case("{s8}", RISCV::X24) 11165 .Case("{s9}", RISCV::X25) 11166 .Case("{s10}", RISCV::X26) 11167 .Case("{s11}", RISCV::X27) 11168 .Case("{t3}", RISCV::X28) 11169 .Case("{t4}", RISCV::X29) 11170 .Case("{t5}", RISCV::X30) 11171 .Case("{t6}", RISCV::X31) 11172 .Default(RISCV::NoRegister); 11173 if (XRegFromAlias != RISCV::NoRegister) 11174 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11175 11176 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11177 // TableGen record rather than the AsmName to choose registers for InlineAsm 11178 // constraints, plus we want to match those names to the widest floating point 11179 // register type available, manually select floating point registers here. 11180 // 11181 // The second case is the ABI name of the register, so that frontends can also 11182 // use the ABI names in register constraint lists. 11183 if (Subtarget.hasStdExtF()) { 11184 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11185 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11186 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11187 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11188 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11189 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11190 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11191 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11192 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11193 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11194 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11195 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11196 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11197 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11198 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11199 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11200 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11201 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11202 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11203 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11204 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11205 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11206 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11207 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11208 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11209 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11210 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11211 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11212 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11213 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11214 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11215 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11216 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11217 .Default(RISCV::NoRegister); 11218 if (FReg != RISCV::NoRegister) { 11219 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11220 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11221 unsigned RegNo = FReg - RISCV::F0_F; 11222 unsigned DReg = RISCV::F0_D + RegNo; 11223 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11224 } 11225 if (VT == MVT::f32 || VT == MVT::Other) 11226 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11227 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11228 unsigned RegNo = FReg - RISCV::F0_F; 11229 unsigned HReg = RISCV::F0_H + RegNo; 11230 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11231 } 11232 } 11233 } 11234 11235 if (Subtarget.hasVInstructions()) { 11236 Register VReg = StringSwitch<Register>(Constraint.lower()) 11237 .Case("{v0}", RISCV::V0) 11238 .Case("{v1}", RISCV::V1) 11239 .Case("{v2}", RISCV::V2) 11240 .Case("{v3}", RISCV::V3) 11241 .Case("{v4}", RISCV::V4) 11242 .Case("{v5}", RISCV::V5) 11243 .Case("{v6}", RISCV::V6) 11244 .Case("{v7}", RISCV::V7) 11245 .Case("{v8}", RISCV::V8) 11246 .Case("{v9}", RISCV::V9) 11247 .Case("{v10}", RISCV::V10) 11248 .Case("{v11}", RISCV::V11) 11249 .Case("{v12}", RISCV::V12) 11250 .Case("{v13}", RISCV::V13) 11251 .Case("{v14}", RISCV::V14) 11252 .Case("{v15}", RISCV::V15) 11253 .Case("{v16}", RISCV::V16) 11254 .Case("{v17}", RISCV::V17) 11255 .Case("{v18}", RISCV::V18) 11256 .Case("{v19}", RISCV::V19) 11257 .Case("{v20}", RISCV::V20) 11258 .Case("{v21}", RISCV::V21) 11259 .Case("{v22}", RISCV::V22) 11260 .Case("{v23}", RISCV::V23) 11261 .Case("{v24}", RISCV::V24) 11262 .Case("{v25}", RISCV::V25) 11263 .Case("{v26}", RISCV::V26) 11264 .Case("{v27}", RISCV::V27) 11265 .Case("{v28}", RISCV::V28) 11266 .Case("{v29}", RISCV::V29) 11267 .Case("{v30}", RISCV::V30) 11268 .Case("{v31}", RISCV::V31) 11269 .Default(RISCV::NoRegister); 11270 if (VReg != RISCV::NoRegister) { 11271 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11272 return std::make_pair(VReg, &RISCV::VMRegClass); 11273 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11274 return std::make_pair(VReg, &RISCV::VRRegClass); 11275 for (const auto *RC : 11276 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11277 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11278 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11279 return std::make_pair(VReg, RC); 11280 } 11281 } 11282 } 11283 } 11284 11285 std::pair<Register, const TargetRegisterClass *> Res = 11286 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11287 11288 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11289 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11290 // Subtarget into account. 11291 if (Res.second == &RISCV::GPRF16RegClass || 11292 Res.second == &RISCV::GPRF32RegClass || 11293 Res.second == &RISCV::GPRF64RegClass) 11294 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11295 11296 return Res; 11297 } 11298 11299 unsigned 11300 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11301 // Currently only support length 1 constraints. 11302 if (ConstraintCode.size() == 1) { 11303 switch (ConstraintCode[0]) { 11304 case 'A': 11305 return InlineAsm::Constraint_A; 11306 default: 11307 break; 11308 } 11309 } 11310 11311 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11312 } 11313 11314 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11315 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11316 SelectionDAG &DAG) const { 11317 // Currently only support length 1 constraints. 11318 if (Constraint.length() == 1) { 11319 switch (Constraint[0]) { 11320 case 'I': 11321 // Validate & create a 12-bit signed immediate operand. 11322 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11323 uint64_t CVal = C->getSExtValue(); 11324 if (isInt<12>(CVal)) 11325 Ops.push_back( 11326 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11327 } 11328 return; 11329 case 'J': 11330 // Validate & create an integer zero operand. 11331 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11332 if (C->getZExtValue() == 0) 11333 Ops.push_back( 11334 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11335 return; 11336 case 'K': 11337 // Validate & create a 5-bit unsigned immediate operand. 11338 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11339 uint64_t CVal = C->getZExtValue(); 11340 if (isUInt<5>(CVal)) 11341 Ops.push_back( 11342 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11343 } 11344 return; 11345 case 'S': 11346 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11347 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11348 GA->getValueType(0))); 11349 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11350 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11351 BA->getValueType(0))); 11352 } 11353 return; 11354 default: 11355 break; 11356 } 11357 } 11358 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11359 } 11360 11361 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11362 Instruction *Inst, 11363 AtomicOrdering Ord) const { 11364 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11365 return Builder.CreateFence(Ord); 11366 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11367 return Builder.CreateFence(AtomicOrdering::Release); 11368 return nullptr; 11369 } 11370 11371 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11372 Instruction *Inst, 11373 AtomicOrdering Ord) const { 11374 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11375 return Builder.CreateFence(AtomicOrdering::Acquire); 11376 return nullptr; 11377 } 11378 11379 TargetLowering::AtomicExpansionKind 11380 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11381 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11382 // point operations can't be used in an lr/sc sequence without breaking the 11383 // forward-progress guarantee. 11384 if (AI->isFloatingPointOperation()) 11385 return AtomicExpansionKind::CmpXChg; 11386 11387 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11388 if (Size == 8 || Size == 16) 11389 return AtomicExpansionKind::MaskedIntrinsic; 11390 return AtomicExpansionKind::None; 11391 } 11392 11393 static Intrinsic::ID 11394 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11395 if (XLen == 32) { 11396 switch (BinOp) { 11397 default: 11398 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11399 case AtomicRMWInst::Xchg: 11400 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11401 case AtomicRMWInst::Add: 11402 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11403 case AtomicRMWInst::Sub: 11404 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11405 case AtomicRMWInst::Nand: 11406 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11407 case AtomicRMWInst::Max: 11408 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11409 case AtomicRMWInst::Min: 11410 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11411 case AtomicRMWInst::UMax: 11412 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11413 case AtomicRMWInst::UMin: 11414 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11415 } 11416 } 11417 11418 if (XLen == 64) { 11419 switch (BinOp) { 11420 default: 11421 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11422 case AtomicRMWInst::Xchg: 11423 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11424 case AtomicRMWInst::Add: 11425 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11426 case AtomicRMWInst::Sub: 11427 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11428 case AtomicRMWInst::Nand: 11429 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11430 case AtomicRMWInst::Max: 11431 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11432 case AtomicRMWInst::Min: 11433 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11434 case AtomicRMWInst::UMax: 11435 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11436 case AtomicRMWInst::UMin: 11437 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11438 } 11439 } 11440 11441 llvm_unreachable("Unexpected XLen\n"); 11442 } 11443 11444 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11445 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11446 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11447 unsigned XLen = Subtarget.getXLen(); 11448 Value *Ordering = 11449 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11450 Type *Tys[] = {AlignedAddr->getType()}; 11451 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11452 AI->getModule(), 11453 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11454 11455 if (XLen == 64) { 11456 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11457 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11458 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11459 } 11460 11461 Value *Result; 11462 11463 // Must pass the shift amount needed to sign extend the loaded value prior 11464 // to performing a signed comparison for min/max. ShiftAmt is the number of 11465 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11466 // is the number of bits to left+right shift the value in order to 11467 // sign-extend. 11468 if (AI->getOperation() == AtomicRMWInst::Min || 11469 AI->getOperation() == AtomicRMWInst::Max) { 11470 const DataLayout &DL = AI->getModule()->getDataLayout(); 11471 unsigned ValWidth = 11472 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11473 Value *SextShamt = 11474 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11475 Result = Builder.CreateCall(LrwOpScwLoop, 11476 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11477 } else { 11478 Result = 11479 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11480 } 11481 11482 if (XLen == 64) 11483 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11484 return Result; 11485 } 11486 11487 TargetLowering::AtomicExpansionKind 11488 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11489 AtomicCmpXchgInst *CI) const { 11490 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11491 if (Size == 8 || Size == 16) 11492 return AtomicExpansionKind::MaskedIntrinsic; 11493 return AtomicExpansionKind::None; 11494 } 11495 11496 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11497 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11498 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11499 unsigned XLen = Subtarget.getXLen(); 11500 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11501 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11502 if (XLen == 64) { 11503 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11504 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11505 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11506 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11507 } 11508 Type *Tys[] = {AlignedAddr->getType()}; 11509 Function *MaskedCmpXchg = 11510 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11511 Value *Result = Builder.CreateCall( 11512 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11513 if (XLen == 64) 11514 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11515 return Result; 11516 } 11517 11518 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11519 return false; 11520 } 11521 11522 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11523 EVT VT) const { 11524 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11525 return false; 11526 11527 switch (FPVT.getSimpleVT().SimpleTy) { 11528 case MVT::f16: 11529 return Subtarget.hasStdExtZfh(); 11530 case MVT::f32: 11531 return Subtarget.hasStdExtF(); 11532 case MVT::f64: 11533 return Subtarget.hasStdExtD(); 11534 default: 11535 return false; 11536 } 11537 } 11538 11539 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11540 // If we are using the small code model, we can reduce size of jump table 11541 // entry to 4 bytes. 11542 if (Subtarget.is64Bit() && !isPositionIndependent() && 11543 getTargetMachine().getCodeModel() == CodeModel::Small) { 11544 return MachineJumpTableInfo::EK_Custom32; 11545 } 11546 return TargetLowering::getJumpTableEncoding(); 11547 } 11548 11549 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11550 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11551 unsigned uid, MCContext &Ctx) const { 11552 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11553 getTargetMachine().getCodeModel() == CodeModel::Small); 11554 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11555 } 11556 11557 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11558 EVT VT) const { 11559 VT = VT.getScalarType(); 11560 11561 if (!VT.isSimple()) 11562 return false; 11563 11564 switch (VT.getSimpleVT().SimpleTy) { 11565 case MVT::f16: 11566 return Subtarget.hasStdExtZfh(); 11567 case MVT::f32: 11568 return Subtarget.hasStdExtF(); 11569 case MVT::f64: 11570 return Subtarget.hasStdExtD(); 11571 default: 11572 break; 11573 } 11574 11575 return false; 11576 } 11577 11578 Register RISCVTargetLowering::getExceptionPointerRegister( 11579 const Constant *PersonalityFn) const { 11580 return RISCV::X10; 11581 } 11582 11583 Register RISCVTargetLowering::getExceptionSelectorRegister( 11584 const Constant *PersonalityFn) const { 11585 return RISCV::X11; 11586 } 11587 11588 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11589 // Return false to suppress the unnecessary extensions if the LibCall 11590 // arguments or return value is f32 type for LP64 ABI. 11591 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11592 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11593 return false; 11594 11595 return true; 11596 } 11597 11598 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11599 if (Subtarget.is64Bit() && Type == MVT::i32) 11600 return true; 11601 11602 return IsSigned; 11603 } 11604 11605 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11606 SDValue C) const { 11607 // Check integral scalar types. 11608 if (VT.isScalarInteger()) { 11609 // Omit the optimization if the sub target has the M extension and the data 11610 // size exceeds XLen. 11611 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11612 return false; 11613 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11614 // Break the MUL to a SLLI and an ADD/SUB. 11615 const APInt &Imm = ConstNode->getAPIntValue(); 11616 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11617 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11618 return true; 11619 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11620 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11621 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11622 (Imm - 8).isPowerOf2())) 11623 return true; 11624 // Omit the following optimization if the sub target has the M extension 11625 // and the data size >= XLen. 11626 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11627 return false; 11628 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11629 // a pair of LUI/ADDI. 11630 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11631 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11632 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11633 (1 - ImmS).isPowerOf2()) 11634 return true; 11635 } 11636 } 11637 } 11638 11639 return false; 11640 } 11641 11642 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11643 SDValue ConstNode) const { 11644 // Let the DAGCombiner decide for vectors. 11645 EVT VT = AddNode.getValueType(); 11646 if (VT.isVector()) 11647 return true; 11648 11649 // Let the DAGCombiner decide for larger types. 11650 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11651 return true; 11652 11653 // It is worse if c1 is simm12 while c1*c2 is not. 11654 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11655 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11656 const APInt &C1 = C1Node->getAPIntValue(); 11657 const APInt &C2 = C2Node->getAPIntValue(); 11658 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11659 return false; 11660 11661 // Default to true and let the DAGCombiner decide. 11662 return true; 11663 } 11664 11665 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11666 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11667 bool *Fast) const { 11668 if (!VT.isVector()) 11669 return false; 11670 11671 EVT ElemVT = VT.getVectorElementType(); 11672 if (Alignment >= ElemVT.getStoreSize()) { 11673 if (Fast) 11674 *Fast = true; 11675 return true; 11676 } 11677 11678 return false; 11679 } 11680 11681 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11682 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11683 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11684 bool IsABIRegCopy = CC.hasValue(); 11685 EVT ValueVT = Val.getValueType(); 11686 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11687 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11688 // and cast to f32. 11689 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11690 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11691 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11692 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11693 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11694 Parts[0] = Val; 11695 return true; 11696 } 11697 11698 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11699 LLVMContext &Context = *DAG.getContext(); 11700 EVT ValueEltVT = ValueVT.getVectorElementType(); 11701 EVT PartEltVT = PartVT.getVectorElementType(); 11702 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11703 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11704 if (PartVTBitSize % ValueVTBitSize == 0) { 11705 assert(PartVTBitSize >= ValueVTBitSize); 11706 // If the element types are different, bitcast to the same element type of 11707 // PartVT first. 11708 // Give an example here, we want copy a <vscale x 1 x i8> value to 11709 // <vscale x 4 x i16>. 11710 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11711 // subvector, then we can bitcast to <vscale x 4 x i16>. 11712 if (ValueEltVT != PartEltVT) { 11713 if (PartVTBitSize > ValueVTBitSize) { 11714 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11715 assert(Count != 0 && "The number of element should not be zero."); 11716 EVT SameEltTypeVT = 11717 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11718 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11719 DAG.getUNDEF(SameEltTypeVT), Val, 11720 DAG.getVectorIdxConstant(0, DL)); 11721 } 11722 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11723 } else { 11724 Val = 11725 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11726 Val, DAG.getVectorIdxConstant(0, DL)); 11727 } 11728 Parts[0] = Val; 11729 return true; 11730 } 11731 } 11732 return false; 11733 } 11734 11735 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11736 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11737 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11738 bool IsABIRegCopy = CC.hasValue(); 11739 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11740 SDValue Val = Parts[0]; 11741 11742 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11743 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11744 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11745 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11746 return Val; 11747 } 11748 11749 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11750 LLVMContext &Context = *DAG.getContext(); 11751 SDValue Val = Parts[0]; 11752 EVT ValueEltVT = ValueVT.getVectorElementType(); 11753 EVT PartEltVT = PartVT.getVectorElementType(); 11754 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11755 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11756 if (PartVTBitSize % ValueVTBitSize == 0) { 11757 assert(PartVTBitSize >= ValueVTBitSize); 11758 EVT SameEltTypeVT = ValueVT; 11759 // If the element types are different, convert it to the same element type 11760 // of PartVT. 11761 // Give an example here, we want copy a <vscale x 1 x i8> value from 11762 // <vscale x 4 x i16>. 11763 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11764 // then we can extract <vscale x 1 x i8>. 11765 if (ValueEltVT != PartEltVT) { 11766 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11767 assert(Count != 0 && "The number of element should not be zero."); 11768 SameEltTypeVT = 11769 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11770 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11771 } 11772 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11773 DAG.getVectorIdxConstant(0, DL)); 11774 return Val; 11775 } 11776 } 11777 return SDValue(); 11778 } 11779 11780 SDValue 11781 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11782 SelectionDAG &DAG, 11783 SmallVectorImpl<SDNode *> &Created) const { 11784 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11785 if (isIntDivCheap(N->getValueType(0), Attr)) 11786 return SDValue(N, 0); // Lower SDIV as SDIV 11787 11788 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11789 "Unexpected divisor!"); 11790 11791 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11792 if (!Subtarget.hasStdExtZbt()) 11793 return SDValue(); 11794 11795 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11796 // Besides, more critical path instructions will be generated when dividing 11797 // by 2. So we keep using the original DAGs for these cases. 11798 unsigned Lg2 = Divisor.countTrailingZeros(); 11799 if (Lg2 == 1 || Lg2 >= 12) 11800 return SDValue(); 11801 11802 // fold (sdiv X, pow2) 11803 EVT VT = N->getValueType(0); 11804 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11805 return SDValue(); 11806 11807 SDLoc DL(N); 11808 SDValue N0 = N->getOperand(0); 11809 SDValue Zero = DAG.getConstant(0, DL, VT); 11810 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11811 11812 // Add (N0 < 0) ? Pow2 - 1 : 0; 11813 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11814 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11815 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11816 11817 Created.push_back(Cmp.getNode()); 11818 Created.push_back(Add.getNode()); 11819 Created.push_back(Sel.getNode()); 11820 11821 // Divide by pow2. 11822 SDValue SRA = 11823 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11824 11825 // If we're dividing by a positive value, we're done. Otherwise, we must 11826 // negate the result. 11827 if (Divisor.isNonNegative()) 11828 return SRA; 11829 11830 Created.push_back(SRA.getNode()); 11831 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11832 } 11833 11834 #define GET_REGISTER_MATCHER 11835 #include "RISCVGenAsmMatcher.inc" 11836 11837 Register 11838 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11839 const MachineFunction &MF) const { 11840 Register Reg = MatchRegisterAltName(RegName); 11841 if (Reg == RISCV::NoRegister) 11842 Reg = MatchRegisterName(RegName); 11843 if (Reg == RISCV::NoRegister) 11844 report_fatal_error( 11845 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11846 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11847 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11848 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11849 StringRef(RegName) + "\".")); 11850 return Reg; 11851 } 11852 11853 namespace llvm { 11854 namespace RISCVVIntrinsicsTable { 11855 11856 #define GET_RISCVVIntrinsicsTable_IMPL 11857 #include "RISCVGenSearchableTables.inc" 11858 11859 } // namespace RISCVVIntrinsicsTable 11860 11861 } // namespace llvm 11862