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_SIGN_EXTEND, 436 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 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 ISD::VP_FP_EXTEND}; 448 449 if (!Subtarget.is64Bit()) { 450 // We must custom-lower certain vXi64 operations on RV32 due to the vector 451 // element type being illegal. 452 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 453 MVT::i64, Custom); 454 455 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 456 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 457 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 458 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 459 MVT::i64, Custom); 460 461 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 462 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 463 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 464 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 465 MVT::i64, Custom); 466 } 467 468 for (MVT VT : BoolVecVTs) { 469 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 470 471 // Mask VTs are custom-expanded into a series of standard nodes 472 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 473 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 474 VT, Custom); 475 476 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 477 Custom); 478 479 setOperationAction(ISD::SELECT, VT, Custom); 480 setOperationAction( 481 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 482 Expand); 483 484 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 485 486 setOperationAction( 487 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 488 Custom); 489 490 setOperationAction( 491 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 492 Custom); 493 494 // RVV has native int->float & float->int conversions where the 495 // element type sizes are within one power-of-two of each other. Any 496 // wider distances between type sizes have to be lowered as sequences 497 // which progressively narrow the gap in stages. 498 setOperationAction( 499 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 500 VT, Custom); 501 502 // Expand all extending loads to types larger than this, and truncating 503 // stores from types larger than this. 504 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 505 setTruncStoreAction(OtherVT, VT, Expand); 506 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 507 VT, Expand); 508 } 509 510 setOperationAction( 511 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 512 Custom); 513 } 514 515 for (MVT VT : IntVecVTs) { 516 if (VT.getVectorElementType() == MVT::i64 && 517 !Subtarget.hasVInstructionsI64()) 518 continue; 519 520 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 521 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 522 523 // Vectors implement MULHS/MULHU. 524 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 525 526 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 527 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 528 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 529 530 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 531 Legal); 532 533 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 534 535 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 536 Expand); 537 538 setOperationAction(ISD::BSWAP, VT, Expand); 539 540 // Custom-lower extensions and truncations from/to mask types. 541 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 542 VT, Custom); 543 544 // RVV has native int->float & float->int conversions where the 545 // element type sizes are within one power-of-two of each other. Any 546 // wider distances between type sizes have to be lowered as sequences 547 // which progressively narrow the gap in stages. 548 setOperationAction( 549 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 550 VT, Custom); 551 552 setOperationAction( 553 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 554 555 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 556 // nodes which truncate by one power of two at a time. 557 setOperationAction(ISD::TRUNCATE, VT, Custom); 558 559 // Custom-lower insert/extract operations to simplify patterns. 560 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 561 Custom); 562 563 // Custom-lower reduction operations to set up the corresponding custom 564 // nodes' operands. 565 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 566 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 567 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 568 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 569 VT, Custom); 570 571 for (unsigned VPOpc : IntegerVPOps) 572 setOperationAction(VPOpc, VT, Custom); 573 574 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 575 576 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 577 VT, Custom); 578 579 setOperationAction( 580 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 581 Custom); 582 583 setOperationAction( 584 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 585 VT, Custom); 586 587 setOperationAction(ISD::SELECT, VT, Custom); 588 setOperationAction(ISD::SELECT_CC, VT, Expand); 589 590 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 591 592 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 593 setTruncStoreAction(VT, OtherVT, Expand); 594 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 595 VT, Expand); 596 } 597 598 // Splice 599 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 600 601 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 602 // type that can represent the value exactly. 603 if (VT.getVectorElementType() != MVT::i64) { 604 MVT FloatEltVT = 605 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 606 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 607 if (isTypeLegal(FloatVT)) { 608 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 609 Custom); 610 } 611 } 612 } 613 614 // Expand various CCs to best match the RVV ISA, which natively supports UNE 615 // but no other unordered comparisons, and supports all ordered comparisons 616 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 617 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 618 // and we pattern-match those back to the "original", swapping operands once 619 // more. This way we catch both operations and both "vf" and "fv" forms with 620 // fewer patterns. 621 static const ISD::CondCode VFPCCToExpand[] = { 622 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 623 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 624 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 625 }; 626 627 // Sets common operation actions on RVV floating-point vector types. 628 const auto SetCommonVFPActions = [&](MVT VT) { 629 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 630 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 631 // sizes are within one power-of-two of each other. Therefore conversions 632 // between vXf16 and vXf64 must be lowered as sequences which convert via 633 // vXf32. 634 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 635 // Custom-lower insert/extract operations to simplify patterns. 636 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 637 Custom); 638 // Expand various condition codes (explained above). 639 for (auto CC : VFPCCToExpand) 640 setCondCodeAction(CC, VT, Expand); 641 642 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 643 644 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 645 VT, Custom); 646 647 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 648 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 649 VT, Custom); 650 651 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 652 653 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 654 655 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 656 VT, Custom); 657 658 setOperationAction( 659 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 660 Custom); 661 662 setOperationAction(ISD::SELECT, VT, Custom); 663 setOperationAction(ISD::SELECT_CC, VT, Expand); 664 665 setOperationAction( 666 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 667 VT, Custom); 668 669 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 670 671 for (unsigned VPOpc : FloatingPointVPOps) 672 setOperationAction(VPOpc, VT, Custom); 673 }; 674 675 // Sets common extload/truncstore actions on RVV floating-point vector 676 // types. 677 const auto SetCommonVFPExtLoadTruncStoreActions = 678 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 679 for (auto SmallVT : SmallerVTs) { 680 setTruncStoreAction(VT, SmallVT, Expand); 681 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 682 } 683 }; 684 685 if (Subtarget.hasVInstructionsF16()) 686 for (MVT VT : F16VecVTs) 687 SetCommonVFPActions(VT); 688 689 for (MVT VT : F32VecVTs) { 690 if (Subtarget.hasVInstructionsF32()) 691 SetCommonVFPActions(VT); 692 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 693 } 694 695 for (MVT VT : F64VecVTs) { 696 if (Subtarget.hasVInstructionsF64()) 697 SetCommonVFPActions(VT); 698 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 699 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 700 } 701 702 if (Subtarget.useRVVForFixedLengthVectors()) { 703 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 704 if (!useRVVForFixedLengthVectorVT(VT)) 705 continue; 706 707 // By default everything must be expanded. 708 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 709 setOperationAction(Op, VT, Expand); 710 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 711 setTruncStoreAction(VT, OtherVT, Expand); 712 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 713 OtherVT, VT, Expand); 714 } 715 716 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 717 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 718 Custom); 719 720 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 721 Custom); 722 723 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 724 VT, Custom); 725 726 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 727 728 setOperationAction(ISD::SETCC, VT, Custom); 729 730 setOperationAction(ISD::SELECT, VT, Custom); 731 732 setOperationAction(ISD::TRUNCATE, VT, Custom); 733 734 setOperationAction(ISD::BITCAST, VT, Custom); 735 736 setOperationAction( 737 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 738 Custom); 739 740 setOperationAction( 741 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 742 Custom); 743 744 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 745 ISD::FP_TO_UINT}, 746 VT, Custom); 747 748 // Operations below are different for between masks and other vectors. 749 if (VT.getVectorElementType() == MVT::i1) { 750 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 751 ISD::OR, ISD::XOR}, 752 VT, Custom); 753 754 setOperationAction( 755 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 756 VT, Custom); 757 continue; 758 } 759 760 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 761 // it before type legalization for i64 vectors on RV32. It will then be 762 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 763 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 764 // improvements first. 765 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 766 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 767 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 768 } 769 770 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 771 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 772 773 setOperationAction( 774 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 775 776 setOperationAction( 777 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 778 Custom); 779 780 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 781 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 782 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 783 VT, Custom); 784 785 setOperationAction( 786 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 787 788 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 789 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 790 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 791 792 setOperationAction( 793 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 794 Custom); 795 796 setOperationAction(ISD::VSELECT, VT, Custom); 797 setOperationAction(ISD::SELECT_CC, VT, Expand); 798 799 setOperationAction( 800 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 801 802 // Custom-lower reduction operations to set up the corresponding custom 803 // nodes' operands. 804 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 805 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 806 ISD::VECREDUCE_UMIN}, 807 VT, Custom); 808 809 for (unsigned VPOpc : IntegerVPOps) 810 setOperationAction(VPOpc, VT, Custom); 811 812 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 813 // type that can represent the value exactly. 814 if (VT.getVectorElementType() != MVT::i64) { 815 MVT FloatEltVT = 816 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 817 EVT FloatVT = 818 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 819 if (isTypeLegal(FloatVT)) 820 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 821 Custom); 822 } 823 } 824 825 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 826 if (!useRVVForFixedLengthVectorVT(VT)) 827 continue; 828 829 // By default everything must be expanded. 830 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 831 setOperationAction(Op, VT, Expand); 832 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 833 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 834 setTruncStoreAction(VT, OtherVT, Expand); 835 } 836 837 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 838 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 839 Custom); 840 841 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 842 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 843 ISD::EXTRACT_VECTOR_ELT}, 844 VT, Custom); 845 846 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 847 ISD::MGATHER, ISD::MSCATTER}, 848 VT, Custom); 849 850 setOperationAction( 851 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 852 Custom); 853 854 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 855 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 856 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 857 VT, Custom); 858 859 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 860 861 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 862 VT, Custom); 863 864 for (auto CC : VFPCCToExpand) 865 setCondCodeAction(CC, VT, Expand); 866 867 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 868 setOperationAction(ISD::SELECT_CC, VT, Expand); 869 870 setOperationAction(ISD::BITCAST, VT, Custom); 871 872 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 873 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 874 VT, Custom); 875 876 for (unsigned VPOpc : FloatingPointVPOps) 877 setOperationAction(VPOpc, VT, Custom); 878 } 879 880 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 881 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 882 Custom); 883 if (Subtarget.hasStdExtZfh()) 884 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 885 if (Subtarget.hasStdExtF()) 886 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 887 if (Subtarget.hasStdExtD()) 888 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 889 } 890 } 891 892 // Function alignments. 893 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 894 setMinFunctionAlignment(FunctionAlignment); 895 setPrefFunctionAlignment(FunctionAlignment); 896 897 setMinimumJumpTableEntries(5); 898 899 // Jumps are expensive, compared to logic 900 setJumpIsExpensive(); 901 902 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 903 ISD::OR, ISD::XOR}); 904 905 if (Subtarget.hasStdExtF()) 906 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 907 908 if (Subtarget.hasStdExtZbp()) 909 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 910 911 if (Subtarget.hasStdExtZbb()) 912 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 913 914 if (Subtarget.hasStdExtZbkb()) 915 setTargetDAGCombine(ISD::BITREVERSE); 916 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 917 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 918 if (Subtarget.hasStdExtF()) 919 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 920 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 921 if (Subtarget.hasVInstructions()) 922 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 923 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 924 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 925 926 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 927 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 928 } 929 930 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 931 LLVMContext &Context, 932 EVT VT) const { 933 if (!VT.isVector()) 934 return getPointerTy(DL); 935 if (Subtarget.hasVInstructions() && 936 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 937 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 938 return VT.changeVectorElementTypeToInteger(); 939 } 940 941 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 942 return Subtarget.getXLenVT(); 943 } 944 945 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 946 const CallInst &I, 947 MachineFunction &MF, 948 unsigned Intrinsic) const { 949 auto &DL = I.getModule()->getDataLayout(); 950 switch (Intrinsic) { 951 default: 952 return false; 953 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 954 case Intrinsic::riscv_masked_atomicrmw_add_i32: 955 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 956 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 957 case Intrinsic::riscv_masked_atomicrmw_max_i32: 958 case Intrinsic::riscv_masked_atomicrmw_min_i32: 959 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 960 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 961 case Intrinsic::riscv_masked_cmpxchg_i32: 962 Info.opc = ISD::INTRINSIC_W_CHAIN; 963 Info.memVT = MVT::i32; 964 Info.ptrVal = I.getArgOperand(0); 965 Info.offset = 0; 966 Info.align = Align(4); 967 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 968 MachineMemOperand::MOVolatile; 969 return true; 970 case Intrinsic::riscv_masked_strided_load: 971 Info.opc = ISD::INTRINSIC_W_CHAIN; 972 Info.ptrVal = I.getArgOperand(1); 973 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 974 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 975 Info.size = MemoryLocation::UnknownSize; 976 Info.flags |= MachineMemOperand::MOLoad; 977 return true; 978 case Intrinsic::riscv_masked_strided_store: 979 Info.opc = ISD::INTRINSIC_VOID; 980 Info.ptrVal = I.getArgOperand(1); 981 Info.memVT = 982 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 983 Info.align = Align( 984 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 985 8); 986 Info.size = MemoryLocation::UnknownSize; 987 Info.flags |= MachineMemOperand::MOStore; 988 return true; 989 case Intrinsic::riscv_seg2_load: 990 case Intrinsic::riscv_seg3_load: 991 case Intrinsic::riscv_seg4_load: 992 case Intrinsic::riscv_seg5_load: 993 case Intrinsic::riscv_seg6_load: 994 case Intrinsic::riscv_seg7_load: 995 case Intrinsic::riscv_seg8_load: 996 Info.opc = ISD::INTRINSIC_W_CHAIN; 997 Info.ptrVal = I.getArgOperand(0); 998 Info.memVT = 999 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1000 Info.align = 1001 Align(DL.getTypeSizeInBits( 1002 I.getType()->getStructElementType(0)->getScalarType()) / 1003 8); 1004 Info.size = MemoryLocation::UnknownSize; 1005 Info.flags |= MachineMemOperand::MOLoad; 1006 return true; 1007 } 1008 } 1009 1010 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1011 const AddrMode &AM, Type *Ty, 1012 unsigned AS, 1013 Instruction *I) const { 1014 // No global is ever allowed as a base. 1015 if (AM.BaseGV) 1016 return false; 1017 1018 // RVV instructions only support register addressing. 1019 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1020 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1021 1022 // Require a 12-bit signed offset. 1023 if (!isInt<12>(AM.BaseOffs)) 1024 return false; 1025 1026 switch (AM.Scale) { 1027 case 0: // "r+i" or just "i", depending on HasBaseReg. 1028 break; 1029 case 1: 1030 if (!AM.HasBaseReg) // allow "r+i". 1031 break; 1032 return false; // disallow "r+r" or "r+r+i". 1033 default: 1034 return false; 1035 } 1036 1037 return true; 1038 } 1039 1040 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1041 return isInt<12>(Imm); 1042 } 1043 1044 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1045 return isInt<12>(Imm); 1046 } 1047 1048 // On RV32, 64-bit integers are split into their high and low parts and held 1049 // in two different registers, so the trunc is free since the low register can 1050 // just be used. 1051 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1052 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1053 return false; 1054 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1055 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1056 return (SrcBits == 64 && DestBits == 32); 1057 } 1058 1059 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1060 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1061 !SrcVT.isInteger() || !DstVT.isInteger()) 1062 return false; 1063 unsigned SrcBits = SrcVT.getSizeInBits(); 1064 unsigned DestBits = DstVT.getSizeInBits(); 1065 return (SrcBits == 64 && DestBits == 32); 1066 } 1067 1068 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1069 // Zexts are free if they can be combined with a load. 1070 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1071 // poorly with type legalization of compares preferring sext. 1072 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1073 EVT MemVT = LD->getMemoryVT(); 1074 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1075 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1076 LD->getExtensionType() == ISD::ZEXTLOAD)) 1077 return true; 1078 } 1079 1080 return TargetLowering::isZExtFree(Val, VT2); 1081 } 1082 1083 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1084 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1085 } 1086 1087 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1088 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1089 } 1090 1091 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1092 return Subtarget.hasStdExtZbb(); 1093 } 1094 1095 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1096 return Subtarget.hasStdExtZbb(); 1097 } 1098 1099 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1100 EVT VT = Y.getValueType(); 1101 1102 // FIXME: Support vectors once we have tests. 1103 if (VT.isVector()) 1104 return false; 1105 1106 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1107 Subtarget.hasStdExtZbkb()) && 1108 !isa<ConstantSDNode>(Y); 1109 } 1110 1111 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1112 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1113 auto *C = dyn_cast<ConstantSDNode>(Y); 1114 return C && C->getAPIntValue().ule(10); 1115 } 1116 1117 bool RISCVTargetLowering:: 1118 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1119 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1120 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1121 SelectionDAG &DAG) const { 1122 // One interesting pattern that we'd want to form is 'bit extract': 1123 // ((1 >> Y) & 1) ==/!= 0 1124 // But we also need to be careful not to try to reverse that fold. 1125 1126 // Is this '((1 >> Y) & 1)'? 1127 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1128 return false; // Keep the 'bit extract' pattern. 1129 1130 // Will this be '((1 >> Y) & 1)' after the transform? 1131 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1132 return true; // Do form the 'bit extract' pattern. 1133 1134 // If 'X' is a constant, and we transform, then we will immediately 1135 // try to undo the fold, thus causing endless combine loop. 1136 // So only do the transform if X is not a constant. This matches the default 1137 // implementation of this function. 1138 return !XC; 1139 } 1140 1141 /// Check if sinking \p I's operands to I's basic block is profitable, because 1142 /// the operands can be folded into a target instruction, e.g. 1143 /// splats of scalars can fold into vector instructions. 1144 bool RISCVTargetLowering::shouldSinkOperands( 1145 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1146 using namespace llvm::PatternMatch; 1147 1148 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1149 return false; 1150 1151 auto IsSinker = [&](Instruction *I, int Operand) { 1152 switch (I->getOpcode()) { 1153 case Instruction::Add: 1154 case Instruction::Sub: 1155 case Instruction::Mul: 1156 case Instruction::And: 1157 case Instruction::Or: 1158 case Instruction::Xor: 1159 case Instruction::FAdd: 1160 case Instruction::FSub: 1161 case Instruction::FMul: 1162 case Instruction::FDiv: 1163 case Instruction::ICmp: 1164 case Instruction::FCmp: 1165 return true; 1166 case Instruction::Shl: 1167 case Instruction::LShr: 1168 case Instruction::AShr: 1169 case Instruction::UDiv: 1170 case Instruction::SDiv: 1171 case Instruction::URem: 1172 case Instruction::SRem: 1173 return Operand == 1; 1174 case Instruction::Call: 1175 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1176 switch (II->getIntrinsicID()) { 1177 case Intrinsic::fma: 1178 case Intrinsic::vp_fma: 1179 return Operand == 0 || Operand == 1; 1180 // FIXME: Our patterns can only match vx/vf instructions when the splat 1181 // it on the RHS, because TableGen doesn't recognize our VP operations 1182 // as commutative. 1183 case Intrinsic::vp_add: 1184 case Intrinsic::vp_mul: 1185 case Intrinsic::vp_and: 1186 case Intrinsic::vp_or: 1187 case Intrinsic::vp_xor: 1188 case Intrinsic::vp_fadd: 1189 case Intrinsic::vp_fmul: 1190 case Intrinsic::vp_shl: 1191 case Intrinsic::vp_lshr: 1192 case Intrinsic::vp_ashr: 1193 case Intrinsic::vp_udiv: 1194 case Intrinsic::vp_sdiv: 1195 case Intrinsic::vp_urem: 1196 case Intrinsic::vp_srem: 1197 return Operand == 1; 1198 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1199 // explicit patterns for both LHS and RHS (as 'vr' versions). 1200 case Intrinsic::vp_sub: 1201 case Intrinsic::vp_fsub: 1202 case Intrinsic::vp_fdiv: 1203 return Operand == 0 || Operand == 1; 1204 default: 1205 return false; 1206 } 1207 } 1208 return false; 1209 default: 1210 return false; 1211 } 1212 }; 1213 1214 for (auto OpIdx : enumerate(I->operands())) { 1215 if (!IsSinker(I, OpIdx.index())) 1216 continue; 1217 1218 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1219 // Make sure we are not already sinking this operand 1220 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1221 continue; 1222 1223 // We are looking for a splat that can be sunk. 1224 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1225 m_Undef(), m_ZeroMask()))) 1226 continue; 1227 1228 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1229 // and vector registers 1230 for (Use &U : Op->uses()) { 1231 Instruction *Insn = cast<Instruction>(U.getUser()); 1232 if (!IsSinker(Insn, U.getOperandNo())) 1233 return false; 1234 } 1235 1236 Ops.push_back(&Op->getOperandUse(0)); 1237 Ops.push_back(&OpIdx.value()); 1238 } 1239 return true; 1240 } 1241 1242 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1243 bool ForCodeSize) const { 1244 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1245 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1246 return false; 1247 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1248 return false; 1249 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1250 return false; 1251 return Imm.isZero(); 1252 } 1253 1254 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1255 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1256 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1257 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1258 } 1259 1260 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1261 CallingConv::ID CC, 1262 EVT VT) const { 1263 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1264 // We might still end up using a GPR but that will be decided based on ABI. 1265 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1266 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1267 return MVT::f32; 1268 1269 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1270 } 1271 1272 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1273 CallingConv::ID CC, 1274 EVT VT) const { 1275 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1276 // We might still end up using a GPR but that will be decided based on ABI. 1277 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1278 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1279 return 1; 1280 1281 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1282 } 1283 1284 // Changes the condition code and swaps operands if necessary, so the SetCC 1285 // operation matches one of the comparisons supported directly by branches 1286 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1287 // with 1/-1. 1288 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1289 ISD::CondCode &CC, SelectionDAG &DAG) { 1290 // Convert X > -1 to X >= 0. 1291 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1292 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1293 CC = ISD::SETGE; 1294 return; 1295 } 1296 // Convert X < 1 to 0 >= X. 1297 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1298 RHS = LHS; 1299 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1300 CC = ISD::SETGE; 1301 return; 1302 } 1303 1304 switch (CC) { 1305 default: 1306 break; 1307 case ISD::SETGT: 1308 case ISD::SETLE: 1309 case ISD::SETUGT: 1310 case ISD::SETULE: 1311 CC = ISD::getSetCCSwappedOperands(CC); 1312 std::swap(LHS, RHS); 1313 break; 1314 } 1315 } 1316 1317 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1318 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1319 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1320 if (VT.getVectorElementType() == MVT::i1) 1321 KnownSize *= 8; 1322 1323 switch (KnownSize) { 1324 default: 1325 llvm_unreachable("Invalid LMUL."); 1326 case 8: 1327 return RISCVII::VLMUL::LMUL_F8; 1328 case 16: 1329 return RISCVII::VLMUL::LMUL_F4; 1330 case 32: 1331 return RISCVII::VLMUL::LMUL_F2; 1332 case 64: 1333 return RISCVII::VLMUL::LMUL_1; 1334 case 128: 1335 return RISCVII::VLMUL::LMUL_2; 1336 case 256: 1337 return RISCVII::VLMUL::LMUL_4; 1338 case 512: 1339 return RISCVII::VLMUL::LMUL_8; 1340 } 1341 } 1342 1343 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1344 switch (LMul) { 1345 default: 1346 llvm_unreachable("Invalid LMUL."); 1347 case RISCVII::VLMUL::LMUL_F8: 1348 case RISCVII::VLMUL::LMUL_F4: 1349 case RISCVII::VLMUL::LMUL_F2: 1350 case RISCVII::VLMUL::LMUL_1: 1351 return RISCV::VRRegClassID; 1352 case RISCVII::VLMUL::LMUL_2: 1353 return RISCV::VRM2RegClassID; 1354 case RISCVII::VLMUL::LMUL_4: 1355 return RISCV::VRM4RegClassID; 1356 case RISCVII::VLMUL::LMUL_8: 1357 return RISCV::VRM8RegClassID; 1358 } 1359 } 1360 1361 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1362 RISCVII::VLMUL LMUL = getLMUL(VT); 1363 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1364 LMUL == RISCVII::VLMUL::LMUL_F4 || 1365 LMUL == RISCVII::VLMUL::LMUL_F2 || 1366 LMUL == RISCVII::VLMUL::LMUL_1) { 1367 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1368 "Unexpected subreg numbering"); 1369 return RISCV::sub_vrm1_0 + Index; 1370 } 1371 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1372 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1373 "Unexpected subreg numbering"); 1374 return RISCV::sub_vrm2_0 + Index; 1375 } 1376 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1377 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1378 "Unexpected subreg numbering"); 1379 return RISCV::sub_vrm4_0 + Index; 1380 } 1381 llvm_unreachable("Invalid vector type."); 1382 } 1383 1384 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1385 if (VT.getVectorElementType() == MVT::i1) 1386 return RISCV::VRRegClassID; 1387 return getRegClassIDForLMUL(getLMUL(VT)); 1388 } 1389 1390 // Attempt to decompose a subvector insert/extract between VecVT and 1391 // SubVecVT via subregister indices. Returns the subregister index that 1392 // can perform the subvector insert/extract with the given element index, as 1393 // well as the index corresponding to any leftover subvectors that must be 1394 // further inserted/extracted within the register class for SubVecVT. 1395 std::pair<unsigned, unsigned> 1396 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1397 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1398 const RISCVRegisterInfo *TRI) { 1399 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1400 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1401 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1402 "Register classes not ordered"); 1403 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1404 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1405 // Try to compose a subregister index that takes us from the incoming 1406 // LMUL>1 register class down to the outgoing one. At each step we half 1407 // the LMUL: 1408 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1409 // Note that this is not guaranteed to find a subregister index, such as 1410 // when we are extracting from one VR type to another. 1411 unsigned SubRegIdx = RISCV::NoSubRegister; 1412 for (const unsigned RCID : 1413 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1414 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1415 VecVT = VecVT.getHalfNumVectorElementsVT(); 1416 bool IsHi = 1417 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1418 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1419 getSubregIndexByMVT(VecVT, IsHi)); 1420 if (IsHi) 1421 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1422 } 1423 return {SubRegIdx, InsertExtractIdx}; 1424 } 1425 1426 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1427 // stores for those types. 1428 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1429 return !Subtarget.useRVVForFixedLengthVectors() || 1430 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1431 } 1432 1433 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1434 if (ScalarTy->isPointerTy()) 1435 return true; 1436 1437 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1438 ScalarTy->isIntegerTy(32)) 1439 return true; 1440 1441 if (ScalarTy->isIntegerTy(64)) 1442 return Subtarget.hasVInstructionsI64(); 1443 1444 if (ScalarTy->isHalfTy()) 1445 return Subtarget.hasVInstructionsF16(); 1446 if (ScalarTy->isFloatTy()) 1447 return Subtarget.hasVInstructionsF32(); 1448 if (ScalarTy->isDoubleTy()) 1449 return Subtarget.hasVInstructionsF64(); 1450 1451 return false; 1452 } 1453 1454 static SDValue getVLOperand(SDValue Op) { 1455 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1456 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1457 "Unexpected opcode"); 1458 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1459 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1460 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1461 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1462 if (!II) 1463 return SDValue(); 1464 return Op.getOperand(II->VLOperand + 1 + HasChain); 1465 } 1466 1467 static bool useRVVForFixedLengthVectorVT(MVT VT, 1468 const RISCVSubtarget &Subtarget) { 1469 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1470 if (!Subtarget.useRVVForFixedLengthVectors()) 1471 return false; 1472 1473 // We only support a set of vector types with a consistent maximum fixed size 1474 // across all supported vector element types to avoid legalization issues. 1475 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1476 // fixed-length vector type we support is 1024 bytes. 1477 if (VT.getFixedSizeInBits() > 1024 * 8) 1478 return false; 1479 1480 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1481 1482 MVT EltVT = VT.getVectorElementType(); 1483 1484 // Don't use RVV for vectors we cannot scalarize if required. 1485 switch (EltVT.SimpleTy) { 1486 // i1 is supported but has different rules. 1487 default: 1488 return false; 1489 case MVT::i1: 1490 // Masks can only use a single register. 1491 if (VT.getVectorNumElements() > MinVLen) 1492 return false; 1493 MinVLen /= 8; 1494 break; 1495 case MVT::i8: 1496 case MVT::i16: 1497 case MVT::i32: 1498 break; 1499 case MVT::i64: 1500 if (!Subtarget.hasVInstructionsI64()) 1501 return false; 1502 break; 1503 case MVT::f16: 1504 if (!Subtarget.hasVInstructionsF16()) 1505 return false; 1506 break; 1507 case MVT::f32: 1508 if (!Subtarget.hasVInstructionsF32()) 1509 return false; 1510 break; 1511 case MVT::f64: 1512 if (!Subtarget.hasVInstructionsF64()) 1513 return false; 1514 break; 1515 } 1516 1517 // Reject elements larger than ELEN. 1518 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1519 return false; 1520 1521 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1522 // Don't use RVV for types that don't fit. 1523 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1524 return false; 1525 1526 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1527 // the base fixed length RVV support in place. 1528 if (!VT.isPow2VectorType()) 1529 return false; 1530 1531 return true; 1532 } 1533 1534 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1535 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1536 } 1537 1538 // Return the largest legal scalable vector type that matches VT's element type. 1539 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1540 const RISCVSubtarget &Subtarget) { 1541 // This may be called before legal types are setup. 1542 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1543 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1544 "Expected legal fixed length vector!"); 1545 1546 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1547 unsigned MaxELen = Subtarget.getELEN(); 1548 1549 MVT EltVT = VT.getVectorElementType(); 1550 switch (EltVT.SimpleTy) { 1551 default: 1552 llvm_unreachable("unexpected element type for RVV container"); 1553 case MVT::i1: 1554 case MVT::i8: 1555 case MVT::i16: 1556 case MVT::i32: 1557 case MVT::i64: 1558 case MVT::f16: 1559 case MVT::f32: 1560 case MVT::f64: { 1561 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1562 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1563 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1564 unsigned NumElts = 1565 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1566 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1567 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1568 return MVT::getScalableVectorVT(EltVT, NumElts); 1569 } 1570 } 1571 } 1572 1573 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1574 const RISCVSubtarget &Subtarget) { 1575 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1576 Subtarget); 1577 } 1578 1579 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1580 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1581 } 1582 1583 // Grow V to consume an entire RVV register. 1584 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1585 const RISCVSubtarget &Subtarget) { 1586 assert(VT.isScalableVector() && 1587 "Expected to convert into a scalable vector!"); 1588 assert(V.getValueType().isFixedLengthVector() && 1589 "Expected a fixed length vector operand!"); 1590 SDLoc DL(V); 1591 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1592 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1593 } 1594 1595 // Shrink V so it's just big enough to maintain a VT's worth of data. 1596 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1597 const RISCVSubtarget &Subtarget) { 1598 assert(VT.isFixedLengthVector() && 1599 "Expected to convert into a fixed length vector!"); 1600 assert(V.getValueType().isScalableVector() && 1601 "Expected a scalable vector operand!"); 1602 SDLoc DL(V); 1603 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1604 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1605 } 1606 1607 /// Return the type of the mask type suitable for masking the provided 1608 /// vector type. This is simply an i1 element type vector of the same 1609 /// (possibly scalable) length. 1610 static MVT getMaskTypeFor(EVT VecVT) { 1611 assert(VecVT.isVector()); 1612 ElementCount EC = VecVT.getVectorElementCount(); 1613 return MVT::getVectorVT(MVT::i1, EC); 1614 } 1615 1616 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1617 /// vector length VL. . 1618 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1619 SelectionDAG &DAG) { 1620 MVT MaskVT = getMaskTypeFor(VecVT); 1621 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1622 } 1623 1624 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1625 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1626 // the vector type that it is contained in. 1627 static std::pair<SDValue, SDValue> 1628 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1629 const RISCVSubtarget &Subtarget) { 1630 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1631 MVT XLenVT = Subtarget.getXLenVT(); 1632 SDValue VL = VecVT.isFixedLengthVector() 1633 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1634 : DAG.getRegister(RISCV::X0, XLenVT); 1635 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1636 return {Mask, VL}; 1637 } 1638 1639 // As above but assuming the given type is a scalable vector type. 1640 static std::pair<SDValue, SDValue> 1641 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1642 const RISCVSubtarget &Subtarget) { 1643 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1644 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1645 } 1646 1647 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1648 // of either is (currently) supported. This can get us into an infinite loop 1649 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1650 // as a ..., etc. 1651 // Until either (or both) of these can reliably lower any node, reporting that 1652 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1653 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1654 // which is not desirable. 1655 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1656 EVT VT, unsigned DefinedValues) const { 1657 return false; 1658 } 1659 1660 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1661 const RISCVSubtarget &Subtarget) { 1662 // RISCV FP-to-int conversions saturate to the destination register size, but 1663 // don't produce 0 for nan. We can use a conversion instruction and fix the 1664 // nan case with a compare and a select. 1665 SDValue Src = Op.getOperand(0); 1666 1667 EVT DstVT = Op.getValueType(); 1668 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1669 1670 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1671 unsigned Opc; 1672 if (SatVT == DstVT) 1673 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1674 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1675 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1676 else 1677 return SDValue(); 1678 // FIXME: Support other SatVTs by clamping before or after the conversion. 1679 1680 SDLoc DL(Op); 1681 SDValue FpToInt = DAG.getNode( 1682 Opc, DL, DstVT, Src, 1683 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1684 1685 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1686 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1687 } 1688 1689 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1690 // and back. Taking care to avoid converting values that are nan or already 1691 // correct. 1692 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1693 // have FRM dependencies modeled yet. 1694 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1695 MVT VT = Op.getSimpleValueType(); 1696 assert(VT.isVector() && "Unexpected type"); 1697 1698 SDLoc DL(Op); 1699 1700 // Freeze the source since we are increasing the number of uses. 1701 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1702 1703 // Truncate to integer and convert back to FP. 1704 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1705 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1706 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1707 1708 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1709 1710 if (Op.getOpcode() == ISD::FCEIL) { 1711 // If the truncated value is the greater than or equal to the original 1712 // value, we've computed the ceil. Otherwise, we went the wrong way and 1713 // need to increase by 1. 1714 // FIXME: This should use a masked operation. Handle here or in isel? 1715 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1716 DAG.getConstantFP(1.0, DL, VT)); 1717 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1718 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1719 } else if (Op.getOpcode() == ISD::FFLOOR) { 1720 // If the truncated value is the less than or equal to the original value, 1721 // we've computed the floor. Otherwise, we went the wrong way and need to 1722 // decrease by 1. 1723 // FIXME: This should use a masked operation. Handle here or in isel? 1724 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1725 DAG.getConstantFP(1.0, DL, VT)); 1726 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1727 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1728 } 1729 1730 // Restore the original sign so that -0.0 is preserved. 1731 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1732 1733 // Determine the largest integer that can be represented exactly. This and 1734 // values larger than it don't have any fractional bits so don't need to 1735 // be converted. 1736 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 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 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1745 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1746 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1747 } 1748 1749 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1750 // This mode isn't supported in vector hardware on RISCV. But as long as we 1751 // aren't compiling with trapping math, we can emulate this with 1752 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1753 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1754 // dependencies modeled yet. 1755 // FIXME: Use masked operations to avoid final merge. 1756 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1757 MVT VT = Op.getSimpleValueType(); 1758 assert(VT.isVector() && "Unexpected type"); 1759 1760 SDLoc DL(Op); 1761 1762 // Freeze the source since we are increasing the number of uses. 1763 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1764 1765 // We do the conversion on the absolute value and fix the sign at the end. 1766 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1767 1768 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1769 bool Ignored; 1770 APFloat Point5Pred = APFloat(0.5f); 1771 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1772 Point5Pred.next(/*nextDown*/ true); 1773 1774 // Add the adjustment. 1775 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1776 DAG.getConstantFP(Point5Pred, DL, VT)); 1777 1778 // Truncate to integer and convert back to fp. 1779 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1780 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1781 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1782 1783 // Restore the original sign. 1784 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1785 1786 // Determine the largest integer that can be represented exactly. This and 1787 // values larger than it don't have any fractional bits so don't need to 1788 // be converted. 1789 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1790 APFloat MaxVal = APFloat(FltSem); 1791 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1792 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1793 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1794 1795 // If abs(Src) was larger than MaxVal or nan, keep it. 1796 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1797 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1798 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1799 } 1800 1801 struct VIDSequence { 1802 int64_t StepNumerator; 1803 unsigned StepDenominator; 1804 int64_t Addend; 1805 }; 1806 1807 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1808 // to the (non-zero) step S and start value X. This can be then lowered as the 1809 // RVV sequence (VID * S) + X, for example. 1810 // The step S is represented as an integer numerator divided by a positive 1811 // denominator. Note that the implementation currently only identifies 1812 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1813 // cannot detect 2/3, for example. 1814 // Note that this method will also match potentially unappealing index 1815 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1816 // determine whether this is worth generating code for. 1817 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1818 unsigned NumElts = Op.getNumOperands(); 1819 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1820 if (!Op.getValueType().isInteger()) 1821 return None; 1822 1823 Optional<unsigned> SeqStepDenom; 1824 Optional<int64_t> SeqStepNum, SeqAddend; 1825 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1826 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1827 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1828 // Assume undef elements match the sequence; we just have to be careful 1829 // when interpolating across them. 1830 if (Op.getOperand(Idx).isUndef()) 1831 continue; 1832 // The BUILD_VECTOR must be all constants. 1833 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1834 return None; 1835 1836 uint64_t Val = Op.getConstantOperandVal(Idx) & 1837 maskTrailingOnes<uint64_t>(EltSizeInBits); 1838 1839 if (PrevElt) { 1840 // Calculate the step since the last non-undef element, and ensure 1841 // it's consistent across the entire sequence. 1842 unsigned IdxDiff = Idx - PrevElt->second; 1843 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1844 1845 // A zero-value value difference means that we're somewhere in the middle 1846 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1847 // step change before evaluating the sequence. 1848 if (ValDiff == 0) 1849 continue; 1850 1851 int64_t Remainder = ValDiff % IdxDiff; 1852 // Normalize the step if it's greater than 1. 1853 if (Remainder != ValDiff) { 1854 // The difference must cleanly divide the element span. 1855 if (Remainder != 0) 1856 return None; 1857 ValDiff /= IdxDiff; 1858 IdxDiff = 1; 1859 } 1860 1861 if (!SeqStepNum) 1862 SeqStepNum = ValDiff; 1863 else if (ValDiff != SeqStepNum) 1864 return None; 1865 1866 if (!SeqStepDenom) 1867 SeqStepDenom = IdxDiff; 1868 else if (IdxDiff != *SeqStepDenom) 1869 return None; 1870 } 1871 1872 // Record this non-undef element for later. 1873 if (!PrevElt || PrevElt->first != Val) 1874 PrevElt = std::make_pair(Val, Idx); 1875 } 1876 1877 // We need to have logged a step for this to count as a legal index sequence. 1878 if (!SeqStepNum || !SeqStepDenom) 1879 return None; 1880 1881 // Loop back through the sequence and validate elements we might have skipped 1882 // while waiting for a valid step. While doing this, log any sequence addend. 1883 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1884 if (Op.getOperand(Idx).isUndef()) 1885 continue; 1886 uint64_t Val = Op.getConstantOperandVal(Idx) & 1887 maskTrailingOnes<uint64_t>(EltSizeInBits); 1888 uint64_t ExpectedVal = 1889 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1890 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1891 if (!SeqAddend) 1892 SeqAddend = Addend; 1893 else if (Addend != SeqAddend) 1894 return None; 1895 } 1896 1897 assert(SeqAddend && "Must have an addend if we have a step"); 1898 1899 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1900 } 1901 1902 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1903 // and lower it as a VRGATHER_VX_VL from the source vector. 1904 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1905 SelectionDAG &DAG, 1906 const RISCVSubtarget &Subtarget) { 1907 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1908 return SDValue(); 1909 SDValue Vec = SplatVal.getOperand(0); 1910 // Only perform this optimization on vectors of the same size for simplicity. 1911 if (Vec.getValueType() != VT) 1912 return SDValue(); 1913 SDValue Idx = SplatVal.getOperand(1); 1914 // The index must be a legal type. 1915 if (Idx.getValueType() != Subtarget.getXLenVT()) 1916 return SDValue(); 1917 1918 MVT ContainerVT = VT; 1919 if (VT.isFixedLengthVector()) { 1920 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1921 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1922 } 1923 1924 SDValue Mask, VL; 1925 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1926 1927 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1928 Idx, Mask, VL); 1929 1930 if (!VT.isFixedLengthVector()) 1931 return Gather; 1932 1933 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1934 } 1935 1936 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1937 const RISCVSubtarget &Subtarget) { 1938 MVT VT = Op.getSimpleValueType(); 1939 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1940 1941 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1942 1943 SDLoc DL(Op); 1944 SDValue Mask, VL; 1945 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1946 1947 MVT XLenVT = Subtarget.getXLenVT(); 1948 unsigned NumElts = Op.getNumOperands(); 1949 1950 if (VT.getVectorElementType() == MVT::i1) { 1951 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1952 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1953 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1954 } 1955 1956 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1957 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1958 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1959 } 1960 1961 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1962 // scalar integer chunks whose bit-width depends on the number of mask 1963 // bits and XLEN. 1964 // First, determine the most appropriate scalar integer type to use. This 1965 // is at most XLenVT, but may be shrunk to a smaller vector element type 1966 // according to the size of the final vector - use i8 chunks rather than 1967 // XLenVT if we're producing a v8i1. This results in more consistent 1968 // codegen across RV32 and RV64. 1969 unsigned NumViaIntegerBits = 1970 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1971 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1972 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1973 // If we have to use more than one INSERT_VECTOR_ELT then this 1974 // optimization is likely to increase code size; avoid peforming it in 1975 // such a case. We can use a load from a constant pool in this case. 1976 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1977 return SDValue(); 1978 // Now we can create our integer vector type. Note that it may be larger 1979 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1980 MVT IntegerViaVecVT = 1981 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1982 divideCeil(NumElts, NumViaIntegerBits)); 1983 1984 uint64_t Bits = 0; 1985 unsigned BitPos = 0, IntegerEltIdx = 0; 1986 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1987 1988 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1989 // Once we accumulate enough bits to fill our scalar type, insert into 1990 // our vector and clear our accumulated data. 1991 if (I != 0 && I % NumViaIntegerBits == 0) { 1992 if (NumViaIntegerBits <= 32) 1993 Bits = SignExtend64(Bits, 32); 1994 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1995 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1996 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1997 Bits = 0; 1998 BitPos = 0; 1999 IntegerEltIdx++; 2000 } 2001 SDValue V = Op.getOperand(I); 2002 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2003 Bits |= ((uint64_t)BitValue << BitPos); 2004 } 2005 2006 // Insert the (remaining) scalar value into position in our integer 2007 // vector type. 2008 if (NumViaIntegerBits <= 32) 2009 Bits = SignExtend64(Bits, 32); 2010 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2011 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2012 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2013 2014 if (NumElts < NumViaIntegerBits) { 2015 // If we're producing a smaller vector than our minimum legal integer 2016 // type, bitcast to the equivalent (known-legal) mask type, and extract 2017 // our final mask. 2018 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2019 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2020 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2021 DAG.getConstant(0, DL, XLenVT)); 2022 } else { 2023 // Else we must have produced an integer type with the same size as the 2024 // mask type; bitcast for the final result. 2025 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2026 Vec = DAG.getBitcast(VT, Vec); 2027 } 2028 2029 return Vec; 2030 } 2031 2032 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2033 // vector type, we have a legal equivalently-sized i8 type, so we can use 2034 // that. 2035 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2036 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2037 2038 SDValue WideVec; 2039 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2040 // For a splat, perform a scalar truncate before creating the wider 2041 // vector. 2042 assert(Splat.getValueType() == XLenVT && 2043 "Unexpected type for i1 splat value"); 2044 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2045 DAG.getConstant(1, DL, XLenVT)); 2046 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2047 } else { 2048 SmallVector<SDValue, 8> Ops(Op->op_values()); 2049 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2050 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2051 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2052 } 2053 2054 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2055 } 2056 2057 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2058 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2059 return Gather; 2060 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2061 : RISCVISD::VMV_V_X_VL; 2062 Splat = 2063 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2064 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2065 } 2066 2067 // Try and match index sequences, which we can lower to the vid instruction 2068 // with optional modifications. An all-undef vector is matched by 2069 // getSplatValue, above. 2070 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2071 int64_t StepNumerator = SimpleVID->StepNumerator; 2072 unsigned StepDenominator = SimpleVID->StepDenominator; 2073 int64_t Addend = SimpleVID->Addend; 2074 2075 assert(StepNumerator != 0 && "Invalid step"); 2076 bool Negate = false; 2077 int64_t SplatStepVal = StepNumerator; 2078 unsigned StepOpcode = ISD::MUL; 2079 if (StepNumerator != 1) { 2080 if (isPowerOf2_64(std::abs(StepNumerator))) { 2081 Negate = StepNumerator < 0; 2082 StepOpcode = ISD::SHL; 2083 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2084 } 2085 } 2086 2087 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2088 // threshold since it's the immediate value many RVV instructions accept. 2089 // There is no vmul.vi instruction so ensure multiply constant can fit in 2090 // a single addi instruction. 2091 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2092 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2093 isPowerOf2_32(StepDenominator) && 2094 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2095 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2096 // Convert right out of the scalable type so we can use standard ISD 2097 // nodes for the rest of the computation. If we used scalable types with 2098 // these, we'd lose the fixed-length vector info and generate worse 2099 // vsetvli code. 2100 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2101 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2102 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2103 SDValue SplatStep = DAG.getSplatBuildVector( 2104 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2105 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2106 } 2107 if (StepDenominator != 1) { 2108 SDValue SplatStep = DAG.getSplatBuildVector( 2109 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2110 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2111 } 2112 if (Addend != 0 || Negate) { 2113 SDValue SplatAddend = DAG.getSplatBuildVector( 2114 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2115 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2116 } 2117 return VID; 2118 } 2119 } 2120 2121 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2122 // when re-interpreted as a vector with a larger element type. For example, 2123 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2124 // could be instead splat as 2125 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2126 // TODO: This optimization could also work on non-constant splats, but it 2127 // would require bit-manipulation instructions to construct the splat value. 2128 SmallVector<SDValue> Sequence; 2129 unsigned EltBitSize = VT.getScalarSizeInBits(); 2130 const auto *BV = cast<BuildVectorSDNode>(Op); 2131 if (VT.isInteger() && EltBitSize < 64 && 2132 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2133 BV->getRepeatedSequence(Sequence) && 2134 (Sequence.size() * EltBitSize) <= 64) { 2135 unsigned SeqLen = Sequence.size(); 2136 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2137 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2138 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2139 ViaIntVT == MVT::i64) && 2140 "Unexpected sequence type"); 2141 2142 unsigned EltIdx = 0; 2143 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2144 uint64_t SplatValue = 0; 2145 // Construct the amalgamated value which can be splatted as this larger 2146 // vector type. 2147 for (const auto &SeqV : Sequence) { 2148 if (!SeqV.isUndef()) 2149 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2150 << (EltIdx * EltBitSize)); 2151 EltIdx++; 2152 } 2153 2154 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2155 // achieve better constant materializion. 2156 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2157 SplatValue = SignExtend64(SplatValue, 32); 2158 2159 // Since we can't introduce illegal i64 types at this stage, we can only 2160 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2161 // way we can use RVV instructions to splat. 2162 assert((ViaIntVT.bitsLE(XLenVT) || 2163 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2164 "Unexpected bitcast sequence"); 2165 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2166 SDValue ViaVL = 2167 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2168 MVT ViaContainerVT = 2169 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2170 SDValue Splat = 2171 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2172 DAG.getUNDEF(ViaContainerVT), 2173 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2174 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2175 return DAG.getBitcast(VT, Splat); 2176 } 2177 } 2178 2179 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2180 // which constitute a large proportion of the elements. In such cases we can 2181 // splat a vector with the dominant element and make up the shortfall with 2182 // INSERT_VECTOR_ELTs. 2183 // Note that this includes vectors of 2 elements by association. The 2184 // upper-most element is the "dominant" one, allowing us to use a splat to 2185 // "insert" the upper element, and an insert of the lower element at position 2186 // 0, which improves codegen. 2187 SDValue DominantValue; 2188 unsigned MostCommonCount = 0; 2189 DenseMap<SDValue, unsigned> ValueCounts; 2190 unsigned NumUndefElts = 2191 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2192 2193 // Track the number of scalar loads we know we'd be inserting, estimated as 2194 // any non-zero floating-point constant. Other kinds of element are either 2195 // already in registers or are materialized on demand. The threshold at which 2196 // a vector load is more desirable than several scalar materializion and 2197 // vector-insertion instructions is not known. 2198 unsigned NumScalarLoads = 0; 2199 2200 for (SDValue V : Op->op_values()) { 2201 if (V.isUndef()) 2202 continue; 2203 2204 ValueCounts.insert(std::make_pair(V, 0)); 2205 unsigned &Count = ValueCounts[V]; 2206 2207 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2208 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2209 2210 // Is this value dominant? In case of a tie, prefer the highest element as 2211 // it's cheaper to insert near the beginning of a vector than it is at the 2212 // end. 2213 if (++Count >= MostCommonCount) { 2214 DominantValue = V; 2215 MostCommonCount = Count; 2216 } 2217 } 2218 2219 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2220 unsigned NumDefElts = NumElts - NumUndefElts; 2221 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2222 2223 // Don't perform this optimization when optimizing for size, since 2224 // materializing elements and inserting them tends to cause code bloat. 2225 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2226 ((MostCommonCount > DominantValueCountThreshold) || 2227 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2228 // Start by splatting the most common element. 2229 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2230 2231 DenseSet<SDValue> Processed{DominantValue}; 2232 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2233 for (const auto &OpIdx : enumerate(Op->ops())) { 2234 const SDValue &V = OpIdx.value(); 2235 if (V.isUndef() || !Processed.insert(V).second) 2236 continue; 2237 if (ValueCounts[V] == 1) { 2238 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2239 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2240 } else { 2241 // Blend in all instances of this value using a VSELECT, using a 2242 // mask where each bit signals whether that element is the one 2243 // we're after. 2244 SmallVector<SDValue> Ops; 2245 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2246 return DAG.getConstant(V == V1, DL, XLenVT); 2247 }); 2248 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2249 DAG.getBuildVector(SelMaskTy, DL, Ops), 2250 DAG.getSplatBuildVector(VT, DL, V), Vec); 2251 } 2252 } 2253 2254 return Vec; 2255 } 2256 2257 return SDValue(); 2258 } 2259 2260 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2261 SDValue Lo, SDValue Hi, SDValue VL, 2262 SelectionDAG &DAG) { 2263 if (!Passthru) 2264 Passthru = DAG.getUNDEF(VT); 2265 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2266 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2267 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2268 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2269 // node in order to try and match RVV vector/scalar instructions. 2270 if ((LoC >> 31) == HiC) 2271 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2272 2273 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2274 // vmv.v.x whose EEW = 32 to lower it. 2275 auto *Const = dyn_cast<ConstantSDNode>(VL); 2276 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2277 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2278 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2279 // access the subtarget here now. 2280 auto InterVec = DAG.getNode( 2281 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2282 DAG.getRegister(RISCV::X0, MVT::i32)); 2283 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2284 } 2285 } 2286 2287 // Fall back to a stack store and stride x0 vector load. 2288 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2289 Hi, VL); 2290 } 2291 2292 // Called by type legalization to handle splat of i64 on RV32. 2293 // FIXME: We can optimize this when the type has sign or zero bits in one 2294 // of the halves. 2295 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2296 SDValue Scalar, SDValue VL, 2297 SelectionDAG &DAG) { 2298 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2299 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2300 DAG.getConstant(0, DL, MVT::i32)); 2301 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2302 DAG.getConstant(1, DL, MVT::i32)); 2303 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2304 } 2305 2306 // This function lowers a splat of a scalar operand Splat with the vector 2307 // length VL. It ensures the final sequence is type legal, which is useful when 2308 // lowering a splat after type legalization. 2309 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2310 MVT VT, SDLoc DL, SelectionDAG &DAG, 2311 const RISCVSubtarget &Subtarget) { 2312 bool HasPassthru = Passthru && !Passthru.isUndef(); 2313 if (!HasPassthru && !Passthru) 2314 Passthru = DAG.getUNDEF(VT); 2315 if (VT.isFloatingPoint()) { 2316 // If VL is 1, we could use vfmv.s.f. 2317 if (isOneConstant(VL)) 2318 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2319 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2320 } 2321 2322 MVT XLenVT = Subtarget.getXLenVT(); 2323 2324 // Simplest case is that the operand needs to be promoted to XLenVT. 2325 if (Scalar.getValueType().bitsLE(XLenVT)) { 2326 // If the operand is a constant, sign extend to increase our chances 2327 // of being able to use a .vi instruction. ANY_EXTEND would become a 2328 // a zero extend and the simm5 check in isel would fail. 2329 // FIXME: Should we ignore the upper bits in isel instead? 2330 unsigned ExtOpc = 2331 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2332 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2333 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2334 // If VL is 1 and the scalar value won't benefit from immediate, we could 2335 // use vmv.s.x. 2336 if (isOneConstant(VL) && 2337 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2338 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2339 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2340 } 2341 2342 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2343 "Unexpected scalar for splat lowering!"); 2344 2345 if (isOneConstant(VL) && isNullConstant(Scalar)) 2346 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2347 DAG.getConstant(0, DL, XLenVT), VL); 2348 2349 // Otherwise use the more complicated splatting algorithm. 2350 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2351 } 2352 2353 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2354 const RISCVSubtarget &Subtarget) { 2355 // We need to be able to widen elements to the next larger integer type. 2356 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2357 return false; 2358 2359 int Size = Mask.size(); 2360 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2361 2362 int Srcs[] = {-1, -1}; 2363 for (int i = 0; i != Size; ++i) { 2364 // Ignore undef elements. 2365 if (Mask[i] < 0) 2366 continue; 2367 2368 // Is this an even or odd element. 2369 int Pol = i % 2; 2370 2371 // Ensure we consistently use the same source for this element polarity. 2372 int Src = Mask[i] / Size; 2373 if (Srcs[Pol] < 0) 2374 Srcs[Pol] = Src; 2375 if (Srcs[Pol] != Src) 2376 return false; 2377 2378 // Make sure the element within the source is appropriate for this element 2379 // in the destination. 2380 int Elt = Mask[i] % Size; 2381 if (Elt != i / 2) 2382 return false; 2383 } 2384 2385 // We need to find a source for each polarity and they can't be the same. 2386 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2387 return false; 2388 2389 // Swap the sources if the second source was in the even polarity. 2390 SwapSources = Srcs[0] > Srcs[1]; 2391 2392 return true; 2393 } 2394 2395 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2396 /// and then extract the original number of elements from the rotated result. 2397 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2398 /// returned rotation amount is for a rotate right, where elements move from 2399 /// higher elements to lower elements. \p LoSrc indicates the first source 2400 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2401 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2402 /// 0 or 1 if a rotation is found. 2403 /// 2404 /// NOTE: We talk about rotate to the right which matches how bit shift and 2405 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2406 /// and the table below write vectors with the lowest elements on the left. 2407 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2408 int Size = Mask.size(); 2409 2410 // We need to detect various ways of spelling a rotation: 2411 // [11, 12, 13, 14, 15, 0, 1, 2] 2412 // [-1, 12, 13, 14, -1, -1, 1, -1] 2413 // [-1, -1, -1, -1, -1, -1, 1, 2] 2414 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2415 // [-1, 4, 5, 6, -1, -1, 9, -1] 2416 // [-1, 4, 5, 6, -1, -1, -1, -1] 2417 int Rotation = 0; 2418 LoSrc = -1; 2419 HiSrc = -1; 2420 for (int i = 0; i != Size; ++i) { 2421 int M = Mask[i]; 2422 if (M < 0) 2423 continue; 2424 2425 // Determine where a rotate vector would have started. 2426 int StartIdx = i - (M % Size); 2427 // The identity rotation isn't interesting, stop. 2428 if (StartIdx == 0) 2429 return -1; 2430 2431 // If we found the tail of a vector the rotation must be the missing 2432 // front. If we found the head of a vector, it must be how much of the 2433 // head. 2434 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2435 2436 if (Rotation == 0) 2437 Rotation = CandidateRotation; 2438 else if (Rotation != CandidateRotation) 2439 // The rotations don't match, so we can't match this mask. 2440 return -1; 2441 2442 // Compute which value this mask is pointing at. 2443 int MaskSrc = M < Size ? 0 : 1; 2444 2445 // Compute which of the two target values this index should be assigned to. 2446 // This reflects whether the high elements are remaining or the low elemnts 2447 // are remaining. 2448 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2449 2450 // Either set up this value if we've not encountered it before, or check 2451 // that it remains consistent. 2452 if (TargetSrc < 0) 2453 TargetSrc = MaskSrc; 2454 else if (TargetSrc != MaskSrc) 2455 // This may be a rotation, but it pulls from the inputs in some 2456 // unsupported interleaving. 2457 return -1; 2458 } 2459 2460 // Check that we successfully analyzed the mask, and normalize the results. 2461 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2462 assert((LoSrc >= 0 || HiSrc >= 0) && 2463 "Failed to find a rotated input vector!"); 2464 2465 return Rotation; 2466 } 2467 2468 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2469 const RISCVSubtarget &Subtarget) { 2470 SDValue V1 = Op.getOperand(0); 2471 SDValue V2 = Op.getOperand(1); 2472 SDLoc DL(Op); 2473 MVT XLenVT = Subtarget.getXLenVT(); 2474 MVT VT = Op.getSimpleValueType(); 2475 unsigned NumElts = VT.getVectorNumElements(); 2476 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2477 2478 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2479 2480 SDValue TrueMask, VL; 2481 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2482 2483 if (SVN->isSplat()) { 2484 const int Lane = SVN->getSplatIndex(); 2485 if (Lane >= 0) { 2486 MVT SVT = VT.getVectorElementType(); 2487 2488 // Turn splatted vector load into a strided load with an X0 stride. 2489 SDValue V = V1; 2490 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2491 // with undef. 2492 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2493 int Offset = Lane; 2494 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2495 int OpElements = 2496 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2497 V = V.getOperand(Offset / OpElements); 2498 Offset %= OpElements; 2499 } 2500 2501 // We need to ensure the load isn't atomic or volatile. 2502 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2503 auto *Ld = cast<LoadSDNode>(V); 2504 Offset *= SVT.getStoreSize(); 2505 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2506 TypeSize::Fixed(Offset), DL); 2507 2508 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2509 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2510 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2511 SDValue IntID = 2512 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2513 SDValue Ops[] = {Ld->getChain(), 2514 IntID, 2515 DAG.getUNDEF(ContainerVT), 2516 NewAddr, 2517 DAG.getRegister(RISCV::X0, XLenVT), 2518 VL}; 2519 SDValue NewLoad = DAG.getMemIntrinsicNode( 2520 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2521 DAG.getMachineFunction().getMachineMemOperand( 2522 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2523 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2524 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2525 } 2526 2527 // Otherwise use a scalar load and splat. This will give the best 2528 // opportunity to fold a splat into the operation. ISel can turn it into 2529 // the x0 strided load if we aren't able to fold away the select. 2530 if (SVT.isFloatingPoint()) 2531 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2532 Ld->getPointerInfo().getWithOffset(Offset), 2533 Ld->getOriginalAlign(), 2534 Ld->getMemOperand()->getFlags()); 2535 else 2536 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2537 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2538 Ld->getOriginalAlign(), 2539 Ld->getMemOperand()->getFlags()); 2540 DAG.makeEquivalentMemoryOrdering(Ld, V); 2541 2542 unsigned Opc = 2543 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2544 SDValue Splat = 2545 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2546 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2547 } 2548 2549 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2550 assert(Lane < (int)NumElts && "Unexpected lane!"); 2551 SDValue Gather = 2552 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2553 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2554 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2555 } 2556 } 2557 2558 ArrayRef<int> Mask = SVN->getMask(); 2559 2560 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2561 // be undef which can be handled with a single SLIDEDOWN/UP. 2562 int LoSrc, HiSrc; 2563 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2564 if (Rotation > 0) { 2565 SDValue LoV, HiV; 2566 if (LoSrc >= 0) { 2567 LoV = LoSrc == 0 ? V1 : V2; 2568 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2569 } 2570 if (HiSrc >= 0) { 2571 HiV = HiSrc == 0 ? V1 : V2; 2572 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2573 } 2574 2575 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2576 // to slide LoV up by (NumElts - Rotation). 2577 unsigned InvRotate = NumElts - Rotation; 2578 2579 SDValue Res = DAG.getUNDEF(ContainerVT); 2580 if (HiV) { 2581 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2582 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2583 // causes multiple vsetvlis in some test cases such as lowering 2584 // reduce.mul 2585 SDValue DownVL = VL; 2586 if (LoV) 2587 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2588 Res = 2589 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2590 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2591 } 2592 if (LoV) 2593 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2594 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2595 2596 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2597 } 2598 2599 // Detect an interleave shuffle and lower to 2600 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2601 bool SwapSources; 2602 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2603 // Swap sources if needed. 2604 if (SwapSources) 2605 std::swap(V1, V2); 2606 2607 // Extract the lower half of the vectors. 2608 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2609 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2610 DAG.getConstant(0, DL, XLenVT)); 2611 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2612 DAG.getConstant(0, DL, XLenVT)); 2613 2614 // Double the element width and halve the number of elements in an int type. 2615 unsigned EltBits = VT.getScalarSizeInBits(); 2616 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2617 MVT WideIntVT = 2618 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2619 // Convert this to a scalable vector. We need to base this on the 2620 // destination size to ensure there's always a type with a smaller LMUL. 2621 MVT WideIntContainerVT = 2622 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2623 2624 // Convert sources to scalable vectors with the same element count as the 2625 // larger type. 2626 MVT HalfContainerVT = MVT::getVectorVT( 2627 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2628 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2629 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2630 2631 // Cast sources to integer. 2632 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2633 MVT IntHalfVT = 2634 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2635 V1 = DAG.getBitcast(IntHalfVT, V1); 2636 V2 = DAG.getBitcast(IntHalfVT, V2); 2637 2638 // Freeze V2 since we use it twice and we need to be sure that the add and 2639 // multiply see the same value. 2640 V2 = DAG.getFreeze(V2); 2641 2642 // Recreate TrueMask using the widened type's element count. 2643 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2644 2645 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2646 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2647 V2, TrueMask, VL); 2648 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2649 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2650 DAG.getUNDEF(IntHalfVT), 2651 DAG.getAllOnesConstant(DL, XLenVT)); 2652 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2653 V2, Multiplier, TrueMask, VL); 2654 // Add the new copies to our previous addition giving us 2^eltbits copies of 2655 // V2. This is equivalent to shifting V2 left by eltbits. This should 2656 // combine with the vwmulu.vv above to form vwmaccu.vv. 2657 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2658 TrueMask, VL); 2659 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2660 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2661 // vector VT. 2662 ContainerVT = 2663 MVT::getVectorVT(VT.getVectorElementType(), 2664 WideIntContainerVT.getVectorElementCount() * 2); 2665 Add = DAG.getBitcast(ContainerVT, Add); 2666 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2667 } 2668 2669 // Detect shuffles which can be re-expressed as vector selects; these are 2670 // shuffles in which each element in the destination is taken from an element 2671 // at the corresponding index in either source vectors. 2672 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2673 int MaskIndex = MaskIdx.value(); 2674 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2675 }); 2676 2677 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2678 2679 SmallVector<SDValue> MaskVals; 2680 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2681 // merged with a second vrgather. 2682 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2683 2684 // By default we preserve the original operand order, and use a mask to 2685 // select LHS as true and RHS as false. However, since RVV vector selects may 2686 // feature splats but only on the LHS, we may choose to invert our mask and 2687 // instead select between RHS and LHS. 2688 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2689 bool InvertMask = IsSelect == SwapOps; 2690 2691 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2692 // half. 2693 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2694 2695 // Now construct the mask that will be used by the vselect or blended 2696 // vrgather operation. For vrgathers, construct the appropriate indices into 2697 // each vector. 2698 for (int MaskIndex : Mask) { 2699 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2700 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2701 if (!IsSelect) { 2702 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2703 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2704 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2705 : DAG.getUNDEF(XLenVT)); 2706 GatherIndicesRHS.push_back( 2707 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2708 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2709 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2710 ++LHSIndexCounts[MaskIndex]; 2711 if (!IsLHSOrUndefIndex) 2712 ++RHSIndexCounts[MaskIndex - NumElts]; 2713 } 2714 } 2715 2716 if (SwapOps) { 2717 std::swap(V1, V2); 2718 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2719 } 2720 2721 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2722 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2723 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2724 2725 if (IsSelect) 2726 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2727 2728 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2729 // On such a large vector we're unable to use i8 as the index type. 2730 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2731 // may involve vector splitting if we're already at LMUL=8, or our 2732 // user-supplied maximum fixed-length LMUL. 2733 return SDValue(); 2734 } 2735 2736 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2737 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2738 MVT IndexVT = VT.changeTypeToInteger(); 2739 // Since we can't introduce illegal index types at this stage, use i16 and 2740 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2741 // than XLenVT. 2742 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2743 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2744 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2745 } 2746 2747 MVT IndexContainerVT = 2748 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2749 2750 SDValue Gather; 2751 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2752 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2753 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2754 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2755 Subtarget); 2756 } else { 2757 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2758 // If only one index is used, we can use a "splat" vrgather. 2759 // TODO: We can splat the most-common index and fix-up any stragglers, if 2760 // that's beneficial. 2761 if (LHSIndexCounts.size() == 1) { 2762 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2763 Gather = 2764 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2765 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2766 } else { 2767 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2768 LHSIndices = 2769 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2770 2771 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2772 TrueMask, VL); 2773 } 2774 } 2775 2776 // If a second vector operand is used by this shuffle, blend it in with an 2777 // additional vrgather. 2778 if (!V2.isUndef()) { 2779 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2780 // If only one index is used, we can use a "splat" vrgather. 2781 // TODO: We can splat the most-common index and fix-up any stragglers, if 2782 // that's beneficial. 2783 if (RHSIndexCounts.size() == 1) { 2784 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2785 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2786 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2787 } else { 2788 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2789 RHSIndices = 2790 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2791 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2792 VL); 2793 } 2794 2795 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2796 SelectMask = 2797 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2798 2799 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2800 Gather, VL); 2801 } 2802 2803 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2804 } 2805 2806 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2807 // Support splats for any type. These should type legalize well. 2808 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2809 return true; 2810 2811 // Only support legal VTs for other shuffles for now. 2812 if (!isTypeLegal(VT)) 2813 return false; 2814 2815 MVT SVT = VT.getSimpleVT(); 2816 2817 bool SwapSources; 2818 int LoSrc, HiSrc; 2819 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2820 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2821 } 2822 2823 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2824 // the exponent. 2825 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2826 MVT VT = Op.getSimpleValueType(); 2827 unsigned EltSize = VT.getScalarSizeInBits(); 2828 SDValue Src = Op.getOperand(0); 2829 SDLoc DL(Op); 2830 2831 // We need a FP type that can represent the value. 2832 // TODO: Use f16 for i8 when possible? 2833 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2834 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2835 2836 // Legal types should have been checked in the RISCVTargetLowering 2837 // constructor. 2838 // TODO: Splitting may make sense in some cases. 2839 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2840 "Expected legal float type!"); 2841 2842 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2843 // The trailing zero count is equal to log2 of this single bit value. 2844 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2845 SDValue Neg = 2846 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2847 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2848 } 2849 2850 // We have a legal FP type, convert to it. 2851 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2852 // Bitcast to integer and shift the exponent to the LSB. 2853 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2854 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2855 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2856 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2857 DAG.getConstant(ShiftAmt, DL, IntVT)); 2858 // Truncate back to original type to allow vnsrl. 2859 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2860 // The exponent contains log2 of the value in biased form. 2861 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2862 2863 // For trailing zeros, we just need to subtract the bias. 2864 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2865 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2866 DAG.getConstant(ExponentBias, DL, VT)); 2867 2868 // For leading zeros, we need to remove the bias and convert from log2 to 2869 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2870 unsigned Adjust = ExponentBias + (EltSize - 1); 2871 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2872 } 2873 2874 // While RVV has alignment restrictions, we should always be able to load as a 2875 // legal equivalently-sized byte-typed vector instead. This method is 2876 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2877 // the load is already correctly-aligned, it returns SDValue(). 2878 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2879 SelectionDAG &DAG) const { 2880 auto *Load = cast<LoadSDNode>(Op); 2881 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2882 2883 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2884 Load->getMemoryVT(), 2885 *Load->getMemOperand())) 2886 return SDValue(); 2887 2888 SDLoc DL(Op); 2889 MVT VT = Op.getSimpleValueType(); 2890 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2891 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2892 "Unexpected unaligned RVV load type"); 2893 MVT NewVT = 2894 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2895 assert(NewVT.isValid() && 2896 "Expecting equally-sized RVV vector types to be legal"); 2897 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2898 Load->getPointerInfo(), Load->getOriginalAlign(), 2899 Load->getMemOperand()->getFlags()); 2900 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2901 } 2902 2903 // While RVV has alignment restrictions, we should always be able to store as a 2904 // legal equivalently-sized byte-typed vector instead. This method is 2905 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2906 // returns SDValue() if the store is already correctly aligned. 2907 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2908 SelectionDAG &DAG) const { 2909 auto *Store = cast<StoreSDNode>(Op); 2910 assert(Store && Store->getValue().getValueType().isVector() && 2911 "Expected vector store"); 2912 2913 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2914 Store->getMemoryVT(), 2915 *Store->getMemOperand())) 2916 return SDValue(); 2917 2918 SDLoc DL(Op); 2919 SDValue StoredVal = Store->getValue(); 2920 MVT VT = StoredVal.getSimpleValueType(); 2921 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2922 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2923 "Unexpected unaligned RVV store type"); 2924 MVT NewVT = 2925 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2926 assert(NewVT.isValid() && 2927 "Expecting equally-sized RVV vector types to be legal"); 2928 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2929 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2930 Store->getPointerInfo(), Store->getOriginalAlign(), 2931 Store->getMemOperand()->getFlags()); 2932 } 2933 2934 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2935 SelectionDAG &DAG) const { 2936 switch (Op.getOpcode()) { 2937 default: 2938 report_fatal_error("unimplemented operand"); 2939 case ISD::GlobalAddress: 2940 return lowerGlobalAddress(Op, DAG); 2941 case ISD::BlockAddress: 2942 return lowerBlockAddress(Op, DAG); 2943 case ISD::ConstantPool: 2944 return lowerConstantPool(Op, DAG); 2945 case ISD::JumpTable: 2946 return lowerJumpTable(Op, DAG); 2947 case ISD::GlobalTLSAddress: 2948 return lowerGlobalTLSAddress(Op, DAG); 2949 case ISD::SELECT: 2950 return lowerSELECT(Op, DAG); 2951 case ISD::BRCOND: 2952 return lowerBRCOND(Op, DAG); 2953 case ISD::VASTART: 2954 return lowerVASTART(Op, DAG); 2955 case ISD::FRAMEADDR: 2956 return lowerFRAMEADDR(Op, DAG); 2957 case ISD::RETURNADDR: 2958 return lowerRETURNADDR(Op, DAG); 2959 case ISD::SHL_PARTS: 2960 return lowerShiftLeftParts(Op, DAG); 2961 case ISD::SRA_PARTS: 2962 return lowerShiftRightParts(Op, DAG, true); 2963 case ISD::SRL_PARTS: 2964 return lowerShiftRightParts(Op, DAG, false); 2965 case ISD::BITCAST: { 2966 SDLoc DL(Op); 2967 EVT VT = Op.getValueType(); 2968 SDValue Op0 = Op.getOperand(0); 2969 EVT Op0VT = Op0.getValueType(); 2970 MVT XLenVT = Subtarget.getXLenVT(); 2971 if (VT.isFixedLengthVector()) { 2972 // We can handle fixed length vector bitcasts with a simple replacement 2973 // in isel. 2974 if (Op0VT.isFixedLengthVector()) 2975 return Op; 2976 // When bitcasting from scalar to fixed-length vector, insert the scalar 2977 // into a one-element vector of the result type, and perform a vector 2978 // bitcast. 2979 if (!Op0VT.isVector()) { 2980 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2981 if (!isTypeLegal(BVT)) 2982 return SDValue(); 2983 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2984 DAG.getUNDEF(BVT), Op0, 2985 DAG.getConstant(0, DL, XLenVT))); 2986 } 2987 return SDValue(); 2988 } 2989 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2990 // thus: bitcast the vector to a one-element vector type whose element type 2991 // is the same as the result type, and extract the first element. 2992 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2993 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2994 if (!isTypeLegal(BVT)) 2995 return SDValue(); 2996 SDValue BVec = DAG.getBitcast(BVT, Op0); 2997 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2998 DAG.getConstant(0, DL, XLenVT)); 2999 } 3000 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3001 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3002 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3003 return FPConv; 3004 } 3005 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3006 Subtarget.hasStdExtF()) { 3007 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3008 SDValue FPConv = 3009 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3010 return FPConv; 3011 } 3012 return SDValue(); 3013 } 3014 case ISD::INTRINSIC_WO_CHAIN: 3015 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3016 case ISD::INTRINSIC_W_CHAIN: 3017 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3018 case ISD::INTRINSIC_VOID: 3019 return LowerINTRINSIC_VOID(Op, DAG); 3020 case ISD::BSWAP: 3021 case ISD::BITREVERSE: { 3022 MVT VT = Op.getSimpleValueType(); 3023 SDLoc DL(Op); 3024 if (Subtarget.hasStdExtZbp()) { 3025 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3026 // Start with the maximum immediate value which is the bitwidth - 1. 3027 unsigned Imm = VT.getSizeInBits() - 1; 3028 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3029 if (Op.getOpcode() == ISD::BSWAP) 3030 Imm &= ~0x7U; 3031 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3032 DAG.getConstant(Imm, DL, VT)); 3033 } 3034 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3035 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3036 // Expand bitreverse to a bswap(rev8) followed by brev8. 3037 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3038 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3039 // as brev8 by an isel pattern. 3040 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3041 DAG.getConstant(7, DL, VT)); 3042 } 3043 case ISD::FSHL: 3044 case ISD::FSHR: { 3045 MVT VT = Op.getSimpleValueType(); 3046 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3047 SDLoc DL(Op); 3048 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3049 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3050 // accidentally setting the extra bit. 3051 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3052 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3053 DAG.getConstant(ShAmtWidth, DL, VT)); 3054 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3055 // instruction use different orders. fshl will return its first operand for 3056 // shift of zero, fshr will return its second operand. fsl and fsr both 3057 // return rs1 so the ISD nodes need to have different operand orders. 3058 // Shift amount is in rs2. 3059 SDValue Op0 = Op.getOperand(0); 3060 SDValue Op1 = Op.getOperand(1); 3061 unsigned Opc = RISCVISD::FSL; 3062 if (Op.getOpcode() == ISD::FSHR) { 3063 std::swap(Op0, Op1); 3064 Opc = RISCVISD::FSR; 3065 } 3066 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3067 } 3068 case ISD::TRUNCATE: 3069 // Only custom-lower vector truncates 3070 if (!Op.getSimpleValueType().isVector()) 3071 return Op; 3072 return lowerVectorTruncLike(Op, DAG); 3073 case ISD::ANY_EXTEND: 3074 case ISD::ZERO_EXTEND: 3075 if (Op.getOperand(0).getValueType().isVector() && 3076 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3077 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3078 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3079 case ISD::SIGN_EXTEND: 3080 if (Op.getOperand(0).getValueType().isVector() && 3081 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3082 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3083 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3084 case ISD::SPLAT_VECTOR_PARTS: 3085 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3086 case ISD::INSERT_VECTOR_ELT: 3087 return lowerINSERT_VECTOR_ELT(Op, DAG); 3088 case ISD::EXTRACT_VECTOR_ELT: 3089 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3090 case ISD::VSCALE: { 3091 MVT VT = Op.getSimpleValueType(); 3092 SDLoc DL(Op); 3093 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3094 // We define our scalable vector types for lmul=1 to use a 64 bit known 3095 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3096 // vscale as VLENB / 8. 3097 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3098 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3099 report_fatal_error("Support for VLEN==32 is incomplete."); 3100 // We assume VLENB is a multiple of 8. We manually choose the best shift 3101 // here because SimplifyDemandedBits isn't always able to simplify it. 3102 uint64_t Val = Op.getConstantOperandVal(0); 3103 if (isPowerOf2_64(Val)) { 3104 uint64_t Log2 = Log2_64(Val); 3105 if (Log2 < 3) 3106 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3107 DAG.getConstant(3 - Log2, DL, VT)); 3108 if (Log2 > 3) 3109 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3110 DAG.getConstant(Log2 - 3, DL, VT)); 3111 return VLENB; 3112 } 3113 // If the multiplier is a multiple of 8, scale it down to avoid needing 3114 // to shift the VLENB value. 3115 if ((Val % 8) == 0) 3116 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3117 DAG.getConstant(Val / 8, DL, VT)); 3118 3119 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3120 DAG.getConstant(3, DL, VT)); 3121 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3122 } 3123 case ISD::FPOWI: { 3124 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3125 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3126 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3127 Op.getOperand(1).getValueType() == MVT::i32) { 3128 SDLoc DL(Op); 3129 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3130 SDValue Powi = 3131 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3132 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3133 DAG.getIntPtrConstant(0, DL)); 3134 } 3135 return SDValue(); 3136 } 3137 case ISD::FP_EXTEND: 3138 case ISD::FP_ROUND: 3139 if (!Op.getValueType().isVector()) 3140 return Op; 3141 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3142 case ISD::FP_TO_SINT: 3143 case ISD::FP_TO_UINT: 3144 case ISD::SINT_TO_FP: 3145 case ISD::UINT_TO_FP: { 3146 // RVV can only do fp<->int conversions to types half/double the size as 3147 // the source. We custom-lower any conversions that do two hops into 3148 // sequences. 3149 MVT VT = Op.getSimpleValueType(); 3150 if (!VT.isVector()) 3151 return Op; 3152 SDLoc DL(Op); 3153 SDValue Src = Op.getOperand(0); 3154 MVT EltVT = VT.getVectorElementType(); 3155 MVT SrcVT = Src.getSimpleValueType(); 3156 MVT SrcEltVT = SrcVT.getVectorElementType(); 3157 unsigned EltSize = EltVT.getSizeInBits(); 3158 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3159 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3160 "Unexpected vector element types"); 3161 3162 bool IsInt2FP = SrcEltVT.isInteger(); 3163 // Widening conversions 3164 if (EltSize > (2 * SrcEltSize)) { 3165 if (IsInt2FP) { 3166 // Do a regular integer sign/zero extension then convert to float. 3167 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3168 VT.getVectorElementCount()); 3169 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3170 ? ISD::ZERO_EXTEND 3171 : ISD::SIGN_EXTEND; 3172 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3173 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3174 } 3175 // FP2Int 3176 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3177 // Do one doubling fp_extend then complete the operation by converting 3178 // to int. 3179 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3180 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3181 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3182 } 3183 3184 // Narrowing conversions 3185 if (SrcEltSize > (2 * EltSize)) { 3186 if (IsInt2FP) { 3187 // One narrowing int_to_fp, then an fp_round. 3188 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3189 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3190 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3191 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3192 } 3193 // FP2Int 3194 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3195 // representable by the integer, the result is poison. 3196 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3197 VT.getVectorElementCount()); 3198 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3199 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3200 } 3201 3202 // Scalable vectors can exit here. Patterns will handle equally-sized 3203 // conversions halving/doubling ones. 3204 if (!VT.isFixedLengthVector()) 3205 return Op; 3206 3207 // For fixed-length vectors we lower to a custom "VL" node. 3208 unsigned RVVOpc = 0; 3209 switch (Op.getOpcode()) { 3210 default: 3211 llvm_unreachable("Impossible opcode"); 3212 case ISD::FP_TO_SINT: 3213 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3214 break; 3215 case ISD::FP_TO_UINT: 3216 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3217 break; 3218 case ISD::SINT_TO_FP: 3219 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3220 break; 3221 case ISD::UINT_TO_FP: 3222 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3223 break; 3224 } 3225 3226 MVT ContainerVT, SrcContainerVT; 3227 // Derive the reference container type from the larger vector type. 3228 if (SrcEltSize > EltSize) { 3229 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3230 ContainerVT = 3231 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3232 } else { 3233 ContainerVT = getContainerForFixedLengthVector(VT); 3234 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3235 } 3236 3237 SDValue Mask, VL; 3238 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3239 3240 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3241 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3242 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3243 } 3244 case ISD::FP_TO_SINT_SAT: 3245 case ISD::FP_TO_UINT_SAT: 3246 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3247 case ISD::FTRUNC: 3248 case ISD::FCEIL: 3249 case ISD::FFLOOR: 3250 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3251 case ISD::FROUND: 3252 return lowerFROUND(Op, DAG); 3253 case ISD::VECREDUCE_ADD: 3254 case ISD::VECREDUCE_UMAX: 3255 case ISD::VECREDUCE_SMAX: 3256 case ISD::VECREDUCE_UMIN: 3257 case ISD::VECREDUCE_SMIN: 3258 return lowerVECREDUCE(Op, DAG); 3259 case ISD::VECREDUCE_AND: 3260 case ISD::VECREDUCE_OR: 3261 case ISD::VECREDUCE_XOR: 3262 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3263 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3264 return lowerVECREDUCE(Op, DAG); 3265 case ISD::VECREDUCE_FADD: 3266 case ISD::VECREDUCE_SEQ_FADD: 3267 case ISD::VECREDUCE_FMIN: 3268 case ISD::VECREDUCE_FMAX: 3269 return lowerFPVECREDUCE(Op, DAG); 3270 case ISD::VP_REDUCE_ADD: 3271 case ISD::VP_REDUCE_UMAX: 3272 case ISD::VP_REDUCE_SMAX: 3273 case ISD::VP_REDUCE_UMIN: 3274 case ISD::VP_REDUCE_SMIN: 3275 case ISD::VP_REDUCE_FADD: 3276 case ISD::VP_REDUCE_SEQ_FADD: 3277 case ISD::VP_REDUCE_FMIN: 3278 case ISD::VP_REDUCE_FMAX: 3279 return lowerVPREDUCE(Op, DAG); 3280 case ISD::VP_REDUCE_AND: 3281 case ISD::VP_REDUCE_OR: 3282 case ISD::VP_REDUCE_XOR: 3283 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3284 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3285 return lowerVPREDUCE(Op, DAG); 3286 case ISD::INSERT_SUBVECTOR: 3287 return lowerINSERT_SUBVECTOR(Op, DAG); 3288 case ISD::EXTRACT_SUBVECTOR: 3289 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3290 case ISD::STEP_VECTOR: 3291 return lowerSTEP_VECTOR(Op, DAG); 3292 case ISD::VECTOR_REVERSE: 3293 return lowerVECTOR_REVERSE(Op, DAG); 3294 case ISD::VECTOR_SPLICE: 3295 return lowerVECTOR_SPLICE(Op, DAG); 3296 case ISD::BUILD_VECTOR: 3297 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3298 case ISD::SPLAT_VECTOR: 3299 if (Op.getValueType().getVectorElementType() == MVT::i1) 3300 return lowerVectorMaskSplat(Op, DAG); 3301 return SDValue(); 3302 case ISD::VECTOR_SHUFFLE: 3303 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3304 case ISD::CONCAT_VECTORS: { 3305 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3306 // better than going through the stack, as the default expansion does. 3307 SDLoc DL(Op); 3308 MVT VT = Op.getSimpleValueType(); 3309 unsigned NumOpElts = 3310 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3311 SDValue Vec = DAG.getUNDEF(VT); 3312 for (const auto &OpIdx : enumerate(Op->ops())) { 3313 SDValue SubVec = OpIdx.value(); 3314 // Don't insert undef subvectors. 3315 if (SubVec.isUndef()) 3316 continue; 3317 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3318 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3319 } 3320 return Vec; 3321 } 3322 case ISD::LOAD: 3323 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3324 return V; 3325 if (Op.getValueType().isFixedLengthVector()) 3326 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3327 return Op; 3328 case ISD::STORE: 3329 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3330 return V; 3331 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3332 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3333 return Op; 3334 case ISD::MLOAD: 3335 case ISD::VP_LOAD: 3336 return lowerMaskedLoad(Op, DAG); 3337 case ISD::MSTORE: 3338 case ISD::VP_STORE: 3339 return lowerMaskedStore(Op, DAG); 3340 case ISD::SETCC: 3341 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3342 case ISD::ADD: 3343 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3344 case ISD::SUB: 3345 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3346 case ISD::MUL: 3347 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3348 case ISD::MULHS: 3349 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3350 case ISD::MULHU: 3351 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3352 case ISD::AND: 3353 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3354 RISCVISD::AND_VL); 3355 case ISD::OR: 3356 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3357 RISCVISD::OR_VL); 3358 case ISD::XOR: 3359 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3360 RISCVISD::XOR_VL); 3361 case ISD::SDIV: 3362 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3363 case ISD::SREM: 3364 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3365 case ISD::UDIV: 3366 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3367 case ISD::UREM: 3368 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3369 case ISD::SHL: 3370 case ISD::SRA: 3371 case ISD::SRL: 3372 if (Op.getSimpleValueType().isFixedLengthVector()) 3373 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3374 // This can be called for an i32 shift amount that needs to be promoted. 3375 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3376 "Unexpected custom legalisation"); 3377 return SDValue(); 3378 case ISD::SADDSAT: 3379 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3380 case ISD::UADDSAT: 3381 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3382 case ISD::SSUBSAT: 3383 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3384 case ISD::USUBSAT: 3385 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3386 case ISD::FADD: 3387 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3388 case ISD::FSUB: 3389 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3390 case ISD::FMUL: 3391 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3392 case ISD::FDIV: 3393 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3394 case ISD::FNEG: 3395 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3396 case ISD::FABS: 3397 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3398 case ISD::FSQRT: 3399 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3400 case ISD::FMA: 3401 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3402 case ISD::SMIN: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3404 case ISD::SMAX: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3406 case ISD::UMIN: 3407 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3408 case ISD::UMAX: 3409 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3410 case ISD::FMINNUM: 3411 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3412 case ISD::FMAXNUM: 3413 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3414 case ISD::ABS: 3415 return lowerABS(Op, DAG); 3416 case ISD::CTLZ_ZERO_UNDEF: 3417 case ISD::CTTZ_ZERO_UNDEF: 3418 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3419 case ISD::VSELECT: 3420 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3421 case ISD::FCOPYSIGN: 3422 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3423 case ISD::MGATHER: 3424 case ISD::VP_GATHER: 3425 return lowerMaskedGather(Op, DAG); 3426 case ISD::MSCATTER: 3427 case ISD::VP_SCATTER: 3428 return lowerMaskedScatter(Op, DAG); 3429 case ISD::FLT_ROUNDS_: 3430 return lowerGET_ROUNDING(Op, DAG); 3431 case ISD::SET_ROUNDING: 3432 return lowerSET_ROUNDING(Op, DAG); 3433 case ISD::VP_SELECT: 3434 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3435 case ISD::VP_MERGE: 3436 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3437 case ISD::VP_ADD: 3438 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3439 case ISD::VP_SUB: 3440 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3441 case ISD::VP_MUL: 3442 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3443 case ISD::VP_SDIV: 3444 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3445 case ISD::VP_UDIV: 3446 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3447 case ISD::VP_SREM: 3448 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3449 case ISD::VP_UREM: 3450 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3451 case ISD::VP_AND: 3452 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3453 case ISD::VP_OR: 3454 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3455 case ISD::VP_XOR: 3456 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3457 case ISD::VP_ASHR: 3458 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3459 case ISD::VP_LSHR: 3460 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3461 case ISD::VP_SHL: 3462 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3463 case ISD::VP_FADD: 3464 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3465 case ISD::VP_FSUB: 3466 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3467 case ISD::VP_FMUL: 3468 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3469 case ISD::VP_FDIV: 3470 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3471 case ISD::VP_FNEG: 3472 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3473 case ISD::VP_FMA: 3474 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3475 case ISD::VP_SIGN_EXTEND: 3476 case ISD::VP_ZERO_EXTEND: 3477 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3478 return lowerVPExtMaskOp(Op, DAG); 3479 return lowerVPOp(Op, DAG, 3480 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3481 ? RISCVISD::VSEXT_VL 3482 : RISCVISD::VZEXT_VL); 3483 case ISD::VP_TRUNCATE: 3484 return lowerVectorTruncLike(Op, DAG); 3485 case ISD::VP_FP_EXTEND: 3486 case ISD::VP_FP_ROUND: 3487 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3488 case ISD::VP_FPTOSI: 3489 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3490 case ISD::VP_FPTOUI: 3491 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3492 case ISD::VP_SITOFP: 3493 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3494 case ISD::VP_UITOFP: 3495 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3496 case ISD::VP_SETCC: 3497 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3498 return lowerVPSetCCMaskOp(Op, DAG); 3499 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3500 } 3501 } 3502 3503 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3504 SelectionDAG &DAG, unsigned Flags) { 3505 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3506 } 3507 3508 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3509 SelectionDAG &DAG, unsigned Flags) { 3510 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3511 Flags); 3512 } 3513 3514 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3515 SelectionDAG &DAG, unsigned Flags) { 3516 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3517 N->getOffset(), Flags); 3518 } 3519 3520 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3521 SelectionDAG &DAG, unsigned Flags) { 3522 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3523 } 3524 3525 template <class NodeTy> 3526 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3527 bool IsLocal) const { 3528 SDLoc DL(N); 3529 EVT Ty = getPointerTy(DAG.getDataLayout()); 3530 3531 if (isPositionIndependent()) { 3532 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3533 if (IsLocal) 3534 // Use PC-relative addressing to access the symbol. This generates the 3535 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3536 // %pcrel_lo(auipc)). 3537 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3538 3539 // Use PC-relative addressing to access the GOT for this symbol, then load 3540 // the address from the GOT. This generates the pattern (PseudoLA sym), 3541 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3542 SDValue Load = 3543 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3544 MachineFunction &MF = DAG.getMachineFunction(); 3545 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3546 MachinePointerInfo::getGOT(MF), 3547 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3548 MachineMemOperand::MOInvariant, 3549 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3550 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3551 return Load; 3552 } 3553 3554 switch (getTargetMachine().getCodeModel()) { 3555 default: 3556 report_fatal_error("Unsupported code model for lowering"); 3557 case CodeModel::Small: { 3558 // Generate a sequence for accessing addresses within the first 2 GiB of 3559 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3560 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3561 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3562 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3563 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3564 } 3565 case CodeModel::Medium: { 3566 // Generate a sequence for accessing addresses within any 2GiB range within 3567 // the address space. This generates the pattern (PseudoLLA sym), which 3568 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3569 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3570 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3571 } 3572 } 3573 } 3574 3575 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3576 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3577 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3578 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3579 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3580 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3581 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3582 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3583 3584 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3585 SelectionDAG &DAG) const { 3586 SDLoc DL(Op); 3587 EVT Ty = Op.getValueType(); 3588 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3589 int64_t Offset = N->getOffset(); 3590 MVT XLenVT = Subtarget.getXLenVT(); 3591 3592 const GlobalValue *GV = N->getGlobal(); 3593 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3594 SDValue Addr = getAddr(N, DAG, IsLocal); 3595 3596 // In order to maximise the opportunity for common subexpression elimination, 3597 // emit a separate ADD node for the global address offset instead of folding 3598 // it in the global address node. Later peephole optimisations may choose to 3599 // fold it back in when profitable. 3600 if (Offset != 0) 3601 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3602 DAG.getConstant(Offset, DL, XLenVT)); 3603 return Addr; 3604 } 3605 3606 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3607 SelectionDAG &DAG) const { 3608 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3609 3610 return getAddr(N, DAG); 3611 } 3612 3613 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3614 SelectionDAG &DAG) const { 3615 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3616 3617 return getAddr(N, DAG); 3618 } 3619 3620 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3621 SelectionDAG &DAG) const { 3622 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3623 3624 return getAddr(N, DAG); 3625 } 3626 3627 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3628 SelectionDAG &DAG, 3629 bool UseGOT) const { 3630 SDLoc DL(N); 3631 EVT Ty = getPointerTy(DAG.getDataLayout()); 3632 const GlobalValue *GV = N->getGlobal(); 3633 MVT XLenVT = Subtarget.getXLenVT(); 3634 3635 if (UseGOT) { 3636 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3637 // load the address from the GOT and add the thread pointer. This generates 3638 // the pattern (PseudoLA_TLS_IE sym), which expands to 3639 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3640 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3641 SDValue Load = 3642 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3643 MachineFunction &MF = DAG.getMachineFunction(); 3644 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3645 MachinePointerInfo::getGOT(MF), 3646 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3647 MachineMemOperand::MOInvariant, 3648 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3649 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3650 3651 // Add the thread pointer. 3652 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3653 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3654 } 3655 3656 // Generate a sequence for accessing the address relative to the thread 3657 // pointer, with the appropriate adjustment for the thread pointer offset. 3658 // This generates the pattern 3659 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3660 SDValue AddrHi = 3661 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3662 SDValue AddrAdd = 3663 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3664 SDValue AddrLo = 3665 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3666 3667 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3668 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3669 SDValue MNAdd = SDValue( 3670 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3671 0); 3672 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3673 } 3674 3675 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3676 SelectionDAG &DAG) const { 3677 SDLoc DL(N); 3678 EVT Ty = getPointerTy(DAG.getDataLayout()); 3679 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3680 const GlobalValue *GV = N->getGlobal(); 3681 3682 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3683 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3684 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3685 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3686 SDValue Load = 3687 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3688 3689 // Prepare argument list to generate call. 3690 ArgListTy Args; 3691 ArgListEntry Entry; 3692 Entry.Node = Load; 3693 Entry.Ty = CallTy; 3694 Args.push_back(Entry); 3695 3696 // Setup call to __tls_get_addr. 3697 TargetLowering::CallLoweringInfo CLI(DAG); 3698 CLI.setDebugLoc(DL) 3699 .setChain(DAG.getEntryNode()) 3700 .setLibCallee(CallingConv::C, CallTy, 3701 DAG.getExternalSymbol("__tls_get_addr", Ty), 3702 std::move(Args)); 3703 3704 return LowerCallTo(CLI).first; 3705 } 3706 3707 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3708 SelectionDAG &DAG) const { 3709 SDLoc DL(Op); 3710 EVT Ty = Op.getValueType(); 3711 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3712 int64_t Offset = N->getOffset(); 3713 MVT XLenVT = Subtarget.getXLenVT(); 3714 3715 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3716 3717 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3718 CallingConv::GHC) 3719 report_fatal_error("In GHC calling convention TLS is not supported"); 3720 3721 SDValue Addr; 3722 switch (Model) { 3723 case TLSModel::LocalExec: 3724 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3725 break; 3726 case TLSModel::InitialExec: 3727 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3728 break; 3729 case TLSModel::LocalDynamic: 3730 case TLSModel::GeneralDynamic: 3731 Addr = getDynamicTLSAddr(N, DAG); 3732 break; 3733 } 3734 3735 // In order to maximise the opportunity for common subexpression elimination, 3736 // emit a separate ADD node for the global address offset instead of folding 3737 // it in the global address node. Later peephole optimisations may choose to 3738 // fold it back in when profitable. 3739 if (Offset != 0) 3740 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3741 DAG.getConstant(Offset, DL, XLenVT)); 3742 return Addr; 3743 } 3744 3745 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3746 SDValue CondV = Op.getOperand(0); 3747 SDValue TrueV = Op.getOperand(1); 3748 SDValue FalseV = Op.getOperand(2); 3749 SDLoc DL(Op); 3750 MVT VT = Op.getSimpleValueType(); 3751 MVT XLenVT = Subtarget.getXLenVT(); 3752 3753 // Lower vector SELECTs to VSELECTs by splatting the condition. 3754 if (VT.isVector()) { 3755 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3756 SDValue CondSplat = VT.isScalableVector() 3757 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3758 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3759 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3760 } 3761 3762 // If the result type is XLenVT and CondV is the output of a SETCC node 3763 // which also operated on XLenVT inputs, then merge the SETCC node into the 3764 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3765 // compare+branch instructions. i.e.: 3766 // (select (setcc lhs, rhs, cc), truev, falsev) 3767 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3768 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3769 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3770 SDValue LHS = CondV.getOperand(0); 3771 SDValue RHS = CondV.getOperand(1); 3772 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3773 ISD::CondCode CCVal = CC->get(); 3774 3775 // Special case for a select of 2 constants that have a diffence of 1. 3776 // Normally this is done by DAGCombine, but if the select is introduced by 3777 // type legalization or op legalization, we miss it. Restricting to SETLT 3778 // case for now because that is what signed saturating add/sub need. 3779 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3780 // but we would probably want to swap the true/false values if the condition 3781 // is SETGE/SETLE to avoid an XORI. 3782 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3783 CCVal == ISD::SETLT) { 3784 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3785 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3786 if (TrueVal - 1 == FalseVal) 3787 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3788 if (TrueVal + 1 == FalseVal) 3789 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3790 } 3791 3792 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3793 3794 SDValue TargetCC = DAG.getCondCode(CCVal); 3795 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3796 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3797 } 3798 3799 // Otherwise: 3800 // (select condv, truev, falsev) 3801 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3802 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3803 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3804 3805 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3806 3807 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3808 } 3809 3810 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3811 SDValue CondV = Op.getOperand(1); 3812 SDLoc DL(Op); 3813 MVT XLenVT = Subtarget.getXLenVT(); 3814 3815 if (CondV.getOpcode() == ISD::SETCC && 3816 CondV.getOperand(0).getValueType() == XLenVT) { 3817 SDValue LHS = CondV.getOperand(0); 3818 SDValue RHS = CondV.getOperand(1); 3819 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3820 3821 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3822 3823 SDValue TargetCC = DAG.getCondCode(CCVal); 3824 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3825 LHS, RHS, TargetCC, Op.getOperand(2)); 3826 } 3827 3828 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3829 CondV, DAG.getConstant(0, DL, XLenVT), 3830 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3831 } 3832 3833 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3834 MachineFunction &MF = DAG.getMachineFunction(); 3835 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3836 3837 SDLoc DL(Op); 3838 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3839 getPointerTy(MF.getDataLayout())); 3840 3841 // vastart just stores the address of the VarArgsFrameIndex slot into the 3842 // memory location argument. 3843 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3844 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3845 MachinePointerInfo(SV)); 3846 } 3847 3848 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3849 SelectionDAG &DAG) const { 3850 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3851 MachineFunction &MF = DAG.getMachineFunction(); 3852 MachineFrameInfo &MFI = MF.getFrameInfo(); 3853 MFI.setFrameAddressIsTaken(true); 3854 Register FrameReg = RI.getFrameRegister(MF); 3855 int XLenInBytes = Subtarget.getXLen() / 8; 3856 3857 EVT VT = Op.getValueType(); 3858 SDLoc DL(Op); 3859 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3860 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3861 while (Depth--) { 3862 int Offset = -(XLenInBytes * 2); 3863 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3864 DAG.getIntPtrConstant(Offset, DL)); 3865 FrameAddr = 3866 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3867 } 3868 return FrameAddr; 3869 } 3870 3871 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3872 SelectionDAG &DAG) const { 3873 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3874 MachineFunction &MF = DAG.getMachineFunction(); 3875 MachineFrameInfo &MFI = MF.getFrameInfo(); 3876 MFI.setReturnAddressIsTaken(true); 3877 MVT XLenVT = Subtarget.getXLenVT(); 3878 int XLenInBytes = Subtarget.getXLen() / 8; 3879 3880 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3881 return SDValue(); 3882 3883 EVT VT = Op.getValueType(); 3884 SDLoc DL(Op); 3885 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3886 if (Depth) { 3887 int Off = -XLenInBytes; 3888 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3889 SDValue Offset = DAG.getConstant(Off, DL, VT); 3890 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3891 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3892 MachinePointerInfo()); 3893 } 3894 3895 // Return the value of the return address register, marking it an implicit 3896 // live-in. 3897 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3898 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3899 } 3900 3901 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3902 SelectionDAG &DAG) const { 3903 SDLoc DL(Op); 3904 SDValue Lo = Op.getOperand(0); 3905 SDValue Hi = Op.getOperand(1); 3906 SDValue Shamt = Op.getOperand(2); 3907 EVT VT = Lo.getValueType(); 3908 3909 // if Shamt-XLEN < 0: // Shamt < XLEN 3910 // Lo = Lo << Shamt 3911 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3912 // else: 3913 // Lo = 0 3914 // Hi = Lo << (Shamt-XLEN) 3915 3916 SDValue Zero = DAG.getConstant(0, DL, VT); 3917 SDValue One = DAG.getConstant(1, DL, VT); 3918 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3919 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3920 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3921 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3922 3923 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3924 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3925 SDValue ShiftRightLo = 3926 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3927 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3928 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3929 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3930 3931 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3932 3933 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3934 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3935 3936 SDValue Parts[2] = {Lo, Hi}; 3937 return DAG.getMergeValues(Parts, DL); 3938 } 3939 3940 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3941 bool IsSRA) const { 3942 SDLoc DL(Op); 3943 SDValue Lo = Op.getOperand(0); 3944 SDValue Hi = Op.getOperand(1); 3945 SDValue Shamt = Op.getOperand(2); 3946 EVT VT = Lo.getValueType(); 3947 3948 // SRA expansion: 3949 // if Shamt-XLEN < 0: // Shamt < XLEN 3950 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3951 // Hi = Hi >>s Shamt 3952 // else: 3953 // Lo = Hi >>s (Shamt-XLEN); 3954 // Hi = Hi >>s (XLEN-1) 3955 // 3956 // SRL expansion: 3957 // if Shamt-XLEN < 0: // Shamt < XLEN 3958 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3959 // Hi = Hi >>u Shamt 3960 // else: 3961 // Lo = Hi >>u (Shamt-XLEN); 3962 // Hi = 0; 3963 3964 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3965 3966 SDValue Zero = DAG.getConstant(0, DL, VT); 3967 SDValue One = DAG.getConstant(1, DL, VT); 3968 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3969 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3970 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3971 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3972 3973 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3974 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3975 SDValue ShiftLeftHi = 3976 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3977 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3978 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3979 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3980 SDValue HiFalse = 3981 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3982 3983 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3984 3985 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3986 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3987 3988 SDValue Parts[2] = {Lo, Hi}; 3989 return DAG.getMergeValues(Parts, DL); 3990 } 3991 3992 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3993 // legal equivalently-sized i8 type, so we can use that as a go-between. 3994 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3995 SelectionDAG &DAG) const { 3996 SDLoc DL(Op); 3997 MVT VT = Op.getSimpleValueType(); 3998 SDValue SplatVal = Op.getOperand(0); 3999 // All-zeros or all-ones splats are handled specially. 4000 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4001 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4002 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4003 } 4004 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4005 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4006 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4007 } 4008 MVT XLenVT = Subtarget.getXLenVT(); 4009 assert(SplatVal.getValueType() == XLenVT && 4010 "Unexpected type for i1 splat value"); 4011 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4012 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4013 DAG.getConstant(1, DL, XLenVT)); 4014 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4015 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4016 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4017 } 4018 4019 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4020 // illegal (currently only vXi64 RV32). 4021 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4022 // them to VMV_V_X_VL. 4023 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4024 SelectionDAG &DAG) const { 4025 SDLoc DL(Op); 4026 MVT VecVT = Op.getSimpleValueType(); 4027 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4028 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4029 4030 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4031 SDValue Lo = Op.getOperand(0); 4032 SDValue Hi = Op.getOperand(1); 4033 4034 if (VecVT.isFixedLengthVector()) { 4035 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4036 SDLoc DL(Op); 4037 SDValue Mask, VL; 4038 std::tie(Mask, VL) = 4039 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4040 4041 SDValue Res = 4042 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4043 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4044 } 4045 4046 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4047 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4048 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4049 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4050 // node in order to try and match RVV vector/scalar instructions. 4051 if ((LoC >> 31) == HiC) 4052 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4053 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4054 } 4055 4056 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4057 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4058 isa<ConstantSDNode>(Hi.getOperand(1)) && 4059 Hi.getConstantOperandVal(1) == 31) 4060 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4061 DAG.getRegister(RISCV::X0, MVT::i32)); 4062 4063 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4064 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4065 DAG.getUNDEF(VecVT), Lo, Hi, 4066 DAG.getRegister(RISCV::X0, MVT::i32)); 4067 } 4068 4069 // Custom-lower extensions from mask vectors by using a vselect either with 1 4070 // for zero/any-extension or -1 for sign-extension: 4071 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4072 // Note that any-extension is lowered identically to zero-extension. 4073 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4074 int64_t ExtTrueVal) const { 4075 SDLoc DL(Op); 4076 MVT VecVT = Op.getSimpleValueType(); 4077 SDValue Src = Op.getOperand(0); 4078 // Only custom-lower extensions from mask types 4079 assert(Src.getValueType().isVector() && 4080 Src.getValueType().getVectorElementType() == MVT::i1); 4081 4082 if (VecVT.isScalableVector()) { 4083 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4084 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4085 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4086 } 4087 4088 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4089 MVT I1ContainerVT = 4090 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4091 4092 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4093 4094 SDValue Mask, VL; 4095 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4096 4097 MVT XLenVT = Subtarget.getXLenVT(); 4098 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4099 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4100 4101 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4102 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4103 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4104 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4105 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4106 SplatTrueVal, SplatZero, VL); 4107 4108 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4109 } 4110 4111 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4112 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4113 MVT ExtVT = Op.getSimpleValueType(); 4114 // Only custom-lower extensions from fixed-length vector types. 4115 if (!ExtVT.isFixedLengthVector()) 4116 return Op; 4117 MVT VT = Op.getOperand(0).getSimpleValueType(); 4118 // Grab the canonical container type for the extended type. Infer the smaller 4119 // type from that to ensure the same number of vector elements, as we know 4120 // the LMUL will be sufficient to hold the smaller type. 4121 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4122 // Get the extended container type manually to ensure the same number of 4123 // vector elements between source and dest. 4124 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4125 ContainerExtVT.getVectorElementCount()); 4126 4127 SDValue Op1 = 4128 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4129 4130 SDLoc DL(Op); 4131 SDValue Mask, VL; 4132 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4133 4134 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4135 4136 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4137 } 4138 4139 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4140 // setcc operation: 4141 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4142 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4143 SelectionDAG &DAG) const { 4144 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4145 SDLoc DL(Op); 4146 EVT MaskVT = Op.getValueType(); 4147 // Only expect to custom-lower truncations to mask types 4148 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4149 "Unexpected type for vector mask lowering"); 4150 SDValue Src = Op.getOperand(0); 4151 MVT VecVT = Src.getSimpleValueType(); 4152 SDValue Mask, VL; 4153 if (IsVPTrunc) { 4154 Mask = Op.getOperand(1); 4155 VL = Op.getOperand(2); 4156 } 4157 // If this is a fixed vector, we need to convert it to a scalable vector. 4158 MVT ContainerVT = VecVT; 4159 4160 if (VecVT.isFixedLengthVector()) { 4161 ContainerVT = getContainerForFixedLengthVector(VecVT); 4162 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4163 if (IsVPTrunc) { 4164 MVT MaskContainerVT = 4165 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4166 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4167 } 4168 } 4169 4170 if (!IsVPTrunc) { 4171 std::tie(Mask, VL) = 4172 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4173 } 4174 4175 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4176 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4177 4178 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4179 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4180 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4181 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4182 4183 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4184 SDValue Trunc = 4185 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4186 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4187 DAG.getCondCode(ISD::SETNE), Mask, VL); 4188 if (MaskVT.isFixedLengthVector()) 4189 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4190 return Trunc; 4191 } 4192 4193 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4194 SelectionDAG &DAG) const { 4195 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4196 SDLoc DL(Op); 4197 4198 MVT VT = Op.getSimpleValueType(); 4199 // Only custom-lower vector truncates 4200 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4201 4202 // Truncates to mask types are handled differently 4203 if (VT.getVectorElementType() == MVT::i1) 4204 return lowerVectorMaskTruncLike(Op, DAG); 4205 4206 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4207 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4208 // truncate by one power of two at a time. 4209 MVT DstEltVT = VT.getVectorElementType(); 4210 4211 SDValue Src = Op.getOperand(0); 4212 MVT SrcVT = Src.getSimpleValueType(); 4213 MVT SrcEltVT = SrcVT.getVectorElementType(); 4214 4215 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4216 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4217 "Unexpected vector truncate lowering"); 4218 4219 MVT ContainerVT = SrcVT; 4220 SDValue Mask, VL; 4221 if (IsVPTrunc) { 4222 Mask = Op.getOperand(1); 4223 VL = Op.getOperand(2); 4224 } 4225 if (SrcVT.isFixedLengthVector()) { 4226 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4227 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4228 if (IsVPTrunc) { 4229 MVT MaskVT = getMaskTypeFor(ContainerVT); 4230 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4231 } 4232 } 4233 4234 SDValue Result = Src; 4235 if (!IsVPTrunc) { 4236 std::tie(Mask, VL) = 4237 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4238 } 4239 4240 LLVMContext &Context = *DAG.getContext(); 4241 const ElementCount Count = ContainerVT.getVectorElementCount(); 4242 do { 4243 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4244 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4245 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4246 Mask, VL); 4247 } while (SrcEltVT != DstEltVT); 4248 4249 if (SrcVT.isFixedLengthVector()) 4250 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4251 4252 return Result; 4253 } 4254 4255 SDValue 4256 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4257 SelectionDAG &DAG) const { 4258 bool IsVP = 4259 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4260 bool IsExtend = 4261 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4262 // RVV can only do truncate fp to types half the size as the source. We 4263 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4264 // conversion instruction. 4265 SDLoc DL(Op); 4266 MVT VT = Op.getSimpleValueType(); 4267 4268 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4269 4270 SDValue Src = Op.getOperand(0); 4271 MVT SrcVT = Src.getSimpleValueType(); 4272 4273 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4274 SrcVT.getVectorElementType() != MVT::f16); 4275 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4276 SrcVT.getVectorElementType() != MVT::f64); 4277 4278 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4279 4280 // For FP_ROUND/FP_EXTEND of scalable vectors, leave it to the pattern. 4281 if (!VT.isFixedLengthVector() && !IsVP && IsDirectConv) 4282 return Op; 4283 4284 // Prepare any fixed-length vector operands. 4285 MVT ContainerVT = VT; 4286 SDValue Mask, VL; 4287 if (IsVP) { 4288 Mask = Op.getOperand(1); 4289 VL = Op.getOperand(2); 4290 } 4291 if (VT.isFixedLengthVector()) { 4292 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4293 ContainerVT = 4294 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4295 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4296 if (IsVP) { 4297 MVT MaskVT = getMaskTypeFor(ContainerVT); 4298 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4299 } 4300 } 4301 4302 if (!IsVP) 4303 std::tie(Mask, VL) = 4304 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4305 4306 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4307 4308 if (IsDirectConv) { 4309 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4310 if (VT.isFixedLengthVector()) 4311 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4312 return Src; 4313 } 4314 4315 unsigned InterConvOpc = 4316 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4317 4318 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4319 SDValue IntermediateConv = 4320 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4321 SDValue Result = 4322 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4323 if (VT.isFixedLengthVector()) 4324 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4325 return Result; 4326 } 4327 4328 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4329 // first position of a vector, and that vector is slid up to the insert index. 4330 // By limiting the active vector length to index+1 and merging with the 4331 // original vector (with an undisturbed tail policy for elements >= VL), we 4332 // achieve the desired result of leaving all elements untouched except the one 4333 // at VL-1, which is replaced with the desired value. 4334 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4335 SelectionDAG &DAG) const { 4336 SDLoc DL(Op); 4337 MVT VecVT = Op.getSimpleValueType(); 4338 SDValue Vec = Op.getOperand(0); 4339 SDValue Val = Op.getOperand(1); 4340 SDValue Idx = Op.getOperand(2); 4341 4342 if (VecVT.getVectorElementType() == MVT::i1) { 4343 // FIXME: For now we just promote to an i8 vector and insert into that, 4344 // but this is probably not optimal. 4345 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4346 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4347 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4348 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4349 } 4350 4351 MVT ContainerVT = VecVT; 4352 // If the operand is a fixed-length vector, convert to a scalable one. 4353 if (VecVT.isFixedLengthVector()) { 4354 ContainerVT = getContainerForFixedLengthVector(VecVT); 4355 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4356 } 4357 4358 MVT XLenVT = Subtarget.getXLenVT(); 4359 4360 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4361 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4362 // Even i64-element vectors on RV32 can be lowered without scalar 4363 // legalization if the most-significant 32 bits of the value are not affected 4364 // by the sign-extension of the lower 32 bits. 4365 // TODO: We could also catch sign extensions of a 32-bit value. 4366 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4367 const auto *CVal = cast<ConstantSDNode>(Val); 4368 if (isInt<32>(CVal->getSExtValue())) { 4369 IsLegalInsert = true; 4370 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4371 } 4372 } 4373 4374 SDValue Mask, VL; 4375 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4376 4377 SDValue ValInVec; 4378 4379 if (IsLegalInsert) { 4380 unsigned Opc = 4381 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4382 if (isNullConstant(Idx)) { 4383 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4384 if (!VecVT.isFixedLengthVector()) 4385 return Vec; 4386 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4387 } 4388 ValInVec = 4389 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4390 } else { 4391 // On RV32, i64-element vectors must be specially handled to place the 4392 // value at element 0, by using two vslide1up instructions in sequence on 4393 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4394 // this. 4395 SDValue One = DAG.getConstant(1, DL, XLenVT); 4396 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4397 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4398 MVT I32ContainerVT = 4399 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4400 SDValue I32Mask = 4401 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4402 // Limit the active VL to two. 4403 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4404 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4405 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4406 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4407 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4408 // First slide in the hi value, then the lo in underneath it. 4409 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4410 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4411 I32Mask, InsertI64VL); 4412 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4413 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4414 I32Mask, InsertI64VL); 4415 // Bitcast back to the right container type. 4416 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4417 } 4418 4419 // Now that the value is in a vector, slide it into position. 4420 SDValue InsertVL = 4421 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4422 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4423 ValInVec, Idx, Mask, InsertVL); 4424 if (!VecVT.isFixedLengthVector()) 4425 return Slideup; 4426 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4427 } 4428 4429 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4430 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4431 // types this is done using VMV_X_S to allow us to glean information about the 4432 // sign bits of the result. 4433 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4434 SelectionDAG &DAG) const { 4435 SDLoc DL(Op); 4436 SDValue Idx = Op.getOperand(1); 4437 SDValue Vec = Op.getOperand(0); 4438 EVT EltVT = Op.getValueType(); 4439 MVT VecVT = Vec.getSimpleValueType(); 4440 MVT XLenVT = Subtarget.getXLenVT(); 4441 4442 if (VecVT.getVectorElementType() == MVT::i1) { 4443 if (VecVT.isFixedLengthVector()) { 4444 unsigned NumElts = VecVT.getVectorNumElements(); 4445 if (NumElts >= 8) { 4446 MVT WideEltVT; 4447 unsigned WidenVecLen; 4448 SDValue ExtractElementIdx; 4449 SDValue ExtractBitIdx; 4450 unsigned MaxEEW = Subtarget.getELEN(); 4451 MVT LargestEltVT = MVT::getIntegerVT( 4452 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4453 if (NumElts <= LargestEltVT.getSizeInBits()) { 4454 assert(isPowerOf2_32(NumElts) && 4455 "the number of elements should be power of 2"); 4456 WideEltVT = MVT::getIntegerVT(NumElts); 4457 WidenVecLen = 1; 4458 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4459 ExtractBitIdx = Idx; 4460 } else { 4461 WideEltVT = LargestEltVT; 4462 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4463 // extract element index = index / element width 4464 ExtractElementIdx = DAG.getNode( 4465 ISD::SRL, DL, XLenVT, Idx, 4466 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4467 // mask bit index = index % element width 4468 ExtractBitIdx = DAG.getNode( 4469 ISD::AND, DL, XLenVT, Idx, 4470 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4471 } 4472 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4473 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4474 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4475 Vec, ExtractElementIdx); 4476 // Extract the bit from GPR. 4477 SDValue ShiftRight = 4478 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4479 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4480 DAG.getConstant(1, DL, XLenVT)); 4481 } 4482 } 4483 // Otherwise, promote to an i8 vector and extract from that. 4484 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4485 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4486 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4487 } 4488 4489 // If this is a fixed vector, we need to convert it to a scalable vector. 4490 MVT ContainerVT = VecVT; 4491 if (VecVT.isFixedLengthVector()) { 4492 ContainerVT = getContainerForFixedLengthVector(VecVT); 4493 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4494 } 4495 4496 // If the index is 0, the vector is already in the right position. 4497 if (!isNullConstant(Idx)) { 4498 // Use a VL of 1 to avoid processing more elements than we need. 4499 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4500 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4501 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4502 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4503 } 4504 4505 if (!EltVT.isInteger()) { 4506 // Floating-point extracts are handled in TableGen. 4507 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4508 DAG.getConstant(0, DL, XLenVT)); 4509 } 4510 4511 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4512 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4513 } 4514 4515 // Some RVV intrinsics may claim that they want an integer operand to be 4516 // promoted or expanded. 4517 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4518 const RISCVSubtarget &Subtarget) { 4519 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4520 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4521 "Unexpected opcode"); 4522 4523 if (!Subtarget.hasVInstructions()) 4524 return SDValue(); 4525 4526 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4527 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4528 SDLoc DL(Op); 4529 4530 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4531 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4532 if (!II || !II->hasScalarOperand()) 4533 return SDValue(); 4534 4535 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4536 assert(SplatOp < Op.getNumOperands()); 4537 4538 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4539 SDValue &ScalarOp = Operands[SplatOp]; 4540 MVT OpVT = ScalarOp.getSimpleValueType(); 4541 MVT XLenVT = Subtarget.getXLenVT(); 4542 4543 // If this isn't a scalar, or its type is XLenVT we're done. 4544 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4545 return SDValue(); 4546 4547 // Simplest case is that the operand needs to be promoted to XLenVT. 4548 if (OpVT.bitsLT(XLenVT)) { 4549 // If the operand is a constant, sign extend to increase our chances 4550 // of being able to use a .vi instruction. ANY_EXTEND would become a 4551 // a zero extend and the simm5 check in isel would fail. 4552 // FIXME: Should we ignore the upper bits in isel instead? 4553 unsigned ExtOpc = 4554 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4555 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4556 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4557 } 4558 4559 // Use the previous operand to get the vXi64 VT. The result might be a mask 4560 // VT for compares. Using the previous operand assumes that the previous 4561 // operand will never have a smaller element size than a scalar operand and 4562 // that a widening operation never uses SEW=64. 4563 // NOTE: If this fails the below assert, we can probably just find the 4564 // element count from any operand or result and use it to construct the VT. 4565 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4566 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4567 4568 // The more complex case is when the scalar is larger than XLenVT. 4569 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4570 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4571 4572 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4573 // instruction to sign-extend since SEW>XLEN. 4574 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4575 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4576 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4577 } 4578 4579 switch (IntNo) { 4580 case Intrinsic::riscv_vslide1up: 4581 case Intrinsic::riscv_vslide1down: 4582 case Intrinsic::riscv_vslide1up_mask: 4583 case Intrinsic::riscv_vslide1down_mask: { 4584 // We need to special case these when the scalar is larger than XLen. 4585 unsigned NumOps = Op.getNumOperands(); 4586 bool IsMasked = NumOps == 7; 4587 4588 // Convert the vector source to the equivalent nxvXi32 vector. 4589 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4590 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4591 4592 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4593 DAG.getConstant(0, DL, XLenVT)); 4594 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4595 DAG.getConstant(1, DL, XLenVT)); 4596 4597 // Double the VL since we halved SEW. 4598 SDValue AVL = getVLOperand(Op); 4599 SDValue I32VL; 4600 4601 // Optimize for constant AVL 4602 if (isa<ConstantSDNode>(AVL)) { 4603 unsigned EltSize = VT.getScalarSizeInBits(); 4604 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4605 4606 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4607 unsigned MaxVLMAX = 4608 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4609 4610 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4611 unsigned MinVLMAX = 4612 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4613 4614 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4615 if (AVLInt <= MinVLMAX) { 4616 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4617 } else if (AVLInt >= 2 * MaxVLMAX) { 4618 // Just set vl to VLMAX in this situation 4619 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4620 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4621 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4622 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4623 SDValue SETVLMAX = DAG.getTargetConstant( 4624 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4625 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4626 LMUL); 4627 } else { 4628 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4629 // is related to the hardware implementation. 4630 // So let the following code handle 4631 } 4632 } 4633 if (!I32VL) { 4634 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4635 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4636 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4637 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4638 SDValue SETVL = 4639 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4640 // Using vsetvli instruction to get actually used length which related to 4641 // the hardware implementation 4642 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4643 SEW, LMUL); 4644 I32VL = 4645 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4646 } 4647 4648 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4649 4650 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4651 // instructions. 4652 SDValue Passthru; 4653 if (IsMasked) 4654 Passthru = DAG.getUNDEF(I32VT); 4655 else 4656 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4657 4658 if (IntNo == Intrinsic::riscv_vslide1up || 4659 IntNo == Intrinsic::riscv_vslide1up_mask) { 4660 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4661 ScalarHi, I32Mask, I32VL); 4662 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4663 ScalarLo, I32Mask, I32VL); 4664 } else { 4665 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4666 ScalarLo, I32Mask, I32VL); 4667 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4668 ScalarHi, I32Mask, I32VL); 4669 } 4670 4671 // Convert back to nxvXi64. 4672 Vec = DAG.getBitcast(VT, Vec); 4673 4674 if (!IsMasked) 4675 return Vec; 4676 // Apply mask after the operation. 4677 SDValue Mask = Operands[NumOps - 3]; 4678 SDValue MaskedOff = Operands[1]; 4679 // Assume Policy operand is the last operand. 4680 uint64_t Policy = 4681 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4682 // We don't need to select maskedoff if it's undef. 4683 if (MaskedOff.isUndef()) 4684 return Vec; 4685 // TAMU 4686 if (Policy == RISCVII::TAIL_AGNOSTIC) 4687 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4688 AVL); 4689 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4690 // It's fine because vmerge does not care mask policy. 4691 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4692 AVL); 4693 } 4694 } 4695 4696 // We need to convert the scalar to a splat vector. 4697 SDValue VL = getVLOperand(Op); 4698 assert(VL.getValueType() == XLenVT); 4699 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4700 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4701 } 4702 4703 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4704 SelectionDAG &DAG) const { 4705 unsigned IntNo = Op.getConstantOperandVal(0); 4706 SDLoc DL(Op); 4707 MVT XLenVT = Subtarget.getXLenVT(); 4708 4709 switch (IntNo) { 4710 default: 4711 break; // Don't custom lower most intrinsics. 4712 case Intrinsic::thread_pointer: { 4713 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4714 return DAG.getRegister(RISCV::X4, PtrVT); 4715 } 4716 case Intrinsic::riscv_orc_b: 4717 case Intrinsic::riscv_brev8: { 4718 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4719 unsigned Opc = 4720 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4721 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4722 DAG.getConstant(7, DL, XLenVT)); 4723 } 4724 case Intrinsic::riscv_grev: 4725 case Intrinsic::riscv_gorc: { 4726 unsigned Opc = 4727 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4728 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4729 } 4730 case Intrinsic::riscv_zip: 4731 case Intrinsic::riscv_unzip: { 4732 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4733 // For i32 the immediate is 15. For i64 the immediate is 31. 4734 unsigned Opc = 4735 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4736 unsigned BitWidth = Op.getValueSizeInBits(); 4737 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4738 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4739 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4740 } 4741 case Intrinsic::riscv_shfl: 4742 case Intrinsic::riscv_unshfl: { 4743 unsigned Opc = 4744 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4745 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4746 } 4747 case Intrinsic::riscv_bcompress: 4748 case Intrinsic::riscv_bdecompress: { 4749 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4750 : RISCVISD::BDECOMPRESS; 4751 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4752 } 4753 case Intrinsic::riscv_bfp: 4754 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4755 Op.getOperand(2)); 4756 case Intrinsic::riscv_fsl: 4757 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4758 Op.getOperand(2), Op.getOperand(3)); 4759 case Intrinsic::riscv_fsr: 4760 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4761 Op.getOperand(2), Op.getOperand(3)); 4762 case Intrinsic::riscv_vmv_x_s: 4763 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4764 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4765 Op.getOperand(1)); 4766 case Intrinsic::riscv_vmv_v_x: 4767 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4768 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4769 Subtarget); 4770 case Intrinsic::riscv_vfmv_v_f: 4771 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4772 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4773 case Intrinsic::riscv_vmv_s_x: { 4774 SDValue Scalar = Op.getOperand(2); 4775 4776 if (Scalar.getValueType().bitsLE(XLenVT)) { 4777 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4778 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4779 Op.getOperand(1), Scalar, Op.getOperand(3)); 4780 } 4781 4782 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4783 4784 // This is an i64 value that lives in two scalar registers. We have to 4785 // insert this in a convoluted way. First we build vXi64 splat containing 4786 // the two values that we assemble using some bit math. Next we'll use 4787 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4788 // to merge element 0 from our splat into the source vector. 4789 // FIXME: This is probably not the best way to do this, but it is 4790 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4791 // point. 4792 // sw lo, (a0) 4793 // sw hi, 4(a0) 4794 // vlse vX, (a0) 4795 // 4796 // vid.v vVid 4797 // vmseq.vx mMask, vVid, 0 4798 // vmerge.vvm vDest, vSrc, vVal, mMask 4799 MVT VT = Op.getSimpleValueType(); 4800 SDValue Vec = Op.getOperand(1); 4801 SDValue VL = getVLOperand(Op); 4802 4803 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4804 if (Op.getOperand(1).isUndef()) 4805 return SplattedVal; 4806 SDValue SplattedIdx = 4807 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4808 DAG.getConstant(0, DL, MVT::i32), VL); 4809 4810 MVT MaskVT = getMaskTypeFor(VT); 4811 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4812 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4813 SDValue SelectCond = 4814 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4815 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4816 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4817 Vec, VL); 4818 } 4819 } 4820 4821 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4822 } 4823 4824 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4825 SelectionDAG &DAG) const { 4826 unsigned IntNo = Op.getConstantOperandVal(1); 4827 switch (IntNo) { 4828 default: 4829 break; 4830 case Intrinsic::riscv_masked_strided_load: { 4831 SDLoc DL(Op); 4832 MVT XLenVT = Subtarget.getXLenVT(); 4833 4834 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4835 // the selection of the masked intrinsics doesn't do this for us. 4836 SDValue Mask = Op.getOperand(5); 4837 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4838 4839 MVT VT = Op->getSimpleValueType(0); 4840 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4841 4842 SDValue PassThru = Op.getOperand(2); 4843 if (!IsUnmasked) { 4844 MVT MaskVT = getMaskTypeFor(ContainerVT); 4845 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4846 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4847 } 4848 4849 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4850 4851 SDValue IntID = DAG.getTargetConstant( 4852 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4853 XLenVT); 4854 4855 auto *Load = cast<MemIntrinsicSDNode>(Op); 4856 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4857 if (IsUnmasked) 4858 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4859 else 4860 Ops.push_back(PassThru); 4861 Ops.push_back(Op.getOperand(3)); // Ptr 4862 Ops.push_back(Op.getOperand(4)); // Stride 4863 if (!IsUnmasked) 4864 Ops.push_back(Mask); 4865 Ops.push_back(VL); 4866 if (!IsUnmasked) { 4867 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4868 Ops.push_back(Policy); 4869 } 4870 4871 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4872 SDValue Result = 4873 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4874 Load->getMemoryVT(), Load->getMemOperand()); 4875 SDValue Chain = Result.getValue(1); 4876 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4877 return DAG.getMergeValues({Result, Chain}, DL); 4878 } 4879 case Intrinsic::riscv_seg2_load: 4880 case Intrinsic::riscv_seg3_load: 4881 case Intrinsic::riscv_seg4_load: 4882 case Intrinsic::riscv_seg5_load: 4883 case Intrinsic::riscv_seg6_load: 4884 case Intrinsic::riscv_seg7_load: 4885 case Intrinsic::riscv_seg8_load: { 4886 SDLoc DL(Op); 4887 static const Intrinsic::ID VlsegInts[7] = { 4888 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4889 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4890 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4891 Intrinsic::riscv_vlseg8}; 4892 unsigned NF = Op->getNumValues() - 1; 4893 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4894 MVT XLenVT = Subtarget.getXLenVT(); 4895 MVT VT = Op->getSimpleValueType(0); 4896 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4897 4898 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4899 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4900 auto *Load = cast<MemIntrinsicSDNode>(Op); 4901 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4902 ContainerVTs.push_back(MVT::Other); 4903 SDVTList VTs = DAG.getVTList(ContainerVTs); 4904 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4905 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4906 Ops.push_back(Op.getOperand(2)); 4907 Ops.push_back(VL); 4908 SDValue Result = 4909 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4910 Load->getMemoryVT(), Load->getMemOperand()); 4911 SmallVector<SDValue, 9> Results; 4912 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4913 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4914 DAG, Subtarget)); 4915 Results.push_back(Result.getValue(NF)); 4916 return DAG.getMergeValues(Results, DL); 4917 } 4918 } 4919 4920 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4921 } 4922 4923 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4924 SelectionDAG &DAG) const { 4925 unsigned IntNo = Op.getConstantOperandVal(1); 4926 switch (IntNo) { 4927 default: 4928 break; 4929 case Intrinsic::riscv_masked_strided_store: { 4930 SDLoc DL(Op); 4931 MVT XLenVT = Subtarget.getXLenVT(); 4932 4933 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4934 // the selection of the masked intrinsics doesn't do this for us. 4935 SDValue Mask = Op.getOperand(5); 4936 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4937 4938 SDValue Val = Op.getOperand(2); 4939 MVT VT = Val.getSimpleValueType(); 4940 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4941 4942 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4943 if (!IsUnmasked) { 4944 MVT MaskVT = getMaskTypeFor(ContainerVT); 4945 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4946 } 4947 4948 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4949 4950 SDValue IntID = DAG.getTargetConstant( 4951 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4952 XLenVT); 4953 4954 auto *Store = cast<MemIntrinsicSDNode>(Op); 4955 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4956 Ops.push_back(Val); 4957 Ops.push_back(Op.getOperand(3)); // Ptr 4958 Ops.push_back(Op.getOperand(4)); // Stride 4959 if (!IsUnmasked) 4960 Ops.push_back(Mask); 4961 Ops.push_back(VL); 4962 4963 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4964 Ops, Store->getMemoryVT(), 4965 Store->getMemOperand()); 4966 } 4967 } 4968 4969 return SDValue(); 4970 } 4971 4972 static MVT getLMUL1VT(MVT VT) { 4973 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4974 "Unexpected vector MVT"); 4975 return MVT::getScalableVectorVT( 4976 VT.getVectorElementType(), 4977 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4978 } 4979 4980 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4981 switch (ISDOpcode) { 4982 default: 4983 llvm_unreachable("Unhandled reduction"); 4984 case ISD::VECREDUCE_ADD: 4985 return RISCVISD::VECREDUCE_ADD_VL; 4986 case ISD::VECREDUCE_UMAX: 4987 return RISCVISD::VECREDUCE_UMAX_VL; 4988 case ISD::VECREDUCE_SMAX: 4989 return RISCVISD::VECREDUCE_SMAX_VL; 4990 case ISD::VECREDUCE_UMIN: 4991 return RISCVISD::VECREDUCE_UMIN_VL; 4992 case ISD::VECREDUCE_SMIN: 4993 return RISCVISD::VECREDUCE_SMIN_VL; 4994 case ISD::VECREDUCE_AND: 4995 return RISCVISD::VECREDUCE_AND_VL; 4996 case ISD::VECREDUCE_OR: 4997 return RISCVISD::VECREDUCE_OR_VL; 4998 case ISD::VECREDUCE_XOR: 4999 return RISCVISD::VECREDUCE_XOR_VL; 5000 } 5001 } 5002 5003 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5004 SelectionDAG &DAG, 5005 bool IsVP) const { 5006 SDLoc DL(Op); 5007 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5008 MVT VecVT = Vec.getSimpleValueType(); 5009 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5010 Op.getOpcode() == ISD::VECREDUCE_OR || 5011 Op.getOpcode() == ISD::VECREDUCE_XOR || 5012 Op.getOpcode() == ISD::VP_REDUCE_AND || 5013 Op.getOpcode() == ISD::VP_REDUCE_OR || 5014 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5015 "Unexpected reduction lowering"); 5016 5017 MVT XLenVT = Subtarget.getXLenVT(); 5018 assert(Op.getValueType() == XLenVT && 5019 "Expected reduction output to be legalized to XLenVT"); 5020 5021 MVT ContainerVT = VecVT; 5022 if (VecVT.isFixedLengthVector()) { 5023 ContainerVT = getContainerForFixedLengthVector(VecVT); 5024 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5025 } 5026 5027 SDValue Mask, VL; 5028 if (IsVP) { 5029 Mask = Op.getOperand(2); 5030 VL = Op.getOperand(3); 5031 } else { 5032 std::tie(Mask, VL) = 5033 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5034 } 5035 5036 unsigned BaseOpc; 5037 ISD::CondCode CC; 5038 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5039 5040 switch (Op.getOpcode()) { 5041 default: 5042 llvm_unreachable("Unhandled reduction"); 5043 case ISD::VECREDUCE_AND: 5044 case ISD::VP_REDUCE_AND: { 5045 // vcpop ~x == 0 5046 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5047 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5048 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5049 CC = ISD::SETEQ; 5050 BaseOpc = ISD::AND; 5051 break; 5052 } 5053 case ISD::VECREDUCE_OR: 5054 case ISD::VP_REDUCE_OR: 5055 // vcpop x != 0 5056 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5057 CC = ISD::SETNE; 5058 BaseOpc = ISD::OR; 5059 break; 5060 case ISD::VECREDUCE_XOR: 5061 case ISD::VP_REDUCE_XOR: { 5062 // ((vcpop x) & 1) != 0 5063 SDValue One = DAG.getConstant(1, DL, XLenVT); 5064 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5065 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5066 CC = ISD::SETNE; 5067 BaseOpc = ISD::XOR; 5068 break; 5069 } 5070 } 5071 5072 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5073 5074 if (!IsVP) 5075 return SetCC; 5076 5077 // Now include the start value in the operation. 5078 // Note that we must return the start value when no elements are operated 5079 // upon. The vcpop instructions we've emitted in each case above will return 5080 // 0 for an inactive vector, and so we've already received the neutral value: 5081 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5082 // can simply include the start value. 5083 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5084 } 5085 5086 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5087 SelectionDAG &DAG) const { 5088 SDLoc DL(Op); 5089 SDValue Vec = Op.getOperand(0); 5090 EVT VecEVT = Vec.getValueType(); 5091 5092 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5093 5094 // Due to ordering in legalize types we may have a vector type that needs to 5095 // be split. Do that manually so we can get down to a legal type. 5096 while (getTypeAction(*DAG.getContext(), VecEVT) == 5097 TargetLowering::TypeSplitVector) { 5098 SDValue Lo, Hi; 5099 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5100 VecEVT = Lo.getValueType(); 5101 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5102 } 5103 5104 // TODO: The type may need to be widened rather than split. Or widened before 5105 // it can be split. 5106 if (!isTypeLegal(VecEVT)) 5107 return SDValue(); 5108 5109 MVT VecVT = VecEVT.getSimpleVT(); 5110 MVT VecEltVT = VecVT.getVectorElementType(); 5111 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5112 5113 MVT ContainerVT = VecVT; 5114 if (VecVT.isFixedLengthVector()) { 5115 ContainerVT = getContainerForFixedLengthVector(VecVT); 5116 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5117 } 5118 5119 MVT M1VT = getLMUL1VT(ContainerVT); 5120 MVT XLenVT = Subtarget.getXLenVT(); 5121 5122 SDValue Mask, VL; 5123 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5124 5125 SDValue NeutralElem = 5126 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5127 SDValue IdentitySplat = 5128 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5129 M1VT, DL, DAG, Subtarget); 5130 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5131 IdentitySplat, Mask, VL); 5132 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5133 DAG.getConstant(0, DL, XLenVT)); 5134 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5135 } 5136 5137 // Given a reduction op, this function returns the matching reduction opcode, 5138 // the vector SDValue and the scalar SDValue required to lower this to a 5139 // RISCVISD node. 5140 static std::tuple<unsigned, SDValue, SDValue> 5141 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5142 SDLoc DL(Op); 5143 auto Flags = Op->getFlags(); 5144 unsigned Opcode = Op.getOpcode(); 5145 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5146 switch (Opcode) { 5147 default: 5148 llvm_unreachable("Unhandled reduction"); 5149 case ISD::VECREDUCE_FADD: { 5150 // Use positive zero if we can. It is cheaper to materialize. 5151 SDValue Zero = 5152 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5153 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5154 } 5155 case ISD::VECREDUCE_SEQ_FADD: 5156 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5157 Op.getOperand(0)); 5158 case ISD::VECREDUCE_FMIN: 5159 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5160 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5161 case ISD::VECREDUCE_FMAX: 5162 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5163 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5164 } 5165 } 5166 5167 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5168 SelectionDAG &DAG) const { 5169 SDLoc DL(Op); 5170 MVT VecEltVT = Op.getSimpleValueType(); 5171 5172 unsigned RVVOpcode; 5173 SDValue VectorVal, ScalarVal; 5174 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5175 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5176 MVT VecVT = VectorVal.getSimpleValueType(); 5177 5178 MVT ContainerVT = VecVT; 5179 if (VecVT.isFixedLengthVector()) { 5180 ContainerVT = getContainerForFixedLengthVector(VecVT); 5181 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5182 } 5183 5184 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5185 MVT XLenVT = Subtarget.getXLenVT(); 5186 5187 SDValue Mask, VL; 5188 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5189 5190 SDValue ScalarSplat = 5191 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5192 M1VT, DL, DAG, Subtarget); 5193 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5194 VectorVal, ScalarSplat, Mask, VL); 5195 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5196 DAG.getConstant(0, DL, XLenVT)); 5197 } 5198 5199 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5200 switch (ISDOpcode) { 5201 default: 5202 llvm_unreachable("Unhandled reduction"); 5203 case ISD::VP_REDUCE_ADD: 5204 return RISCVISD::VECREDUCE_ADD_VL; 5205 case ISD::VP_REDUCE_UMAX: 5206 return RISCVISD::VECREDUCE_UMAX_VL; 5207 case ISD::VP_REDUCE_SMAX: 5208 return RISCVISD::VECREDUCE_SMAX_VL; 5209 case ISD::VP_REDUCE_UMIN: 5210 return RISCVISD::VECREDUCE_UMIN_VL; 5211 case ISD::VP_REDUCE_SMIN: 5212 return RISCVISD::VECREDUCE_SMIN_VL; 5213 case ISD::VP_REDUCE_AND: 5214 return RISCVISD::VECREDUCE_AND_VL; 5215 case ISD::VP_REDUCE_OR: 5216 return RISCVISD::VECREDUCE_OR_VL; 5217 case ISD::VP_REDUCE_XOR: 5218 return RISCVISD::VECREDUCE_XOR_VL; 5219 case ISD::VP_REDUCE_FADD: 5220 return RISCVISD::VECREDUCE_FADD_VL; 5221 case ISD::VP_REDUCE_SEQ_FADD: 5222 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5223 case ISD::VP_REDUCE_FMAX: 5224 return RISCVISD::VECREDUCE_FMAX_VL; 5225 case ISD::VP_REDUCE_FMIN: 5226 return RISCVISD::VECREDUCE_FMIN_VL; 5227 } 5228 } 5229 5230 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5231 SelectionDAG &DAG) const { 5232 SDLoc DL(Op); 5233 SDValue Vec = Op.getOperand(1); 5234 EVT VecEVT = Vec.getValueType(); 5235 5236 // TODO: The type may need to be widened rather than split. Or widened before 5237 // it can be split. 5238 if (!isTypeLegal(VecEVT)) 5239 return SDValue(); 5240 5241 MVT VecVT = VecEVT.getSimpleVT(); 5242 MVT VecEltVT = VecVT.getVectorElementType(); 5243 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5244 5245 MVT ContainerVT = VecVT; 5246 if (VecVT.isFixedLengthVector()) { 5247 ContainerVT = getContainerForFixedLengthVector(VecVT); 5248 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5249 } 5250 5251 SDValue VL = Op.getOperand(3); 5252 SDValue Mask = Op.getOperand(2); 5253 5254 MVT M1VT = getLMUL1VT(ContainerVT); 5255 MVT XLenVT = Subtarget.getXLenVT(); 5256 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5257 5258 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5259 DAG.getConstant(1, DL, XLenVT), M1VT, 5260 DL, DAG, Subtarget); 5261 SDValue Reduction = 5262 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5263 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5264 DAG.getConstant(0, DL, XLenVT)); 5265 if (!VecVT.isInteger()) 5266 return Elt0; 5267 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5268 } 5269 5270 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5271 SelectionDAG &DAG) const { 5272 SDValue Vec = Op.getOperand(0); 5273 SDValue SubVec = Op.getOperand(1); 5274 MVT VecVT = Vec.getSimpleValueType(); 5275 MVT SubVecVT = SubVec.getSimpleValueType(); 5276 5277 SDLoc DL(Op); 5278 MVT XLenVT = Subtarget.getXLenVT(); 5279 unsigned OrigIdx = Op.getConstantOperandVal(2); 5280 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5281 5282 // We don't have the ability to slide mask vectors up indexed by their i1 5283 // elements; the smallest we can do is i8. Often we are able to bitcast to 5284 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5285 // into a scalable one, we might not necessarily have enough scalable 5286 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5287 if (SubVecVT.getVectorElementType() == MVT::i1 && 5288 (OrigIdx != 0 || !Vec.isUndef())) { 5289 if (VecVT.getVectorMinNumElements() >= 8 && 5290 SubVecVT.getVectorMinNumElements() >= 8) { 5291 assert(OrigIdx % 8 == 0 && "Invalid index"); 5292 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5293 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5294 "Unexpected mask vector lowering"); 5295 OrigIdx /= 8; 5296 SubVecVT = 5297 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5298 SubVecVT.isScalableVector()); 5299 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5300 VecVT.isScalableVector()); 5301 Vec = DAG.getBitcast(VecVT, Vec); 5302 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5303 } else { 5304 // We can't slide this mask vector up indexed by its i1 elements. 5305 // This poses a problem when we wish to insert a scalable vector which 5306 // can't be re-expressed as a larger type. Just choose the slow path and 5307 // extend to a larger type, then truncate back down. 5308 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5309 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5310 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5311 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5312 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5313 Op.getOperand(2)); 5314 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5315 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5316 } 5317 } 5318 5319 // If the subvector vector is a fixed-length type, we cannot use subregister 5320 // manipulation to simplify the codegen; we don't know which register of a 5321 // LMUL group contains the specific subvector as we only know the minimum 5322 // register size. Therefore we must slide the vector group up the full 5323 // amount. 5324 if (SubVecVT.isFixedLengthVector()) { 5325 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5326 return Op; 5327 MVT ContainerVT = VecVT; 5328 if (VecVT.isFixedLengthVector()) { 5329 ContainerVT = getContainerForFixedLengthVector(VecVT); 5330 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5331 } 5332 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5333 DAG.getUNDEF(ContainerVT), SubVec, 5334 DAG.getConstant(0, DL, XLenVT)); 5335 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5336 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5337 return DAG.getBitcast(Op.getValueType(), SubVec); 5338 } 5339 SDValue Mask = 5340 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5341 // Set the vector length to only the number of elements we care about. Note 5342 // that for slideup this includes the offset. 5343 SDValue VL = 5344 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5345 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5346 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5347 SubVec, SlideupAmt, Mask, VL); 5348 if (VecVT.isFixedLengthVector()) 5349 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5350 return DAG.getBitcast(Op.getValueType(), Slideup); 5351 } 5352 5353 unsigned SubRegIdx, RemIdx; 5354 std::tie(SubRegIdx, RemIdx) = 5355 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5356 VecVT, SubVecVT, OrigIdx, TRI); 5357 5358 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5359 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5360 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5361 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5362 5363 // 1. If the Idx has been completely eliminated and this subvector's size is 5364 // a vector register or a multiple thereof, or the surrounding elements are 5365 // undef, then this is a subvector insert which naturally aligns to a vector 5366 // register. These can easily be handled using subregister manipulation. 5367 // 2. If the subvector is smaller than a vector register, then the insertion 5368 // must preserve the undisturbed elements of the register. We do this by 5369 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5370 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5371 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5372 // LMUL=1 type back into the larger vector (resolving to another subregister 5373 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5374 // to avoid allocating a large register group to hold our subvector. 5375 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5376 return Op; 5377 5378 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5379 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5380 // (in our case undisturbed). This means we can set up a subvector insertion 5381 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5382 // size of the subvector. 5383 MVT InterSubVT = VecVT; 5384 SDValue AlignedExtract = Vec; 5385 unsigned AlignedIdx = OrigIdx - RemIdx; 5386 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5387 InterSubVT = getLMUL1VT(VecVT); 5388 // Extract a subvector equal to the nearest full vector register type. This 5389 // should resolve to a EXTRACT_SUBREG instruction. 5390 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5391 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5392 } 5393 5394 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5395 // For scalable vectors this must be further multiplied by vscale. 5396 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5397 5398 SDValue Mask, VL; 5399 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5400 5401 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5402 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5403 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5404 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5405 5406 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5407 DAG.getUNDEF(InterSubVT), SubVec, 5408 DAG.getConstant(0, DL, XLenVT)); 5409 5410 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5411 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5412 5413 // If required, insert this subvector back into the correct vector register. 5414 // This should resolve to an INSERT_SUBREG instruction. 5415 if (VecVT.bitsGT(InterSubVT)) 5416 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5417 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5418 5419 // We might have bitcast from a mask type: cast back to the original type if 5420 // required. 5421 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5422 } 5423 5424 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5425 SelectionDAG &DAG) const { 5426 SDValue Vec = Op.getOperand(0); 5427 MVT SubVecVT = Op.getSimpleValueType(); 5428 MVT VecVT = Vec.getSimpleValueType(); 5429 5430 SDLoc DL(Op); 5431 MVT XLenVT = Subtarget.getXLenVT(); 5432 unsigned OrigIdx = Op.getConstantOperandVal(1); 5433 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5434 5435 // We don't have the ability to slide mask vectors down indexed by their i1 5436 // elements; the smallest we can do is i8. Often we are able to bitcast to 5437 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5438 // from a scalable one, we might not necessarily have enough scalable 5439 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5440 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5441 if (VecVT.getVectorMinNumElements() >= 8 && 5442 SubVecVT.getVectorMinNumElements() >= 8) { 5443 assert(OrigIdx % 8 == 0 && "Invalid index"); 5444 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5445 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5446 "Unexpected mask vector lowering"); 5447 OrigIdx /= 8; 5448 SubVecVT = 5449 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5450 SubVecVT.isScalableVector()); 5451 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5452 VecVT.isScalableVector()); 5453 Vec = DAG.getBitcast(VecVT, Vec); 5454 } else { 5455 // We can't slide this mask vector down, indexed by its i1 elements. 5456 // This poses a problem when we wish to extract a scalable vector which 5457 // can't be re-expressed as a larger type. Just choose the slow path and 5458 // extend to a larger type, then truncate back down. 5459 // TODO: We could probably improve this when extracting certain fixed 5460 // from fixed, where we can extract as i8 and shift the correct element 5461 // right to reach the desired subvector? 5462 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5463 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5464 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5465 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5466 Op.getOperand(1)); 5467 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5468 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5469 } 5470 } 5471 5472 // If the subvector vector is a fixed-length type, we cannot use subregister 5473 // manipulation to simplify the codegen; we don't know which register of a 5474 // LMUL group contains the specific subvector as we only know the minimum 5475 // register size. Therefore we must slide the vector group down the full 5476 // amount. 5477 if (SubVecVT.isFixedLengthVector()) { 5478 // With an index of 0 this is a cast-like subvector, which can be performed 5479 // with subregister operations. 5480 if (OrigIdx == 0) 5481 return Op; 5482 MVT ContainerVT = VecVT; 5483 if (VecVT.isFixedLengthVector()) { 5484 ContainerVT = getContainerForFixedLengthVector(VecVT); 5485 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5486 } 5487 SDValue Mask = 5488 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5489 // Set the vector length to only the number of elements we care about. This 5490 // avoids sliding down elements we're going to discard straight away. 5491 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5492 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5493 SDValue Slidedown = 5494 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5495 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5496 // Now we can use a cast-like subvector extract to get the result. 5497 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5498 DAG.getConstant(0, DL, XLenVT)); 5499 return DAG.getBitcast(Op.getValueType(), Slidedown); 5500 } 5501 5502 unsigned SubRegIdx, RemIdx; 5503 std::tie(SubRegIdx, RemIdx) = 5504 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5505 VecVT, SubVecVT, OrigIdx, TRI); 5506 5507 // If the Idx has been completely eliminated then this is a subvector extract 5508 // which naturally aligns to a vector register. These can easily be handled 5509 // using subregister manipulation. 5510 if (RemIdx == 0) 5511 return Op; 5512 5513 // Else we must shift our vector register directly to extract the subvector. 5514 // Do this using VSLIDEDOWN. 5515 5516 // If the vector type is an LMUL-group type, extract a subvector equal to the 5517 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5518 // instruction. 5519 MVT InterSubVT = VecVT; 5520 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5521 InterSubVT = getLMUL1VT(VecVT); 5522 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5523 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5524 } 5525 5526 // Slide this vector register down by the desired number of elements in order 5527 // to place the desired subvector starting at element 0. 5528 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5529 // For scalable vectors this must be further multiplied by vscale. 5530 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5531 5532 SDValue Mask, VL; 5533 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5534 SDValue Slidedown = 5535 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5536 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5537 5538 // Now the vector is in the right position, extract our final subvector. This 5539 // should resolve to a COPY. 5540 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5541 DAG.getConstant(0, DL, XLenVT)); 5542 5543 // We might have bitcast from a mask type: cast back to the original type if 5544 // required. 5545 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5546 } 5547 5548 // Lower step_vector to the vid instruction. Any non-identity step value must 5549 // be accounted for my manual expansion. 5550 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5551 SelectionDAG &DAG) const { 5552 SDLoc DL(Op); 5553 MVT VT = Op.getSimpleValueType(); 5554 MVT XLenVT = Subtarget.getXLenVT(); 5555 SDValue Mask, VL; 5556 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5557 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5558 uint64_t StepValImm = Op.getConstantOperandVal(0); 5559 if (StepValImm != 1) { 5560 if (isPowerOf2_64(StepValImm)) { 5561 SDValue StepVal = 5562 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5563 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5564 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5565 } else { 5566 SDValue StepVal = lowerScalarSplat( 5567 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5568 VL, VT, DL, DAG, Subtarget); 5569 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5570 } 5571 } 5572 return StepVec; 5573 } 5574 5575 // Implement vector_reverse using vrgather.vv with indices determined by 5576 // subtracting the id of each element from (VLMAX-1). This will convert 5577 // the indices like so: 5578 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5579 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5580 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5581 SelectionDAG &DAG) const { 5582 SDLoc DL(Op); 5583 MVT VecVT = Op.getSimpleValueType(); 5584 unsigned EltSize = VecVT.getScalarSizeInBits(); 5585 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5586 5587 unsigned MaxVLMAX = 0; 5588 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5589 if (VectorBitsMax != 0) 5590 MaxVLMAX = 5591 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5592 5593 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5594 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5595 5596 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5597 // to use vrgatherei16.vv. 5598 // TODO: It's also possible to use vrgatherei16.vv for other types to 5599 // decrease register width for the index calculation. 5600 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5601 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5602 // Reverse each half, then reassemble them in reverse order. 5603 // NOTE: It's also possible that after splitting that VLMAX no longer 5604 // requires vrgatherei16.vv. 5605 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5606 SDValue Lo, Hi; 5607 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5608 EVT LoVT, HiVT; 5609 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5610 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5611 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5612 // Reassemble the low and high pieces reversed. 5613 // FIXME: This is a CONCAT_VECTORS. 5614 SDValue Res = 5615 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5616 DAG.getIntPtrConstant(0, DL)); 5617 return DAG.getNode( 5618 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5619 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5620 } 5621 5622 // Just promote the int type to i16 which will double the LMUL. 5623 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5624 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5625 } 5626 5627 MVT XLenVT = Subtarget.getXLenVT(); 5628 SDValue Mask, VL; 5629 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5630 5631 // Calculate VLMAX-1 for the desired SEW. 5632 unsigned MinElts = VecVT.getVectorMinNumElements(); 5633 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5634 DAG.getConstant(MinElts, DL, XLenVT)); 5635 SDValue VLMinus1 = 5636 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5637 5638 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5639 bool IsRV32E64 = 5640 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5641 SDValue SplatVL; 5642 if (!IsRV32E64) 5643 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5644 else 5645 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5646 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5647 5648 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5649 SDValue Indices = 5650 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5651 5652 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5653 } 5654 5655 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5656 SelectionDAG &DAG) const { 5657 SDLoc DL(Op); 5658 SDValue V1 = Op.getOperand(0); 5659 SDValue V2 = Op.getOperand(1); 5660 MVT XLenVT = Subtarget.getXLenVT(); 5661 MVT VecVT = Op.getSimpleValueType(); 5662 5663 unsigned MinElts = VecVT.getVectorMinNumElements(); 5664 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5665 DAG.getConstant(MinElts, DL, XLenVT)); 5666 5667 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5668 SDValue DownOffset, UpOffset; 5669 if (ImmValue >= 0) { 5670 // The operand is a TargetConstant, we need to rebuild it as a regular 5671 // constant. 5672 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5673 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5674 } else { 5675 // The operand is a TargetConstant, we need to rebuild it as a regular 5676 // constant rather than negating the original operand. 5677 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5678 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5679 } 5680 5681 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5682 5683 SDValue SlideDown = 5684 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5685 DownOffset, TrueMask, UpOffset); 5686 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5687 TrueMask, 5688 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5689 } 5690 5691 SDValue 5692 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5693 SelectionDAG &DAG) const { 5694 SDLoc DL(Op); 5695 auto *Load = cast<LoadSDNode>(Op); 5696 5697 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5698 Load->getMemoryVT(), 5699 *Load->getMemOperand()) && 5700 "Expecting a correctly-aligned load"); 5701 5702 MVT VT = Op.getSimpleValueType(); 5703 MVT XLenVT = Subtarget.getXLenVT(); 5704 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5705 5706 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5707 5708 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5709 SDValue IntID = DAG.getTargetConstant( 5710 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5711 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5712 if (!IsMaskOp) 5713 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5714 Ops.push_back(Load->getBasePtr()); 5715 Ops.push_back(VL); 5716 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5717 SDValue NewLoad = 5718 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5719 Load->getMemoryVT(), Load->getMemOperand()); 5720 5721 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5722 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5723 } 5724 5725 SDValue 5726 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5727 SelectionDAG &DAG) const { 5728 SDLoc DL(Op); 5729 auto *Store = cast<StoreSDNode>(Op); 5730 5731 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5732 Store->getMemoryVT(), 5733 *Store->getMemOperand()) && 5734 "Expecting a correctly-aligned store"); 5735 5736 SDValue StoreVal = Store->getValue(); 5737 MVT VT = StoreVal.getSimpleValueType(); 5738 MVT XLenVT = Subtarget.getXLenVT(); 5739 5740 // If the size less than a byte, we need to pad with zeros to make a byte. 5741 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5742 VT = MVT::v8i1; 5743 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5744 DAG.getConstant(0, DL, VT), StoreVal, 5745 DAG.getIntPtrConstant(0, DL)); 5746 } 5747 5748 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5749 5750 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5751 5752 SDValue NewValue = 5753 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5754 5755 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5756 SDValue IntID = DAG.getTargetConstant( 5757 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5758 return DAG.getMemIntrinsicNode( 5759 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5760 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5761 Store->getMemoryVT(), Store->getMemOperand()); 5762 } 5763 5764 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5765 SelectionDAG &DAG) const { 5766 SDLoc DL(Op); 5767 MVT VT = Op.getSimpleValueType(); 5768 5769 const auto *MemSD = cast<MemSDNode>(Op); 5770 EVT MemVT = MemSD->getMemoryVT(); 5771 MachineMemOperand *MMO = MemSD->getMemOperand(); 5772 SDValue Chain = MemSD->getChain(); 5773 SDValue BasePtr = MemSD->getBasePtr(); 5774 5775 SDValue Mask, PassThru, VL; 5776 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5777 Mask = VPLoad->getMask(); 5778 PassThru = DAG.getUNDEF(VT); 5779 VL = VPLoad->getVectorLength(); 5780 } else { 5781 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5782 Mask = MLoad->getMask(); 5783 PassThru = MLoad->getPassThru(); 5784 } 5785 5786 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5787 5788 MVT XLenVT = Subtarget.getXLenVT(); 5789 5790 MVT ContainerVT = VT; 5791 if (VT.isFixedLengthVector()) { 5792 ContainerVT = getContainerForFixedLengthVector(VT); 5793 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5794 if (!IsUnmasked) { 5795 MVT MaskVT = getMaskTypeFor(ContainerVT); 5796 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5797 } 5798 } 5799 5800 if (!VL) 5801 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5802 5803 unsigned IntID = 5804 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5805 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5806 if (IsUnmasked) 5807 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5808 else 5809 Ops.push_back(PassThru); 5810 Ops.push_back(BasePtr); 5811 if (!IsUnmasked) 5812 Ops.push_back(Mask); 5813 Ops.push_back(VL); 5814 if (!IsUnmasked) 5815 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5816 5817 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5818 5819 SDValue Result = 5820 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5821 Chain = Result.getValue(1); 5822 5823 if (VT.isFixedLengthVector()) 5824 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5825 5826 return DAG.getMergeValues({Result, Chain}, DL); 5827 } 5828 5829 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5830 SelectionDAG &DAG) const { 5831 SDLoc DL(Op); 5832 5833 const auto *MemSD = cast<MemSDNode>(Op); 5834 EVT MemVT = MemSD->getMemoryVT(); 5835 MachineMemOperand *MMO = MemSD->getMemOperand(); 5836 SDValue Chain = MemSD->getChain(); 5837 SDValue BasePtr = MemSD->getBasePtr(); 5838 SDValue Val, Mask, VL; 5839 5840 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5841 Val = VPStore->getValue(); 5842 Mask = VPStore->getMask(); 5843 VL = VPStore->getVectorLength(); 5844 } else { 5845 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5846 Val = MStore->getValue(); 5847 Mask = MStore->getMask(); 5848 } 5849 5850 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5851 5852 MVT VT = Val.getSimpleValueType(); 5853 MVT XLenVT = Subtarget.getXLenVT(); 5854 5855 MVT ContainerVT = VT; 5856 if (VT.isFixedLengthVector()) { 5857 ContainerVT = getContainerForFixedLengthVector(VT); 5858 5859 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5860 if (!IsUnmasked) { 5861 MVT MaskVT = getMaskTypeFor(ContainerVT); 5862 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5863 } 5864 } 5865 5866 if (!VL) 5867 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5868 5869 unsigned IntID = 5870 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5871 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5872 Ops.push_back(Val); 5873 Ops.push_back(BasePtr); 5874 if (!IsUnmasked) 5875 Ops.push_back(Mask); 5876 Ops.push_back(VL); 5877 5878 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5879 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5880 } 5881 5882 SDValue 5883 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5884 SelectionDAG &DAG) const { 5885 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5886 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5887 5888 MVT VT = Op.getSimpleValueType(); 5889 5890 SDValue Op1 = 5891 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5892 SDValue Op2 = 5893 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5894 5895 SDLoc DL(Op); 5896 SDValue VL = 5897 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5898 5899 MVT MaskVT = getMaskTypeFor(ContainerVT); 5900 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5901 5902 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5903 Op.getOperand(2), Mask, VL); 5904 5905 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5906 } 5907 5908 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5909 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5910 MVT VT = Op.getSimpleValueType(); 5911 5912 if (VT.getVectorElementType() == MVT::i1) 5913 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5914 5915 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5916 } 5917 5918 SDValue 5919 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5920 SelectionDAG &DAG) const { 5921 unsigned Opc; 5922 switch (Op.getOpcode()) { 5923 default: llvm_unreachable("Unexpected opcode!"); 5924 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5925 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5926 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5927 } 5928 5929 return lowerToScalableOp(Op, DAG, Opc); 5930 } 5931 5932 // Lower vector ABS to smax(X, sub(0, X)). 5933 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5934 SDLoc DL(Op); 5935 MVT VT = Op.getSimpleValueType(); 5936 SDValue X = Op.getOperand(0); 5937 5938 assert(VT.isFixedLengthVector() && "Unexpected type"); 5939 5940 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5941 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5942 5943 SDValue Mask, VL; 5944 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5945 5946 SDValue SplatZero = DAG.getNode( 5947 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5948 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5949 SDValue NegX = 5950 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5951 SDValue Max = 5952 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5953 5954 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5955 } 5956 5957 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5958 SDValue Op, SelectionDAG &DAG) const { 5959 SDLoc DL(Op); 5960 MVT VT = Op.getSimpleValueType(); 5961 SDValue Mag = Op.getOperand(0); 5962 SDValue Sign = Op.getOperand(1); 5963 assert(Mag.getValueType() == Sign.getValueType() && 5964 "Can only handle COPYSIGN with matching types."); 5965 5966 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5967 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5968 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5969 5970 SDValue Mask, VL; 5971 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5972 5973 SDValue CopySign = 5974 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5975 5976 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5977 } 5978 5979 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5980 SDValue Op, SelectionDAG &DAG) const { 5981 MVT VT = Op.getSimpleValueType(); 5982 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5983 5984 MVT I1ContainerVT = 5985 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5986 5987 SDValue CC = 5988 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5989 SDValue Op1 = 5990 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5991 SDValue Op2 = 5992 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5993 5994 SDLoc DL(Op); 5995 SDValue Mask, VL; 5996 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5997 5998 SDValue Select = 5999 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6000 6001 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6002 } 6003 6004 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6005 unsigned NewOpc, 6006 bool HasMask) const { 6007 MVT VT = Op.getSimpleValueType(); 6008 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6009 6010 // Create list of operands by converting existing ones to scalable types. 6011 SmallVector<SDValue, 6> Ops; 6012 for (const SDValue &V : Op->op_values()) { 6013 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6014 6015 // Pass through non-vector operands. 6016 if (!V.getValueType().isVector()) { 6017 Ops.push_back(V); 6018 continue; 6019 } 6020 6021 // "cast" fixed length vector to a scalable vector. 6022 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6023 "Only fixed length vectors are supported!"); 6024 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6025 } 6026 6027 SDLoc DL(Op); 6028 SDValue Mask, VL; 6029 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6030 if (HasMask) 6031 Ops.push_back(Mask); 6032 Ops.push_back(VL); 6033 6034 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6035 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6036 } 6037 6038 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6039 // * Operands of each node are assumed to be in the same order. 6040 // * The EVL operand is promoted from i32 to i64 on RV64. 6041 // * Fixed-length vectors are converted to their scalable-vector container 6042 // types. 6043 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6044 unsigned RISCVISDOpc) const { 6045 SDLoc DL(Op); 6046 MVT VT = Op.getSimpleValueType(); 6047 SmallVector<SDValue, 4> Ops; 6048 6049 for (const auto &OpIdx : enumerate(Op->ops())) { 6050 SDValue V = OpIdx.value(); 6051 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6052 // Pass through operands which aren't fixed-length vectors. 6053 if (!V.getValueType().isFixedLengthVector()) { 6054 Ops.push_back(V); 6055 continue; 6056 } 6057 // "cast" fixed length vector to a scalable vector. 6058 MVT OpVT = V.getSimpleValueType(); 6059 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6060 assert(useRVVForFixedLengthVectorVT(OpVT) && 6061 "Only fixed length vectors are supported!"); 6062 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6063 } 6064 6065 if (!VT.isFixedLengthVector()) 6066 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6067 6068 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6069 6070 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6071 6072 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6073 } 6074 6075 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6076 SelectionDAG &DAG) const { 6077 SDLoc DL(Op); 6078 MVT VT = Op.getSimpleValueType(); 6079 6080 SDValue Src = Op.getOperand(0); 6081 // NOTE: Mask is dropped. 6082 SDValue VL = Op.getOperand(2); 6083 6084 MVT ContainerVT = VT; 6085 if (VT.isFixedLengthVector()) { 6086 ContainerVT = getContainerForFixedLengthVector(VT); 6087 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6088 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6089 } 6090 6091 MVT XLenVT = Subtarget.getXLenVT(); 6092 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6093 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6094 DAG.getUNDEF(ContainerVT), Zero, VL); 6095 6096 SDValue SplatValue = DAG.getConstant( 6097 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6098 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6099 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6100 6101 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6102 Splat, ZeroSplat, VL); 6103 if (!VT.isFixedLengthVector()) 6104 return Result; 6105 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6106 } 6107 6108 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6109 SelectionDAG &DAG) const { 6110 SDLoc DL(Op); 6111 MVT VT = Op.getSimpleValueType(); 6112 6113 SDValue Op1 = Op.getOperand(0); 6114 SDValue Op2 = Op.getOperand(1); 6115 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6116 // NOTE: Mask is dropped. 6117 SDValue VL = Op.getOperand(4); 6118 6119 MVT ContainerVT = VT; 6120 if (VT.isFixedLengthVector()) { 6121 ContainerVT = getContainerForFixedLengthVector(VT); 6122 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6123 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6124 } 6125 6126 SDValue Result; 6127 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6128 6129 switch (Condition) { 6130 default: 6131 break; 6132 // X != Y --> (X^Y) 6133 case ISD::SETNE: 6134 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6135 break; 6136 // X == Y --> ~(X^Y) 6137 case ISD::SETEQ: { 6138 SDValue Temp = 6139 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6140 Result = 6141 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6142 break; 6143 } 6144 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6145 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6146 case ISD::SETGT: 6147 case ISD::SETULT: { 6148 SDValue Temp = 6149 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6150 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6151 break; 6152 } 6153 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6154 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6155 case ISD::SETLT: 6156 case ISD::SETUGT: { 6157 SDValue Temp = 6158 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6159 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6160 break; 6161 } 6162 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6163 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6164 case ISD::SETGE: 6165 case ISD::SETULE: { 6166 SDValue Temp = 6167 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6168 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6169 break; 6170 } 6171 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6172 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6173 case ISD::SETLE: 6174 case ISD::SETUGE: { 6175 SDValue Temp = 6176 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6177 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6178 break; 6179 } 6180 } 6181 6182 if (!VT.isFixedLengthVector()) 6183 return Result; 6184 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6185 } 6186 6187 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6188 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6189 unsigned RISCVISDOpc) const { 6190 SDLoc DL(Op); 6191 6192 SDValue Src = Op.getOperand(0); 6193 SDValue Mask = Op.getOperand(1); 6194 SDValue VL = Op.getOperand(2); 6195 6196 MVT DstVT = Op.getSimpleValueType(); 6197 MVT SrcVT = Src.getSimpleValueType(); 6198 if (DstVT.isFixedLengthVector()) { 6199 DstVT = getContainerForFixedLengthVector(DstVT); 6200 SrcVT = getContainerForFixedLengthVector(SrcVT); 6201 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6202 MVT MaskVT = getMaskTypeFor(DstVT); 6203 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6204 } 6205 6206 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6207 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6208 ? RISCVISD::VSEXT_VL 6209 : RISCVISD::VZEXT_VL; 6210 6211 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6212 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6213 6214 SDValue Result; 6215 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6216 if (SrcVT.isInteger()) { 6217 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6218 6219 // Do we need to do any pre-widening before converting? 6220 if (SrcEltSize == 1) { 6221 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6222 MVT XLenVT = Subtarget.getXLenVT(); 6223 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6224 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6225 DAG.getUNDEF(IntVT), Zero, VL); 6226 SDValue One = DAG.getConstant( 6227 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6228 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6229 DAG.getUNDEF(IntVT), One, VL); 6230 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6231 ZeroSplat, VL); 6232 } else if (DstEltSize > (2 * SrcEltSize)) { 6233 // Widen before converting. 6234 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6235 DstVT.getVectorElementCount()); 6236 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6237 } 6238 6239 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6240 } else { 6241 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6242 "Wrong input/output vector types"); 6243 6244 // Convert f16 to f32 then convert f32 to i64. 6245 if (DstEltSize > (2 * SrcEltSize)) { 6246 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6247 MVT InterimFVT = 6248 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6249 Src = 6250 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6251 } 6252 6253 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6254 } 6255 } else { // Narrowing + Conversion 6256 if (SrcVT.isInteger()) { 6257 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6258 // First do a narrowing convert to an FP type half the size, then round 6259 // the FP type to a small FP type if needed. 6260 6261 MVT InterimFVT = DstVT; 6262 if (SrcEltSize > (2 * DstEltSize)) { 6263 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6264 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6265 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6266 } 6267 6268 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6269 6270 if (InterimFVT != DstVT) { 6271 Src = Result; 6272 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6273 } 6274 } else { 6275 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6276 "Wrong input/output vector types"); 6277 // First do a narrowing conversion to an integer half the size, then 6278 // truncate if needed. 6279 6280 if (DstEltSize == 1) { 6281 // First convert to the same size integer, then convert to mask using 6282 // setcc. 6283 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6284 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6285 DstVT.getVectorElementCount()); 6286 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6287 6288 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6289 // otherwise the conversion was undefined. 6290 MVT XLenVT = Subtarget.getXLenVT(); 6291 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6292 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6293 DAG.getUNDEF(InterimIVT), SplatZero); 6294 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6295 DAG.getCondCode(ISD::SETNE), Mask, VL); 6296 } else { 6297 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6298 DstVT.getVectorElementCount()); 6299 6300 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6301 6302 while (InterimIVT != DstVT) { 6303 SrcEltSize /= 2; 6304 Src = Result; 6305 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6306 DstVT.getVectorElementCount()); 6307 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6308 Src, Mask, VL); 6309 } 6310 } 6311 } 6312 } 6313 6314 MVT VT = Op.getSimpleValueType(); 6315 if (!VT.isFixedLengthVector()) 6316 return Result; 6317 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6318 } 6319 6320 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6321 unsigned MaskOpc, 6322 unsigned VecOpc) const { 6323 MVT VT = Op.getSimpleValueType(); 6324 if (VT.getVectorElementType() != MVT::i1) 6325 return lowerVPOp(Op, DAG, VecOpc); 6326 6327 // It is safe to drop mask parameter as masked-off elements are undef. 6328 SDValue Op1 = Op->getOperand(0); 6329 SDValue Op2 = Op->getOperand(1); 6330 SDValue VL = Op->getOperand(3); 6331 6332 MVT ContainerVT = VT; 6333 const bool IsFixed = VT.isFixedLengthVector(); 6334 if (IsFixed) { 6335 ContainerVT = getContainerForFixedLengthVector(VT); 6336 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6337 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6338 } 6339 6340 SDLoc DL(Op); 6341 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6342 if (!IsFixed) 6343 return Val; 6344 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6345 } 6346 6347 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6348 // matched to a RVV indexed load. The RVV indexed load instructions only 6349 // support the "unsigned unscaled" addressing mode; indices are implicitly 6350 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6351 // signed or scaled indexing is extended to the XLEN value type and scaled 6352 // accordingly. 6353 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6354 SelectionDAG &DAG) const { 6355 SDLoc DL(Op); 6356 MVT VT = Op.getSimpleValueType(); 6357 6358 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6359 EVT MemVT = MemSD->getMemoryVT(); 6360 MachineMemOperand *MMO = MemSD->getMemOperand(); 6361 SDValue Chain = MemSD->getChain(); 6362 SDValue BasePtr = MemSD->getBasePtr(); 6363 6364 ISD::LoadExtType LoadExtType; 6365 SDValue Index, Mask, PassThru, VL; 6366 6367 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6368 Index = VPGN->getIndex(); 6369 Mask = VPGN->getMask(); 6370 PassThru = DAG.getUNDEF(VT); 6371 VL = VPGN->getVectorLength(); 6372 // VP doesn't support extending loads. 6373 LoadExtType = ISD::NON_EXTLOAD; 6374 } else { 6375 // Else it must be a MGATHER. 6376 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6377 Index = MGN->getIndex(); 6378 Mask = MGN->getMask(); 6379 PassThru = MGN->getPassThru(); 6380 LoadExtType = MGN->getExtensionType(); 6381 } 6382 6383 MVT IndexVT = Index.getSimpleValueType(); 6384 MVT XLenVT = Subtarget.getXLenVT(); 6385 6386 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6387 "Unexpected VTs!"); 6388 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6389 // Targets have to explicitly opt-in for extending vector loads. 6390 assert(LoadExtType == ISD::NON_EXTLOAD && 6391 "Unexpected extending MGATHER/VP_GATHER"); 6392 (void)LoadExtType; 6393 6394 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6395 // the selection of the masked intrinsics doesn't do this for us. 6396 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6397 6398 MVT ContainerVT = VT; 6399 if (VT.isFixedLengthVector()) { 6400 // We need to use the larger of the result and index type to determine the 6401 // scalable type to use so we don't increase LMUL for any operand/result. 6402 if (VT.bitsGE(IndexVT)) { 6403 ContainerVT = getContainerForFixedLengthVector(VT); 6404 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6405 ContainerVT.getVectorElementCount()); 6406 } else { 6407 IndexVT = getContainerForFixedLengthVector(IndexVT); 6408 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6409 IndexVT.getVectorElementCount()); 6410 } 6411 6412 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6413 6414 if (!IsUnmasked) { 6415 MVT MaskVT = getMaskTypeFor(ContainerVT); 6416 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6417 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6418 } 6419 } 6420 6421 if (!VL) 6422 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6423 6424 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6425 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6426 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6427 VL); 6428 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6429 TrueMask, VL); 6430 } 6431 6432 unsigned IntID = 6433 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6434 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6435 if (IsUnmasked) 6436 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6437 else 6438 Ops.push_back(PassThru); 6439 Ops.push_back(BasePtr); 6440 Ops.push_back(Index); 6441 if (!IsUnmasked) 6442 Ops.push_back(Mask); 6443 Ops.push_back(VL); 6444 if (!IsUnmasked) 6445 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6446 6447 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6448 SDValue Result = 6449 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6450 Chain = Result.getValue(1); 6451 6452 if (VT.isFixedLengthVector()) 6453 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6454 6455 return DAG.getMergeValues({Result, Chain}, DL); 6456 } 6457 6458 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6459 // matched to a RVV indexed store. The RVV indexed store instructions only 6460 // support the "unsigned unscaled" addressing mode; indices are implicitly 6461 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6462 // signed or scaled indexing is extended to the XLEN value type and scaled 6463 // accordingly. 6464 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6465 SelectionDAG &DAG) const { 6466 SDLoc DL(Op); 6467 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6468 EVT MemVT = MemSD->getMemoryVT(); 6469 MachineMemOperand *MMO = MemSD->getMemOperand(); 6470 SDValue Chain = MemSD->getChain(); 6471 SDValue BasePtr = MemSD->getBasePtr(); 6472 6473 bool IsTruncatingStore = false; 6474 SDValue Index, Mask, Val, VL; 6475 6476 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6477 Index = VPSN->getIndex(); 6478 Mask = VPSN->getMask(); 6479 Val = VPSN->getValue(); 6480 VL = VPSN->getVectorLength(); 6481 // VP doesn't support truncating stores. 6482 IsTruncatingStore = false; 6483 } else { 6484 // Else it must be a MSCATTER. 6485 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6486 Index = MSN->getIndex(); 6487 Mask = MSN->getMask(); 6488 Val = MSN->getValue(); 6489 IsTruncatingStore = MSN->isTruncatingStore(); 6490 } 6491 6492 MVT VT = Val.getSimpleValueType(); 6493 MVT IndexVT = Index.getSimpleValueType(); 6494 MVT XLenVT = Subtarget.getXLenVT(); 6495 6496 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6497 "Unexpected VTs!"); 6498 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6499 // Targets have to explicitly opt-in for extending vector loads and 6500 // truncating vector stores. 6501 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6502 (void)IsTruncatingStore; 6503 6504 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6505 // the selection of the masked intrinsics doesn't do this for us. 6506 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6507 6508 MVT ContainerVT = VT; 6509 if (VT.isFixedLengthVector()) { 6510 // We need to use the larger of the value and index type to determine the 6511 // scalable type to use so we don't increase LMUL for any operand/result. 6512 if (VT.bitsGE(IndexVT)) { 6513 ContainerVT = getContainerForFixedLengthVector(VT); 6514 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6515 ContainerVT.getVectorElementCount()); 6516 } else { 6517 IndexVT = getContainerForFixedLengthVector(IndexVT); 6518 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6519 IndexVT.getVectorElementCount()); 6520 } 6521 6522 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6523 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6524 6525 if (!IsUnmasked) { 6526 MVT MaskVT = getMaskTypeFor(ContainerVT); 6527 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6528 } 6529 } 6530 6531 if (!VL) 6532 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6533 6534 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6535 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6536 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6537 VL); 6538 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6539 TrueMask, VL); 6540 } 6541 6542 unsigned IntID = 6543 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6544 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6545 Ops.push_back(Val); 6546 Ops.push_back(BasePtr); 6547 Ops.push_back(Index); 6548 if (!IsUnmasked) 6549 Ops.push_back(Mask); 6550 Ops.push_back(VL); 6551 6552 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6553 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6554 } 6555 6556 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6557 SelectionDAG &DAG) const { 6558 const MVT XLenVT = Subtarget.getXLenVT(); 6559 SDLoc DL(Op); 6560 SDValue Chain = Op->getOperand(0); 6561 SDValue SysRegNo = DAG.getTargetConstant( 6562 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6563 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6564 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6565 6566 // Encoding used for rounding mode in RISCV differs from that used in 6567 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6568 // table, which consists of a sequence of 4-bit fields, each representing 6569 // corresponding FLT_ROUNDS mode. 6570 static const int Table = 6571 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6572 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6573 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6574 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6575 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6576 6577 SDValue Shift = 6578 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6579 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6580 DAG.getConstant(Table, DL, XLenVT), Shift); 6581 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6582 DAG.getConstant(7, DL, XLenVT)); 6583 6584 return DAG.getMergeValues({Masked, Chain}, DL); 6585 } 6586 6587 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6588 SelectionDAG &DAG) const { 6589 const MVT XLenVT = Subtarget.getXLenVT(); 6590 SDLoc DL(Op); 6591 SDValue Chain = Op->getOperand(0); 6592 SDValue RMValue = Op->getOperand(1); 6593 SDValue SysRegNo = DAG.getTargetConstant( 6594 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6595 6596 // Encoding used for rounding mode in RISCV differs from that used in 6597 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6598 // a table, which consists of a sequence of 4-bit fields, each representing 6599 // corresponding RISCV mode. 6600 static const unsigned Table = 6601 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6602 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6603 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6604 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6605 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6606 6607 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6608 DAG.getConstant(2, DL, XLenVT)); 6609 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6610 DAG.getConstant(Table, DL, XLenVT), Shift); 6611 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6612 DAG.getConstant(0x7, DL, XLenVT)); 6613 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6614 RMValue); 6615 } 6616 6617 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6618 switch (IntNo) { 6619 default: 6620 llvm_unreachable("Unexpected Intrinsic"); 6621 case Intrinsic::riscv_bcompress: 6622 return RISCVISD::BCOMPRESSW; 6623 case Intrinsic::riscv_bdecompress: 6624 return RISCVISD::BDECOMPRESSW; 6625 case Intrinsic::riscv_bfp: 6626 return RISCVISD::BFPW; 6627 case Intrinsic::riscv_fsl: 6628 return RISCVISD::FSLW; 6629 case Intrinsic::riscv_fsr: 6630 return RISCVISD::FSRW; 6631 } 6632 } 6633 6634 // Converts the given intrinsic to a i64 operation with any extension. 6635 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6636 unsigned IntNo) { 6637 SDLoc DL(N); 6638 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6639 // Deal with the Instruction Operands 6640 SmallVector<SDValue, 3> NewOps; 6641 for (SDValue Op : drop_begin(N->ops())) 6642 // Promote the operand to i64 type 6643 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6644 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6645 // ReplaceNodeResults requires we maintain the same type for the return value. 6646 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6647 } 6648 6649 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6650 // form of the given Opcode. 6651 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6652 switch (Opcode) { 6653 default: 6654 llvm_unreachable("Unexpected opcode"); 6655 case ISD::SHL: 6656 return RISCVISD::SLLW; 6657 case ISD::SRA: 6658 return RISCVISD::SRAW; 6659 case ISD::SRL: 6660 return RISCVISD::SRLW; 6661 case ISD::SDIV: 6662 return RISCVISD::DIVW; 6663 case ISD::UDIV: 6664 return RISCVISD::DIVUW; 6665 case ISD::UREM: 6666 return RISCVISD::REMUW; 6667 case ISD::ROTL: 6668 return RISCVISD::ROLW; 6669 case ISD::ROTR: 6670 return RISCVISD::RORW; 6671 } 6672 } 6673 6674 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6675 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6676 // otherwise be promoted to i64, making it difficult to select the 6677 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6678 // type i8/i16/i32 is lost. 6679 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6680 unsigned ExtOpc = ISD::ANY_EXTEND) { 6681 SDLoc DL(N); 6682 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6683 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6684 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6685 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6686 // ReplaceNodeResults requires we maintain the same type for the return value. 6687 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6688 } 6689 6690 // Converts the given 32-bit operation to a i64 operation with signed extension 6691 // semantic to reduce the signed extension instructions. 6692 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6693 SDLoc DL(N); 6694 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6695 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6696 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6697 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6698 DAG.getValueType(MVT::i32)); 6699 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6700 } 6701 6702 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6703 SmallVectorImpl<SDValue> &Results, 6704 SelectionDAG &DAG) const { 6705 SDLoc DL(N); 6706 switch (N->getOpcode()) { 6707 default: 6708 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6709 case ISD::STRICT_FP_TO_SINT: 6710 case ISD::STRICT_FP_TO_UINT: 6711 case ISD::FP_TO_SINT: 6712 case ISD::FP_TO_UINT: { 6713 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6714 "Unexpected custom legalisation"); 6715 bool IsStrict = N->isStrictFPOpcode(); 6716 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6717 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6718 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6719 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6720 TargetLowering::TypeSoftenFloat) { 6721 if (!isTypeLegal(Op0.getValueType())) 6722 return; 6723 if (IsStrict) { 6724 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6725 : RISCVISD::STRICT_FCVT_WU_RV64; 6726 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6727 SDValue Res = DAG.getNode( 6728 Opc, DL, VTs, N->getOperand(0), Op0, 6729 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6730 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6731 Results.push_back(Res.getValue(1)); 6732 return; 6733 } 6734 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6735 SDValue Res = 6736 DAG.getNode(Opc, DL, MVT::i64, Op0, 6737 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6738 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6739 return; 6740 } 6741 // If the FP type needs to be softened, emit a library call using the 'si' 6742 // version. If we left it to default legalization we'd end up with 'di'. If 6743 // the FP type doesn't need to be softened just let generic type 6744 // legalization promote the result type. 6745 RTLIB::Libcall LC; 6746 if (IsSigned) 6747 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6748 else 6749 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6750 MakeLibCallOptions CallOptions; 6751 EVT OpVT = Op0.getValueType(); 6752 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6753 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6754 SDValue Result; 6755 std::tie(Result, Chain) = 6756 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6757 Results.push_back(Result); 6758 if (IsStrict) 6759 Results.push_back(Chain); 6760 break; 6761 } 6762 case ISD::READCYCLECOUNTER: { 6763 assert(!Subtarget.is64Bit() && 6764 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6765 6766 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6767 SDValue RCW = 6768 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6769 6770 Results.push_back( 6771 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6772 Results.push_back(RCW.getValue(2)); 6773 break; 6774 } 6775 case ISD::MUL: { 6776 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6777 unsigned XLen = Subtarget.getXLen(); 6778 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6779 if (Size > XLen) { 6780 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6781 SDValue LHS = N->getOperand(0); 6782 SDValue RHS = N->getOperand(1); 6783 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6784 6785 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6786 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6787 // We need exactly one side to be unsigned. 6788 if (LHSIsU == RHSIsU) 6789 return; 6790 6791 auto MakeMULPair = [&](SDValue S, SDValue U) { 6792 MVT XLenVT = Subtarget.getXLenVT(); 6793 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6794 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6795 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6796 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6797 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6798 }; 6799 6800 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6801 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6802 6803 // The other operand should be signed, but still prefer MULH when 6804 // possible. 6805 if (RHSIsU && LHSIsS && !RHSIsS) 6806 Results.push_back(MakeMULPair(LHS, RHS)); 6807 else if (LHSIsU && RHSIsS && !LHSIsS) 6808 Results.push_back(MakeMULPair(RHS, LHS)); 6809 6810 return; 6811 } 6812 LLVM_FALLTHROUGH; 6813 } 6814 case ISD::ADD: 6815 case ISD::SUB: 6816 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6817 "Unexpected custom legalisation"); 6818 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6819 break; 6820 case ISD::SHL: 6821 case ISD::SRA: 6822 case ISD::SRL: 6823 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6824 "Unexpected custom legalisation"); 6825 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6826 // If we can use a BSET instruction, allow default promotion to apply. 6827 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6828 isOneConstant(N->getOperand(0))) 6829 break; 6830 Results.push_back(customLegalizeToWOp(N, DAG)); 6831 break; 6832 } 6833 6834 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6835 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6836 // shift amount. 6837 if (N->getOpcode() == ISD::SHL) { 6838 SDLoc DL(N); 6839 SDValue NewOp0 = 6840 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6841 SDValue NewOp1 = 6842 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6843 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6844 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6845 DAG.getValueType(MVT::i32)); 6846 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6847 } 6848 6849 break; 6850 case ISD::ROTL: 6851 case ISD::ROTR: 6852 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6853 "Unexpected custom legalisation"); 6854 Results.push_back(customLegalizeToWOp(N, DAG)); 6855 break; 6856 case ISD::CTTZ: 6857 case ISD::CTTZ_ZERO_UNDEF: 6858 case ISD::CTLZ: 6859 case ISD::CTLZ_ZERO_UNDEF: { 6860 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6861 "Unexpected custom legalisation"); 6862 6863 SDValue NewOp0 = 6864 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6865 bool IsCTZ = 6866 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6867 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6868 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6869 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6870 return; 6871 } 6872 case ISD::SDIV: 6873 case ISD::UDIV: 6874 case ISD::UREM: { 6875 MVT VT = N->getSimpleValueType(0); 6876 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6877 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6878 "Unexpected custom legalisation"); 6879 // Don't promote division/remainder by constant since we should expand those 6880 // to multiply by magic constant. 6881 // FIXME: What if the expansion is disabled for minsize. 6882 if (N->getOperand(1).getOpcode() == ISD::Constant) 6883 return; 6884 6885 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6886 // the upper 32 bits. For other types we need to sign or zero extend 6887 // based on the opcode. 6888 unsigned ExtOpc = ISD::ANY_EXTEND; 6889 if (VT != MVT::i32) 6890 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6891 : ISD::ZERO_EXTEND; 6892 6893 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6894 break; 6895 } 6896 case ISD::UADDO: 6897 case ISD::USUBO: { 6898 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6899 "Unexpected custom legalisation"); 6900 bool IsAdd = N->getOpcode() == ISD::UADDO; 6901 // Create an ADDW or SUBW. 6902 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6903 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6904 SDValue Res = 6905 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6906 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6907 DAG.getValueType(MVT::i32)); 6908 6909 SDValue Overflow; 6910 if (IsAdd && isOneConstant(RHS)) { 6911 // Special case uaddo X, 1 overflowed if the addition result is 0. 6912 // The general case (X + C) < C is not necessarily beneficial. Although we 6913 // reduce the live range of X, we may introduce the materialization of 6914 // constant C, especially when the setcc result is used by branch. We have 6915 // no compare with constant and branch instructions. 6916 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6917 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6918 } else { 6919 // Sign extend the LHS and perform an unsigned compare with the ADDW 6920 // result. Since the inputs are sign extended from i32, this is equivalent 6921 // to comparing the lower 32 bits. 6922 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6923 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6924 IsAdd ? ISD::SETULT : ISD::SETUGT); 6925 } 6926 6927 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6928 Results.push_back(Overflow); 6929 return; 6930 } 6931 case ISD::UADDSAT: 6932 case ISD::USUBSAT: { 6933 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6934 "Unexpected custom legalisation"); 6935 if (Subtarget.hasStdExtZbb()) { 6936 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6937 // sign extend allows overflow of the lower 32 bits to be detected on 6938 // the promoted size. 6939 SDValue LHS = 6940 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6941 SDValue RHS = 6942 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6943 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6944 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6945 return; 6946 } 6947 6948 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6949 // promotion for UADDO/USUBO. 6950 Results.push_back(expandAddSubSat(N, DAG)); 6951 return; 6952 } 6953 case ISD::ABS: { 6954 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6955 "Unexpected custom legalisation"); 6956 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6957 6958 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6959 6960 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6961 6962 // Freeze the source so we can increase it's use count. 6963 Src = DAG.getFreeze(Src); 6964 6965 // Copy sign bit to all bits using the sraiw pattern. 6966 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6967 DAG.getValueType(MVT::i32)); 6968 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6969 DAG.getConstant(31, DL, MVT::i64)); 6970 6971 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6972 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6973 6974 // NOTE: The result is only required to be anyextended, but sext is 6975 // consistent with type legalization of sub. 6976 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6977 DAG.getValueType(MVT::i32)); 6978 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6979 return; 6980 } 6981 case ISD::BITCAST: { 6982 EVT VT = N->getValueType(0); 6983 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6984 SDValue Op0 = N->getOperand(0); 6985 EVT Op0VT = Op0.getValueType(); 6986 MVT XLenVT = Subtarget.getXLenVT(); 6987 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6988 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6989 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6990 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6991 Subtarget.hasStdExtF()) { 6992 SDValue FPConv = 6993 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6994 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6995 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6996 isTypeLegal(Op0VT)) { 6997 // Custom-legalize bitcasts from fixed-length vector types to illegal 6998 // scalar types in order to improve codegen. Bitcast the vector to a 6999 // one-element vector type whose element type is the same as the result 7000 // type, and extract the first element. 7001 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7002 if (isTypeLegal(BVT)) { 7003 SDValue BVec = DAG.getBitcast(BVT, Op0); 7004 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7005 DAG.getConstant(0, DL, XLenVT))); 7006 } 7007 } 7008 break; 7009 } 7010 case RISCVISD::GREV: 7011 case RISCVISD::GORC: 7012 case RISCVISD::SHFL: { 7013 MVT VT = N->getSimpleValueType(0); 7014 MVT XLenVT = Subtarget.getXLenVT(); 7015 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7016 "Unexpected custom legalisation"); 7017 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7018 assert((Subtarget.hasStdExtZbp() || 7019 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7020 N->getConstantOperandVal(1) == 7)) && 7021 "Unexpected extension"); 7022 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7023 SDValue NewOp1 = 7024 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7025 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7026 // ReplaceNodeResults requires we maintain the same type for the return 7027 // value. 7028 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7029 break; 7030 } 7031 case ISD::BSWAP: 7032 case ISD::BITREVERSE: { 7033 MVT VT = N->getSimpleValueType(0); 7034 MVT XLenVT = Subtarget.getXLenVT(); 7035 assert((VT == MVT::i8 || VT == MVT::i16 || 7036 (VT == MVT::i32 && Subtarget.is64Bit())) && 7037 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7038 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7039 unsigned Imm = VT.getSizeInBits() - 1; 7040 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7041 if (N->getOpcode() == ISD::BSWAP) 7042 Imm &= ~0x7U; 7043 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7044 DAG.getConstant(Imm, DL, XLenVT)); 7045 // ReplaceNodeResults requires we maintain the same type for the return 7046 // value. 7047 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7048 break; 7049 } 7050 case ISD::FSHL: 7051 case ISD::FSHR: { 7052 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7053 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7054 SDValue NewOp0 = 7055 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7056 SDValue NewOp1 = 7057 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7058 SDValue NewShAmt = 7059 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7060 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7061 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7062 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7063 DAG.getConstant(0x1f, DL, MVT::i64)); 7064 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7065 // instruction use different orders. fshl will return its first operand for 7066 // shift of zero, fshr will return its second operand. fsl and fsr both 7067 // return rs1 so the ISD nodes need to have different operand orders. 7068 // Shift amount is in rs2. 7069 unsigned Opc = RISCVISD::FSLW; 7070 if (N->getOpcode() == ISD::FSHR) { 7071 std::swap(NewOp0, NewOp1); 7072 Opc = RISCVISD::FSRW; 7073 } 7074 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7075 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7076 break; 7077 } 7078 case ISD::EXTRACT_VECTOR_ELT: { 7079 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7080 // type is illegal (currently only vXi64 RV32). 7081 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7082 // transferred to the destination register. We issue two of these from the 7083 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7084 // first element. 7085 SDValue Vec = N->getOperand(0); 7086 SDValue Idx = N->getOperand(1); 7087 7088 // The vector type hasn't been legalized yet so we can't issue target 7089 // specific nodes if it needs legalization. 7090 // FIXME: We would manually legalize if it's important. 7091 if (!isTypeLegal(Vec.getValueType())) 7092 return; 7093 7094 MVT VecVT = Vec.getSimpleValueType(); 7095 7096 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7097 VecVT.getVectorElementType() == MVT::i64 && 7098 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7099 7100 // If this is a fixed vector, we need to convert it to a scalable vector. 7101 MVT ContainerVT = VecVT; 7102 if (VecVT.isFixedLengthVector()) { 7103 ContainerVT = getContainerForFixedLengthVector(VecVT); 7104 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7105 } 7106 7107 MVT XLenVT = Subtarget.getXLenVT(); 7108 7109 // Use a VL of 1 to avoid processing more elements than we need. 7110 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7111 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7112 7113 // Unless the index is known to be 0, we must slide the vector down to get 7114 // the desired element into index 0. 7115 if (!isNullConstant(Idx)) { 7116 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7117 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7118 } 7119 7120 // Extract the lower XLEN bits of the correct vector element. 7121 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7122 7123 // To extract the upper XLEN bits of the vector element, shift the first 7124 // element right by 32 bits and re-extract the lower XLEN bits. 7125 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7126 DAG.getUNDEF(ContainerVT), 7127 DAG.getConstant(32, DL, XLenVT), VL); 7128 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7129 ThirtyTwoV, Mask, VL); 7130 7131 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7132 7133 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7134 break; 7135 } 7136 case ISD::INTRINSIC_WO_CHAIN: { 7137 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7138 switch (IntNo) { 7139 default: 7140 llvm_unreachable( 7141 "Don't know how to custom type legalize this intrinsic!"); 7142 case Intrinsic::riscv_grev: 7143 case Intrinsic::riscv_gorc: { 7144 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7145 "Unexpected custom legalisation"); 7146 SDValue NewOp1 = 7147 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7148 SDValue NewOp2 = 7149 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7150 unsigned Opc = 7151 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7152 // If the control is a constant, promote the node by clearing any extra 7153 // bits bits in the control. isel will form greviw/gorciw if the result is 7154 // sign extended. 7155 if (isa<ConstantSDNode>(NewOp2)) { 7156 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7157 DAG.getConstant(0x1f, DL, MVT::i64)); 7158 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7159 } 7160 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7161 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7162 break; 7163 } 7164 case Intrinsic::riscv_bcompress: 7165 case Intrinsic::riscv_bdecompress: 7166 case Intrinsic::riscv_bfp: 7167 case Intrinsic::riscv_fsl: 7168 case Intrinsic::riscv_fsr: { 7169 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7170 "Unexpected custom legalisation"); 7171 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7172 break; 7173 } 7174 case Intrinsic::riscv_orc_b: { 7175 // Lower to the GORCI encoding for orc.b with the operand extended. 7176 SDValue NewOp = 7177 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7178 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7179 DAG.getConstant(7, DL, MVT::i64)); 7180 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7181 return; 7182 } 7183 case Intrinsic::riscv_shfl: 7184 case Intrinsic::riscv_unshfl: { 7185 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7186 "Unexpected custom legalisation"); 7187 SDValue NewOp1 = 7188 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7189 SDValue NewOp2 = 7190 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7191 unsigned Opc = 7192 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7193 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7194 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7195 // will be shuffled the same way as the lower 32 bit half, but the two 7196 // halves won't cross. 7197 if (isa<ConstantSDNode>(NewOp2)) { 7198 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7199 DAG.getConstant(0xf, DL, MVT::i64)); 7200 Opc = 7201 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7202 } 7203 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7204 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7205 break; 7206 } 7207 case Intrinsic::riscv_vmv_x_s: { 7208 EVT VT = N->getValueType(0); 7209 MVT XLenVT = Subtarget.getXLenVT(); 7210 if (VT.bitsLT(XLenVT)) { 7211 // Simple case just extract using vmv.x.s and truncate. 7212 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7213 Subtarget.getXLenVT(), N->getOperand(1)); 7214 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7215 return; 7216 } 7217 7218 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7219 "Unexpected custom legalization"); 7220 7221 // We need to do the move in two steps. 7222 SDValue Vec = N->getOperand(1); 7223 MVT VecVT = Vec.getSimpleValueType(); 7224 7225 // First extract the lower XLEN bits of the element. 7226 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7227 7228 // To extract the upper XLEN bits of the vector element, shift the first 7229 // element right by 32 bits and re-extract the lower XLEN bits. 7230 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7231 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7232 7233 SDValue ThirtyTwoV = 7234 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7235 DAG.getConstant(32, DL, XLenVT), VL); 7236 SDValue LShr32 = 7237 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7238 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7239 7240 Results.push_back( 7241 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7242 break; 7243 } 7244 } 7245 break; 7246 } 7247 case ISD::VECREDUCE_ADD: 7248 case ISD::VECREDUCE_AND: 7249 case ISD::VECREDUCE_OR: 7250 case ISD::VECREDUCE_XOR: 7251 case ISD::VECREDUCE_SMAX: 7252 case ISD::VECREDUCE_UMAX: 7253 case ISD::VECREDUCE_SMIN: 7254 case ISD::VECREDUCE_UMIN: 7255 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7256 Results.push_back(V); 7257 break; 7258 case ISD::VP_REDUCE_ADD: 7259 case ISD::VP_REDUCE_AND: 7260 case ISD::VP_REDUCE_OR: 7261 case ISD::VP_REDUCE_XOR: 7262 case ISD::VP_REDUCE_SMAX: 7263 case ISD::VP_REDUCE_UMAX: 7264 case ISD::VP_REDUCE_SMIN: 7265 case ISD::VP_REDUCE_UMIN: 7266 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7267 Results.push_back(V); 7268 break; 7269 case ISD::FLT_ROUNDS_: { 7270 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7271 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7272 Results.push_back(Res.getValue(0)); 7273 Results.push_back(Res.getValue(1)); 7274 break; 7275 } 7276 } 7277 } 7278 7279 // A structure to hold one of the bit-manipulation patterns below. Together, a 7280 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7281 // (or (and (shl x, 1), 0xAAAAAAAA), 7282 // (and (srl x, 1), 0x55555555)) 7283 struct RISCVBitmanipPat { 7284 SDValue Op; 7285 unsigned ShAmt; 7286 bool IsSHL; 7287 7288 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7289 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7290 } 7291 }; 7292 7293 // Matches patterns of the form 7294 // (and (shl x, C2), (C1 << C2)) 7295 // (and (srl x, C2), C1) 7296 // (shl (and x, C1), C2) 7297 // (srl (and x, (C1 << C2)), C2) 7298 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7299 // The expected masks for each shift amount are specified in BitmanipMasks where 7300 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7301 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7302 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7303 // XLen is 64. 7304 static Optional<RISCVBitmanipPat> 7305 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7306 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7307 "Unexpected number of masks"); 7308 Optional<uint64_t> Mask; 7309 // Optionally consume a mask around the shift operation. 7310 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7311 Mask = Op.getConstantOperandVal(1); 7312 Op = Op.getOperand(0); 7313 } 7314 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7315 return None; 7316 bool IsSHL = Op.getOpcode() == ISD::SHL; 7317 7318 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7319 return None; 7320 uint64_t ShAmt = Op.getConstantOperandVal(1); 7321 7322 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7323 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7324 return None; 7325 // If we don't have enough masks for 64 bit, then we must be trying to 7326 // match SHFL so we're only allowed to shift 1/4 of the width. 7327 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7328 return None; 7329 7330 SDValue Src = Op.getOperand(0); 7331 7332 // The expected mask is shifted left when the AND is found around SHL 7333 // patterns. 7334 // ((x >> 1) & 0x55555555) 7335 // ((x << 1) & 0xAAAAAAAA) 7336 bool SHLExpMask = IsSHL; 7337 7338 if (!Mask) { 7339 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7340 // the mask is all ones: consume that now. 7341 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7342 Mask = Src.getConstantOperandVal(1); 7343 Src = Src.getOperand(0); 7344 // The expected mask is now in fact shifted left for SRL, so reverse the 7345 // decision. 7346 // ((x & 0xAAAAAAAA) >> 1) 7347 // ((x & 0x55555555) << 1) 7348 SHLExpMask = !SHLExpMask; 7349 } else { 7350 // Use a default shifted mask of all-ones if there's no AND, truncated 7351 // down to the expected width. This simplifies the logic later on. 7352 Mask = maskTrailingOnes<uint64_t>(Width); 7353 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7354 } 7355 } 7356 7357 unsigned MaskIdx = Log2_32(ShAmt); 7358 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7359 7360 if (SHLExpMask) 7361 ExpMask <<= ShAmt; 7362 7363 if (Mask != ExpMask) 7364 return None; 7365 7366 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7367 } 7368 7369 // Matches any of the following bit-manipulation patterns: 7370 // (and (shl x, 1), (0x55555555 << 1)) 7371 // (and (srl x, 1), 0x55555555) 7372 // (shl (and x, 0x55555555), 1) 7373 // (srl (and x, (0x55555555 << 1)), 1) 7374 // where the shift amount and mask may vary thus: 7375 // [1] = 0x55555555 / 0xAAAAAAAA 7376 // [2] = 0x33333333 / 0xCCCCCCCC 7377 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7378 // [8] = 0x00FF00FF / 0xFF00FF00 7379 // [16] = 0x0000FFFF / 0xFFFFFFFF 7380 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7381 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7382 // These are the unshifted masks which we use to match bit-manipulation 7383 // patterns. They may be shifted left in certain circumstances. 7384 static const uint64_t BitmanipMasks[] = { 7385 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7386 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7387 7388 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7389 } 7390 7391 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7392 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7393 auto BinOpToRVVReduce = [](unsigned Opc) { 7394 switch (Opc) { 7395 default: 7396 llvm_unreachable("Unhandled binary to transfrom reduction"); 7397 case ISD::ADD: 7398 return RISCVISD::VECREDUCE_ADD_VL; 7399 case ISD::UMAX: 7400 return RISCVISD::VECREDUCE_UMAX_VL; 7401 case ISD::SMAX: 7402 return RISCVISD::VECREDUCE_SMAX_VL; 7403 case ISD::UMIN: 7404 return RISCVISD::VECREDUCE_UMIN_VL; 7405 case ISD::SMIN: 7406 return RISCVISD::VECREDUCE_SMIN_VL; 7407 case ISD::AND: 7408 return RISCVISD::VECREDUCE_AND_VL; 7409 case ISD::OR: 7410 return RISCVISD::VECREDUCE_OR_VL; 7411 case ISD::XOR: 7412 return RISCVISD::VECREDUCE_XOR_VL; 7413 case ISD::FADD: 7414 return RISCVISD::VECREDUCE_FADD_VL; 7415 case ISD::FMAXNUM: 7416 return RISCVISD::VECREDUCE_FMAX_VL; 7417 case ISD::FMINNUM: 7418 return RISCVISD::VECREDUCE_FMIN_VL; 7419 } 7420 }; 7421 7422 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7423 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7424 isNullConstant(V.getOperand(1)) && 7425 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7426 }; 7427 7428 unsigned Opc = N->getOpcode(); 7429 unsigned ReduceIdx; 7430 if (IsReduction(N->getOperand(0), Opc)) 7431 ReduceIdx = 0; 7432 else if (IsReduction(N->getOperand(1), Opc)) 7433 ReduceIdx = 1; 7434 else 7435 return SDValue(); 7436 7437 // Skip if FADD disallows reassociation but the combiner needs. 7438 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7439 return SDValue(); 7440 7441 SDValue Extract = N->getOperand(ReduceIdx); 7442 SDValue Reduce = Extract.getOperand(0); 7443 if (!Reduce.hasOneUse()) 7444 return SDValue(); 7445 7446 SDValue ScalarV = Reduce.getOperand(2); 7447 7448 // Make sure that ScalarV is a splat with VL=1. 7449 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7450 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7451 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7452 return SDValue(); 7453 7454 if (!isOneConstant(ScalarV.getOperand(2))) 7455 return SDValue(); 7456 7457 // TODO: Deal with value other than neutral element. 7458 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7459 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7460 isNullFPConstant(V)) 7461 return true; 7462 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7463 N->getFlags()) == V; 7464 }; 7465 7466 // Check the scalar of ScalarV is neutral element 7467 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7468 return SDValue(); 7469 7470 if (!ScalarV.hasOneUse()) 7471 return SDValue(); 7472 7473 EVT SplatVT = ScalarV.getValueType(); 7474 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7475 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7476 if (SplatVT.isInteger()) { 7477 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7478 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7479 SplatOpc = RISCVISD::VMV_S_X_VL; 7480 else 7481 SplatOpc = RISCVISD::VMV_V_X_VL; 7482 } 7483 7484 SDValue NewScalarV = 7485 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7486 ScalarV.getOperand(2)); 7487 SDValue NewReduce = 7488 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7489 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7490 Reduce.getOperand(3), Reduce.getOperand(4)); 7491 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7492 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7493 } 7494 7495 // Match the following pattern as a GREVI(W) operation 7496 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7497 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7498 const RISCVSubtarget &Subtarget) { 7499 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7500 EVT VT = Op.getValueType(); 7501 7502 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7503 auto LHS = matchGREVIPat(Op.getOperand(0)); 7504 auto RHS = matchGREVIPat(Op.getOperand(1)); 7505 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7506 SDLoc DL(Op); 7507 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7508 DAG.getConstant(LHS->ShAmt, DL, VT)); 7509 } 7510 } 7511 return SDValue(); 7512 } 7513 7514 // Matches any the following pattern as a GORCI(W) operation 7515 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7516 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7517 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7518 // Note that with the variant of 3., 7519 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7520 // the inner pattern will first be matched as GREVI and then the outer 7521 // pattern will be matched to GORC via the first rule above. 7522 // 4. (or (rotl/rotr x, bitwidth/2), x) 7523 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7524 const RISCVSubtarget &Subtarget) { 7525 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7526 EVT VT = Op.getValueType(); 7527 7528 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7529 SDLoc DL(Op); 7530 SDValue Op0 = Op.getOperand(0); 7531 SDValue Op1 = Op.getOperand(1); 7532 7533 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7534 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7535 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7536 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7537 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7538 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7539 if ((Reverse.getOpcode() == ISD::ROTL || 7540 Reverse.getOpcode() == ISD::ROTR) && 7541 Reverse.getOperand(0) == X && 7542 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7543 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7544 if (RotAmt == (VT.getSizeInBits() / 2)) 7545 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7546 DAG.getConstant(RotAmt, DL, VT)); 7547 } 7548 return SDValue(); 7549 }; 7550 7551 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7552 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7553 return V; 7554 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7555 return V; 7556 7557 // OR is commutable so canonicalize its OR operand to the left 7558 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7559 std::swap(Op0, Op1); 7560 if (Op0.getOpcode() != ISD::OR) 7561 return SDValue(); 7562 SDValue OrOp0 = Op0.getOperand(0); 7563 SDValue OrOp1 = Op0.getOperand(1); 7564 auto LHS = matchGREVIPat(OrOp0); 7565 // OR is commutable so swap the operands and try again: x might have been 7566 // on the left 7567 if (!LHS) { 7568 std::swap(OrOp0, OrOp1); 7569 LHS = matchGREVIPat(OrOp0); 7570 } 7571 auto RHS = matchGREVIPat(Op1); 7572 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7573 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7574 DAG.getConstant(LHS->ShAmt, DL, VT)); 7575 } 7576 } 7577 return SDValue(); 7578 } 7579 7580 // Matches any of the following bit-manipulation patterns: 7581 // (and (shl x, 1), (0x22222222 << 1)) 7582 // (and (srl x, 1), 0x22222222) 7583 // (shl (and x, 0x22222222), 1) 7584 // (srl (and x, (0x22222222 << 1)), 1) 7585 // where the shift amount and mask may vary thus: 7586 // [1] = 0x22222222 / 0x44444444 7587 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7588 // [4] = 0x00F000F0 / 0x0F000F00 7589 // [8] = 0x0000FF00 / 0x00FF0000 7590 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7591 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7592 // These are the unshifted masks which we use to match bit-manipulation 7593 // patterns. They may be shifted left in certain circumstances. 7594 static const uint64_t BitmanipMasks[] = { 7595 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7596 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7597 7598 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7599 } 7600 7601 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7602 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7603 const RISCVSubtarget &Subtarget) { 7604 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7605 EVT VT = Op.getValueType(); 7606 7607 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7608 return SDValue(); 7609 7610 SDValue Op0 = Op.getOperand(0); 7611 SDValue Op1 = Op.getOperand(1); 7612 7613 // Or is commutable so canonicalize the second OR to the LHS. 7614 if (Op0.getOpcode() != ISD::OR) 7615 std::swap(Op0, Op1); 7616 if (Op0.getOpcode() != ISD::OR) 7617 return SDValue(); 7618 7619 // We found an inner OR, so our operands are the operands of the inner OR 7620 // and the other operand of the outer OR. 7621 SDValue A = Op0.getOperand(0); 7622 SDValue B = Op0.getOperand(1); 7623 SDValue C = Op1; 7624 7625 auto Match1 = matchSHFLPat(A); 7626 auto Match2 = matchSHFLPat(B); 7627 7628 // If neither matched, we failed. 7629 if (!Match1 && !Match2) 7630 return SDValue(); 7631 7632 // We had at least one match. if one failed, try the remaining C operand. 7633 if (!Match1) { 7634 std::swap(A, C); 7635 Match1 = matchSHFLPat(A); 7636 if (!Match1) 7637 return SDValue(); 7638 } else if (!Match2) { 7639 std::swap(B, C); 7640 Match2 = matchSHFLPat(B); 7641 if (!Match2) 7642 return SDValue(); 7643 } 7644 assert(Match1 && Match2); 7645 7646 // Make sure our matches pair up. 7647 if (!Match1->formsPairWith(*Match2)) 7648 return SDValue(); 7649 7650 // All the remains is to make sure C is an AND with the same input, that masks 7651 // out the bits that are being shuffled. 7652 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7653 C.getOperand(0) != Match1->Op) 7654 return SDValue(); 7655 7656 uint64_t Mask = C.getConstantOperandVal(1); 7657 7658 static const uint64_t BitmanipMasks[] = { 7659 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7660 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7661 }; 7662 7663 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7664 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7665 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7666 7667 if (Mask != ExpMask) 7668 return SDValue(); 7669 7670 SDLoc DL(Op); 7671 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7672 DAG.getConstant(Match1->ShAmt, DL, VT)); 7673 } 7674 7675 // Optimize (add (shl x, c0), (shl y, c1)) -> 7676 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7677 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7678 const RISCVSubtarget &Subtarget) { 7679 // Perform this optimization only in the zba extension. 7680 if (!Subtarget.hasStdExtZba()) 7681 return SDValue(); 7682 7683 // Skip for vector types and larger types. 7684 EVT VT = N->getValueType(0); 7685 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7686 return SDValue(); 7687 7688 // The two operand nodes must be SHL and have no other use. 7689 SDValue N0 = N->getOperand(0); 7690 SDValue N1 = N->getOperand(1); 7691 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7692 !N0->hasOneUse() || !N1->hasOneUse()) 7693 return SDValue(); 7694 7695 // Check c0 and c1. 7696 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7697 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7698 if (!N0C || !N1C) 7699 return SDValue(); 7700 int64_t C0 = N0C->getSExtValue(); 7701 int64_t C1 = N1C->getSExtValue(); 7702 if (C0 <= 0 || C1 <= 0) 7703 return SDValue(); 7704 7705 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7706 int64_t Bits = std::min(C0, C1); 7707 int64_t Diff = std::abs(C0 - C1); 7708 if (Diff != 1 && Diff != 2 && Diff != 3) 7709 return SDValue(); 7710 7711 // Build nodes. 7712 SDLoc DL(N); 7713 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7714 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7715 SDValue NA0 = 7716 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7717 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7718 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7719 } 7720 7721 // Combine 7722 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7723 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7724 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7725 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7726 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7727 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7728 // The grev patterns represents BSWAP. 7729 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7730 // off the grev. 7731 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7732 const RISCVSubtarget &Subtarget) { 7733 bool IsWInstruction = 7734 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7735 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7736 IsWInstruction) && 7737 "Unexpected opcode!"); 7738 SDValue Src = N->getOperand(0); 7739 EVT VT = N->getValueType(0); 7740 SDLoc DL(N); 7741 7742 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7743 return SDValue(); 7744 7745 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7746 !isa<ConstantSDNode>(Src.getOperand(1))) 7747 return SDValue(); 7748 7749 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7750 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7751 7752 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7753 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7754 unsigned ShAmt1 = N->getConstantOperandVal(1); 7755 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7756 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7757 return SDValue(); 7758 7759 Src = Src.getOperand(0); 7760 7761 // Toggle bit the MSB of the shift. 7762 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7763 if (CombinedShAmt == 0) 7764 return Src; 7765 7766 SDValue Res = DAG.getNode( 7767 RISCVISD::GREV, DL, VT, Src, 7768 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7769 if (!IsWInstruction) 7770 return Res; 7771 7772 // Sign extend the result to match the behavior of the rotate. This will be 7773 // selected to GREVIW in isel. 7774 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7775 DAG.getValueType(MVT::i32)); 7776 } 7777 7778 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7779 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7780 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7781 // not undo itself, but they are redundant. 7782 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7783 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7784 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7785 SDValue Src = N->getOperand(0); 7786 7787 if (Src.getOpcode() != N->getOpcode()) 7788 return SDValue(); 7789 7790 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7791 !isa<ConstantSDNode>(Src.getOperand(1))) 7792 return SDValue(); 7793 7794 unsigned ShAmt1 = N->getConstantOperandVal(1); 7795 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7796 Src = Src.getOperand(0); 7797 7798 unsigned CombinedShAmt; 7799 if (IsGORC) 7800 CombinedShAmt = ShAmt1 | ShAmt2; 7801 else 7802 CombinedShAmt = ShAmt1 ^ ShAmt2; 7803 7804 if (CombinedShAmt == 0) 7805 return Src; 7806 7807 SDLoc DL(N); 7808 return DAG.getNode( 7809 N->getOpcode(), DL, N->getValueType(0), Src, 7810 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7811 } 7812 7813 // Combine a constant select operand into its use: 7814 // 7815 // (and (select cond, -1, c), x) 7816 // -> (select cond, x, (and x, c)) [AllOnes=1] 7817 // (or (select cond, 0, c), x) 7818 // -> (select cond, x, (or x, c)) [AllOnes=0] 7819 // (xor (select cond, 0, c), x) 7820 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7821 // (add (select cond, 0, c), x) 7822 // -> (select cond, x, (add x, c)) [AllOnes=0] 7823 // (sub x, (select cond, 0, c)) 7824 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7825 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7826 SelectionDAG &DAG, bool AllOnes) { 7827 EVT VT = N->getValueType(0); 7828 7829 // Skip vectors. 7830 if (VT.isVector()) 7831 return SDValue(); 7832 7833 if ((Slct.getOpcode() != ISD::SELECT && 7834 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7835 !Slct.hasOneUse()) 7836 return SDValue(); 7837 7838 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7839 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7840 }; 7841 7842 bool SwapSelectOps; 7843 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7844 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7845 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7846 SDValue NonConstantVal; 7847 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7848 SwapSelectOps = false; 7849 NonConstantVal = FalseVal; 7850 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7851 SwapSelectOps = true; 7852 NonConstantVal = TrueVal; 7853 } else 7854 return SDValue(); 7855 7856 // Slct is now know to be the desired identity constant when CC is true. 7857 TrueVal = OtherOp; 7858 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7859 // Unless SwapSelectOps says the condition should be false. 7860 if (SwapSelectOps) 7861 std::swap(TrueVal, FalseVal); 7862 7863 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7864 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7865 {Slct.getOperand(0), Slct.getOperand(1), 7866 Slct.getOperand(2), TrueVal, FalseVal}); 7867 7868 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7869 {Slct.getOperand(0), TrueVal, FalseVal}); 7870 } 7871 7872 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7873 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7874 bool AllOnes) { 7875 SDValue N0 = N->getOperand(0); 7876 SDValue N1 = N->getOperand(1); 7877 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7878 return Result; 7879 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7880 return Result; 7881 return SDValue(); 7882 } 7883 7884 // Transform (add (mul x, c0), c1) -> 7885 // (add (mul (add x, c1/c0), c0), c1%c0). 7886 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7887 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7888 // to an infinite loop in DAGCombine if transformed. 7889 // Or transform (add (mul x, c0), c1) -> 7890 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7891 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7892 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7893 // lead to an infinite loop in DAGCombine if transformed. 7894 // Or transform (add (mul x, c0), c1) -> 7895 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7896 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7897 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7898 // lead to an infinite loop in DAGCombine if transformed. 7899 // Or transform (add (mul x, c0), c1) -> 7900 // (mul (add x, c1/c0), c0). 7901 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7902 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7903 const RISCVSubtarget &Subtarget) { 7904 // Skip for vector types and larger types. 7905 EVT VT = N->getValueType(0); 7906 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7907 return SDValue(); 7908 // The first operand node must be a MUL and has no other use. 7909 SDValue N0 = N->getOperand(0); 7910 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7911 return SDValue(); 7912 // Check if c0 and c1 match above conditions. 7913 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7914 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7915 if (!N0C || !N1C) 7916 return SDValue(); 7917 // If N0C has multiple uses it's possible one of the cases in 7918 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7919 // in an infinite loop. 7920 if (!N0C->hasOneUse()) 7921 return SDValue(); 7922 int64_t C0 = N0C->getSExtValue(); 7923 int64_t C1 = N1C->getSExtValue(); 7924 int64_t CA, CB; 7925 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7926 return SDValue(); 7927 // Search for proper CA (non-zero) and CB that both are simm12. 7928 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7929 !isInt<12>(C0 * (C1 / C0))) { 7930 CA = C1 / C0; 7931 CB = C1 % C0; 7932 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7933 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7934 CA = C1 / C0 + 1; 7935 CB = C1 % C0 - C0; 7936 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7937 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7938 CA = C1 / C0 - 1; 7939 CB = C1 % C0 + C0; 7940 } else 7941 return SDValue(); 7942 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7943 SDLoc DL(N); 7944 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7945 DAG.getConstant(CA, DL, VT)); 7946 SDValue New1 = 7947 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7948 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7949 } 7950 7951 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7952 const RISCVSubtarget &Subtarget) { 7953 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7954 return V; 7955 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7956 return V; 7957 if (SDValue V = combineBinOpToReduce(N, DAG)) 7958 return V; 7959 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7960 // (select lhs, rhs, cc, x, (add x, y)) 7961 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7962 } 7963 7964 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7965 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7966 // (select lhs, rhs, cc, x, (sub x, y)) 7967 SDValue N0 = N->getOperand(0); 7968 SDValue N1 = N->getOperand(1); 7969 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7970 } 7971 7972 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 7973 const RISCVSubtarget &Subtarget) { 7974 SDValue N0 = N->getOperand(0); 7975 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 7976 // extending X. This is safe since we only need the LSB after the shift and 7977 // shift amounts larger than 31 would produce poison. If we wait until 7978 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 7979 // to use a BEXT instruction. 7980 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 7981 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 7982 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 7983 N0.hasOneUse()) { 7984 SDLoc DL(N); 7985 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 7986 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 7987 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 7988 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 7989 DAG.getConstant(1, DL, MVT::i64)); 7990 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 7991 } 7992 7993 if (SDValue V = combineBinOpToReduce(N, DAG)) 7994 return V; 7995 7996 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7997 // (select lhs, rhs, cc, x, (and x, y)) 7998 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7999 } 8000 8001 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8002 const RISCVSubtarget &Subtarget) { 8003 if (Subtarget.hasStdExtZbp()) { 8004 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8005 return GREV; 8006 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8007 return GORC; 8008 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8009 return SHFL; 8010 } 8011 8012 if (SDValue V = combineBinOpToReduce(N, DAG)) 8013 return V; 8014 // fold (or (select cond, 0, y), x) -> 8015 // (select cond, x, (or x, y)) 8016 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8017 } 8018 8019 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8020 SDValue N0 = N->getOperand(0); 8021 SDValue N1 = N->getOperand(1); 8022 8023 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8024 // NOTE: Assumes ROL being legal means ROLW is legal. 8025 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8026 if (N0.getOpcode() == RISCVISD::SLLW && 8027 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8028 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8029 SDLoc DL(N); 8030 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8031 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8032 } 8033 8034 if (SDValue V = combineBinOpToReduce(N, DAG)) 8035 return V; 8036 // fold (xor (select cond, 0, y), x) -> 8037 // (select cond, x, (xor x, y)) 8038 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8039 } 8040 8041 static SDValue 8042 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8043 const RISCVSubtarget &Subtarget) { 8044 SDValue Src = N->getOperand(0); 8045 EVT VT = N->getValueType(0); 8046 8047 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8048 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8049 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8050 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8051 Src.getOperand(0)); 8052 8053 // Fold (i64 (sext_inreg (abs X), i32)) -> 8054 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8055 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8056 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8057 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8058 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8059 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8060 // may get combined into an earlier operation so we need to use 8061 // ComputeNumSignBits. 8062 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8063 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8064 // we can't assume that X has 33 sign bits. We must check. 8065 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8066 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8067 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8068 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8069 SDLoc DL(N); 8070 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8071 SDValue Neg = 8072 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8073 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8074 DAG.getValueType(MVT::i32)); 8075 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8076 } 8077 8078 return SDValue(); 8079 } 8080 8081 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8082 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8083 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8084 bool Commute = false) { 8085 assert((N->getOpcode() == RISCVISD::ADD_VL || 8086 N->getOpcode() == RISCVISD::SUB_VL) && 8087 "Unexpected opcode"); 8088 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8089 SDValue Op0 = N->getOperand(0); 8090 SDValue Op1 = N->getOperand(1); 8091 if (Commute) 8092 std::swap(Op0, Op1); 8093 8094 MVT VT = N->getSimpleValueType(0); 8095 8096 // Determine the narrow size for a widening add/sub. 8097 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8098 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8099 VT.getVectorElementCount()); 8100 8101 SDValue Mask = N->getOperand(2); 8102 SDValue VL = N->getOperand(3); 8103 8104 SDLoc DL(N); 8105 8106 // If the RHS is a sext or zext, we can form a widening op. 8107 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8108 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8109 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8110 unsigned ExtOpc = Op1.getOpcode(); 8111 Op1 = Op1.getOperand(0); 8112 // Re-introduce narrower extends if needed. 8113 if (Op1.getValueType() != NarrowVT) 8114 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8115 8116 unsigned WOpc; 8117 if (ExtOpc == RISCVISD::VSEXT_VL) 8118 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8119 else 8120 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8121 8122 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8123 } 8124 8125 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8126 // sext/zext? 8127 8128 return SDValue(); 8129 } 8130 8131 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8132 // vwsub(u).vv/vx. 8133 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8134 SDValue Op0 = N->getOperand(0); 8135 SDValue Op1 = N->getOperand(1); 8136 SDValue Mask = N->getOperand(2); 8137 SDValue VL = N->getOperand(3); 8138 8139 MVT VT = N->getSimpleValueType(0); 8140 MVT NarrowVT = Op1.getSimpleValueType(); 8141 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8142 8143 unsigned VOpc; 8144 switch (N->getOpcode()) { 8145 default: llvm_unreachable("Unexpected opcode"); 8146 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8147 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8148 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8149 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8150 } 8151 8152 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8153 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8154 8155 SDLoc DL(N); 8156 8157 // If the LHS is a sext or zext, we can narrow this op to the same size as 8158 // the RHS. 8159 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8160 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8161 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8162 unsigned ExtOpc = Op0.getOpcode(); 8163 Op0 = Op0.getOperand(0); 8164 // Re-introduce narrower extends if needed. 8165 if (Op0.getValueType() != NarrowVT) 8166 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8167 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8168 } 8169 8170 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8171 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8172 8173 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8174 // to commute and use a vwadd(u).vx instead. 8175 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8176 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8177 Op0 = Op0.getOperand(1); 8178 8179 // See if have enough sign bits or zero bits in the scalar to use a 8180 // widening add/sub by splatting to smaller element size. 8181 unsigned EltBits = VT.getScalarSizeInBits(); 8182 unsigned ScalarBits = Op0.getValueSizeInBits(); 8183 // Make sure we're getting all element bits from the scalar register. 8184 // FIXME: Support implicit sign extension of vmv.v.x? 8185 if (ScalarBits < EltBits) 8186 return SDValue(); 8187 8188 if (IsSigned) { 8189 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8190 return SDValue(); 8191 } else { 8192 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8193 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8194 return SDValue(); 8195 } 8196 8197 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8198 DAG.getUNDEF(NarrowVT), Op0, VL); 8199 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8200 } 8201 8202 return SDValue(); 8203 } 8204 8205 // Try to form VWMUL, VWMULU or VWMULSU. 8206 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8207 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8208 bool Commute) { 8209 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8210 SDValue Op0 = N->getOperand(0); 8211 SDValue Op1 = N->getOperand(1); 8212 if (Commute) 8213 std::swap(Op0, Op1); 8214 8215 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8216 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8217 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8218 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8219 return SDValue(); 8220 8221 SDValue Mask = N->getOperand(2); 8222 SDValue VL = N->getOperand(3); 8223 8224 // Make sure the mask and VL match. 8225 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8226 return SDValue(); 8227 8228 MVT VT = N->getSimpleValueType(0); 8229 8230 // Determine the narrow size for a widening multiply. 8231 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8232 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8233 VT.getVectorElementCount()); 8234 8235 SDLoc DL(N); 8236 8237 // See if the other operand is the same opcode. 8238 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8239 if (!Op1.hasOneUse()) 8240 return SDValue(); 8241 8242 // Make sure the mask and VL match. 8243 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8244 return SDValue(); 8245 8246 Op1 = Op1.getOperand(0); 8247 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8248 // The operand is a splat of a scalar. 8249 8250 // The pasthru must be undef for tail agnostic 8251 if (!Op1.getOperand(0).isUndef()) 8252 return SDValue(); 8253 // The VL must be the same. 8254 if (Op1.getOperand(2) != VL) 8255 return SDValue(); 8256 8257 // Get the scalar value. 8258 Op1 = Op1.getOperand(1); 8259 8260 // See if have enough sign bits or zero bits in the scalar to use a 8261 // widening multiply by splatting to smaller element size. 8262 unsigned EltBits = VT.getScalarSizeInBits(); 8263 unsigned ScalarBits = Op1.getValueSizeInBits(); 8264 // Make sure we're getting all element bits from the scalar register. 8265 // FIXME: Support implicit sign extension of vmv.v.x? 8266 if (ScalarBits < EltBits) 8267 return SDValue(); 8268 8269 // If the LHS is a sign extend, try to use vwmul. 8270 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8271 // Can use vwmul. 8272 } else { 8273 // Otherwise try to use vwmulu or vwmulsu. 8274 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8275 if (DAG.MaskedValueIsZero(Op1, Mask)) 8276 IsVWMULSU = IsSignExt; 8277 else 8278 return SDValue(); 8279 } 8280 8281 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8282 DAG.getUNDEF(NarrowVT), Op1, VL); 8283 } else 8284 return SDValue(); 8285 8286 Op0 = Op0.getOperand(0); 8287 8288 // Re-introduce narrower extends if needed. 8289 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8290 if (Op0.getValueType() != NarrowVT) 8291 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8292 // vwmulsu requires second operand to be zero extended. 8293 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8294 if (Op1.getValueType() != NarrowVT) 8295 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8296 8297 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8298 if (!IsVWMULSU) 8299 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8300 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8301 } 8302 8303 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8304 switch (Op.getOpcode()) { 8305 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8306 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8307 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8308 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8309 case ISD::FROUND: return RISCVFPRndMode::RMM; 8310 } 8311 8312 return RISCVFPRndMode::Invalid; 8313 } 8314 8315 // Fold 8316 // (fp_to_int (froundeven X)) -> fcvt X, rne 8317 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8318 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8319 // (fp_to_int (fceil X)) -> fcvt X, rup 8320 // (fp_to_int (fround X)) -> fcvt X, rmm 8321 static SDValue performFP_TO_INTCombine(SDNode *N, 8322 TargetLowering::DAGCombinerInfo &DCI, 8323 const RISCVSubtarget &Subtarget) { 8324 SelectionDAG &DAG = DCI.DAG; 8325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8326 MVT XLenVT = Subtarget.getXLenVT(); 8327 8328 // Only handle XLen or i32 types. Other types narrower than XLen will 8329 // eventually be legalized to XLenVT. 8330 EVT VT = N->getValueType(0); 8331 if (VT != MVT::i32 && VT != XLenVT) 8332 return SDValue(); 8333 8334 SDValue Src = N->getOperand(0); 8335 8336 // Ensure the FP type is also legal. 8337 if (!TLI.isTypeLegal(Src.getValueType())) 8338 return SDValue(); 8339 8340 // Don't do this for f16 with Zfhmin and not Zfh. 8341 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8342 return SDValue(); 8343 8344 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8345 if (FRM == RISCVFPRndMode::Invalid) 8346 return SDValue(); 8347 8348 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8349 8350 unsigned Opc; 8351 if (VT == XLenVT) 8352 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8353 else 8354 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8355 8356 SDLoc DL(N); 8357 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8358 DAG.getTargetConstant(FRM, DL, XLenVT)); 8359 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8360 } 8361 8362 // Fold 8363 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8364 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8365 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8366 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8367 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8368 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8369 TargetLowering::DAGCombinerInfo &DCI, 8370 const RISCVSubtarget &Subtarget) { 8371 SelectionDAG &DAG = DCI.DAG; 8372 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8373 MVT XLenVT = Subtarget.getXLenVT(); 8374 8375 // Only handle XLen types. Other types narrower than XLen will eventually be 8376 // legalized to XLenVT. 8377 EVT DstVT = N->getValueType(0); 8378 if (DstVT != XLenVT) 8379 return SDValue(); 8380 8381 SDValue Src = N->getOperand(0); 8382 8383 // Ensure the FP type is also legal. 8384 if (!TLI.isTypeLegal(Src.getValueType())) 8385 return SDValue(); 8386 8387 // Don't do this for f16 with Zfhmin and not Zfh. 8388 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8389 return SDValue(); 8390 8391 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8392 8393 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8394 if (FRM == RISCVFPRndMode::Invalid) 8395 return SDValue(); 8396 8397 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8398 8399 unsigned Opc; 8400 if (SatVT == DstVT) 8401 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8402 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8403 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8404 else 8405 return SDValue(); 8406 // FIXME: Support other SatVTs by clamping before or after the conversion. 8407 8408 Src = Src.getOperand(0); 8409 8410 SDLoc DL(N); 8411 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8412 DAG.getTargetConstant(FRM, DL, XLenVT)); 8413 8414 // RISCV FP-to-int conversions saturate to the destination register size, but 8415 // don't produce 0 for nan. 8416 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8417 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8418 } 8419 8420 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8421 // smaller than XLenVT. 8422 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8423 const RISCVSubtarget &Subtarget) { 8424 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8425 8426 SDValue Src = N->getOperand(0); 8427 if (Src.getOpcode() != ISD::BSWAP) 8428 return SDValue(); 8429 8430 EVT VT = N->getValueType(0); 8431 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8432 !isPowerOf2_32(VT.getSizeInBits())) 8433 return SDValue(); 8434 8435 SDLoc DL(N); 8436 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8437 DAG.getConstant(7, DL, VT)); 8438 } 8439 8440 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8441 DAGCombinerInfo &DCI) const { 8442 SelectionDAG &DAG = DCI.DAG; 8443 8444 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8445 // bits are demanded. N will be added to the Worklist if it was not deleted. 8446 // Caller should return SDValue(N, 0) if this returns true. 8447 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8448 SDValue Op = N->getOperand(OpNo); 8449 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8450 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8451 return false; 8452 8453 if (N->getOpcode() != ISD::DELETED_NODE) 8454 DCI.AddToWorklist(N); 8455 return true; 8456 }; 8457 8458 switch (N->getOpcode()) { 8459 default: 8460 break; 8461 case RISCVISD::SplitF64: { 8462 SDValue Op0 = N->getOperand(0); 8463 // If the input to SplitF64 is just BuildPairF64 then the operation is 8464 // redundant. Instead, use BuildPairF64's operands directly. 8465 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8466 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8467 8468 if (Op0->isUndef()) { 8469 SDValue Lo = DAG.getUNDEF(MVT::i32); 8470 SDValue Hi = DAG.getUNDEF(MVT::i32); 8471 return DCI.CombineTo(N, Lo, Hi); 8472 } 8473 8474 SDLoc DL(N); 8475 8476 // It's cheaper to materialise two 32-bit integers than to load a double 8477 // from the constant pool and transfer it to integer registers through the 8478 // stack. 8479 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8480 APInt V = C->getValueAPF().bitcastToAPInt(); 8481 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8482 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8483 return DCI.CombineTo(N, Lo, Hi); 8484 } 8485 8486 // This is a target-specific version of a DAGCombine performed in 8487 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8488 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8489 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8490 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8491 !Op0.getNode()->hasOneUse()) 8492 break; 8493 SDValue NewSplitF64 = 8494 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8495 Op0.getOperand(0)); 8496 SDValue Lo = NewSplitF64.getValue(0); 8497 SDValue Hi = NewSplitF64.getValue(1); 8498 APInt SignBit = APInt::getSignMask(32); 8499 if (Op0.getOpcode() == ISD::FNEG) { 8500 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8501 DAG.getConstant(SignBit, DL, MVT::i32)); 8502 return DCI.CombineTo(N, Lo, NewHi); 8503 } 8504 assert(Op0.getOpcode() == ISD::FABS); 8505 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8506 DAG.getConstant(~SignBit, DL, MVT::i32)); 8507 return DCI.CombineTo(N, Lo, NewHi); 8508 } 8509 case RISCVISD::SLLW: 8510 case RISCVISD::SRAW: 8511 case RISCVISD::SRLW: { 8512 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8513 if (SimplifyDemandedLowBitsHelper(0, 32) || 8514 SimplifyDemandedLowBitsHelper(1, 5)) 8515 return SDValue(N, 0); 8516 8517 break; 8518 } 8519 case ISD::ROTR: 8520 case ISD::ROTL: 8521 case RISCVISD::RORW: 8522 case RISCVISD::ROLW: { 8523 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8524 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8525 if (SimplifyDemandedLowBitsHelper(0, 32) || 8526 SimplifyDemandedLowBitsHelper(1, 5)) 8527 return SDValue(N, 0); 8528 } 8529 8530 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8531 } 8532 case RISCVISD::CLZW: 8533 case RISCVISD::CTZW: { 8534 // Only the lower 32 bits of the first operand are read 8535 if (SimplifyDemandedLowBitsHelper(0, 32)) 8536 return SDValue(N, 0); 8537 break; 8538 } 8539 case RISCVISD::GREV: 8540 case RISCVISD::GORC: { 8541 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8542 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8543 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8544 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8545 return SDValue(N, 0); 8546 8547 return combineGREVI_GORCI(N, DAG); 8548 } 8549 case RISCVISD::GREVW: 8550 case RISCVISD::GORCW: { 8551 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8552 if (SimplifyDemandedLowBitsHelper(0, 32) || 8553 SimplifyDemandedLowBitsHelper(1, 5)) 8554 return SDValue(N, 0); 8555 8556 break; 8557 } 8558 case RISCVISD::SHFL: 8559 case RISCVISD::UNSHFL: { 8560 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8561 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8562 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8563 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8564 return SDValue(N, 0); 8565 8566 break; 8567 } 8568 case RISCVISD::SHFLW: 8569 case RISCVISD::UNSHFLW: { 8570 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8571 if (SimplifyDemandedLowBitsHelper(0, 32) || 8572 SimplifyDemandedLowBitsHelper(1, 4)) 8573 return SDValue(N, 0); 8574 8575 break; 8576 } 8577 case RISCVISD::BCOMPRESSW: 8578 case RISCVISD::BDECOMPRESSW: { 8579 // Only the lower 32 bits of LHS and RHS are read. 8580 if (SimplifyDemandedLowBitsHelper(0, 32) || 8581 SimplifyDemandedLowBitsHelper(1, 32)) 8582 return SDValue(N, 0); 8583 8584 break; 8585 } 8586 case RISCVISD::FSR: 8587 case RISCVISD::FSL: 8588 case RISCVISD::FSRW: 8589 case RISCVISD::FSLW: { 8590 bool IsWInstruction = 8591 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8592 unsigned BitWidth = 8593 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8594 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8595 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8596 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8597 return SDValue(N, 0); 8598 8599 break; 8600 } 8601 case RISCVISD::FMV_X_ANYEXTH: 8602 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8603 SDLoc DL(N); 8604 SDValue Op0 = N->getOperand(0); 8605 MVT VT = N->getSimpleValueType(0); 8606 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8607 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8608 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8609 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8610 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8611 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8612 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8613 assert(Op0.getOperand(0).getValueType() == VT && 8614 "Unexpected value type!"); 8615 return Op0.getOperand(0); 8616 } 8617 8618 // This is a target-specific version of a DAGCombine performed in 8619 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8620 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8621 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8622 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8623 !Op0.getNode()->hasOneUse()) 8624 break; 8625 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8626 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8627 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8628 if (Op0.getOpcode() == ISD::FNEG) 8629 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8630 DAG.getConstant(SignBit, DL, VT)); 8631 8632 assert(Op0.getOpcode() == ISD::FABS); 8633 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8634 DAG.getConstant(~SignBit, DL, VT)); 8635 } 8636 case ISD::ADD: 8637 return performADDCombine(N, DAG, Subtarget); 8638 case ISD::SUB: 8639 return performSUBCombine(N, DAG); 8640 case ISD::AND: 8641 return performANDCombine(N, DAG, Subtarget); 8642 case ISD::OR: 8643 return performORCombine(N, DAG, Subtarget); 8644 case ISD::XOR: 8645 return performXORCombine(N, DAG); 8646 case ISD::FADD: 8647 case ISD::UMAX: 8648 case ISD::UMIN: 8649 case ISD::SMAX: 8650 case ISD::SMIN: 8651 case ISD::FMAXNUM: 8652 case ISD::FMINNUM: 8653 return combineBinOpToReduce(N, DAG); 8654 case ISD::SIGN_EXTEND_INREG: 8655 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8656 case ISD::ZERO_EXTEND: 8657 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8658 // type legalization. This is safe because fp_to_uint produces poison if 8659 // it overflows. 8660 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8661 SDValue Src = N->getOperand(0); 8662 if (Src.getOpcode() == ISD::FP_TO_UINT && 8663 isTypeLegal(Src.getOperand(0).getValueType())) 8664 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8665 Src.getOperand(0)); 8666 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8667 isTypeLegal(Src.getOperand(1).getValueType())) { 8668 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8669 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8670 Src.getOperand(0), Src.getOperand(1)); 8671 DCI.CombineTo(N, Res); 8672 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8673 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8674 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8675 } 8676 } 8677 return SDValue(); 8678 case RISCVISD::SELECT_CC: { 8679 // Transform 8680 SDValue LHS = N->getOperand(0); 8681 SDValue RHS = N->getOperand(1); 8682 SDValue TrueV = N->getOperand(3); 8683 SDValue FalseV = N->getOperand(4); 8684 8685 // If the True and False values are the same, we don't need a select_cc. 8686 if (TrueV == FalseV) 8687 return TrueV; 8688 8689 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8690 if (!ISD::isIntEqualitySetCC(CCVal)) 8691 break; 8692 8693 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8694 // (select_cc X, Y, lt, trueV, falseV) 8695 // Sometimes the setcc is introduced after select_cc has been formed. 8696 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8697 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8698 // If we're looking for eq 0 instead of ne 0, we need to invert the 8699 // condition. 8700 bool Invert = CCVal == ISD::SETEQ; 8701 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8702 if (Invert) 8703 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8704 8705 SDLoc DL(N); 8706 RHS = LHS.getOperand(1); 8707 LHS = LHS.getOperand(0); 8708 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8709 8710 SDValue TargetCC = DAG.getCondCode(CCVal); 8711 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8712 {LHS, RHS, TargetCC, TrueV, FalseV}); 8713 } 8714 8715 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8716 // (select_cc X, Y, eq/ne, trueV, falseV) 8717 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8718 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8719 {LHS.getOperand(0), LHS.getOperand(1), 8720 N->getOperand(2), TrueV, FalseV}); 8721 // (select_cc X, 1, setne, trueV, falseV) -> 8722 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8723 // This can occur when legalizing some floating point comparisons. 8724 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8725 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8726 SDLoc DL(N); 8727 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8728 SDValue TargetCC = DAG.getCondCode(CCVal); 8729 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8730 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8731 {LHS, RHS, TargetCC, TrueV, FalseV}); 8732 } 8733 8734 break; 8735 } 8736 case RISCVISD::BR_CC: { 8737 SDValue LHS = N->getOperand(1); 8738 SDValue RHS = N->getOperand(2); 8739 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8740 if (!ISD::isIntEqualitySetCC(CCVal)) 8741 break; 8742 8743 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8744 // (br_cc X, Y, lt, dest) 8745 // Sometimes the setcc is introduced after br_cc has been formed. 8746 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8747 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8748 // If we're looking for eq 0 instead of ne 0, we need to invert the 8749 // condition. 8750 bool Invert = CCVal == ISD::SETEQ; 8751 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8752 if (Invert) 8753 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8754 8755 SDLoc DL(N); 8756 RHS = LHS.getOperand(1); 8757 LHS = LHS.getOperand(0); 8758 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8759 8760 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8761 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8762 N->getOperand(4)); 8763 } 8764 8765 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8766 // (br_cc X, Y, eq/ne, trueV, falseV) 8767 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8768 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8769 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8770 N->getOperand(3), N->getOperand(4)); 8771 8772 // (br_cc X, 1, setne, br_cc) -> 8773 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8774 // This can occur when legalizing some floating point comparisons. 8775 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8776 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8777 SDLoc DL(N); 8778 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8779 SDValue TargetCC = DAG.getCondCode(CCVal); 8780 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8781 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8782 N->getOperand(0), LHS, RHS, TargetCC, 8783 N->getOperand(4)); 8784 } 8785 break; 8786 } 8787 case ISD::BITREVERSE: 8788 return performBITREVERSECombine(N, DAG, Subtarget); 8789 case ISD::FP_TO_SINT: 8790 case ISD::FP_TO_UINT: 8791 return performFP_TO_INTCombine(N, DCI, Subtarget); 8792 case ISD::FP_TO_SINT_SAT: 8793 case ISD::FP_TO_UINT_SAT: 8794 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8795 case ISD::FCOPYSIGN: { 8796 EVT VT = N->getValueType(0); 8797 if (!VT.isVector()) 8798 break; 8799 // There is a form of VFSGNJ which injects the negated sign of its second 8800 // operand. Try and bubble any FNEG up after the extend/round to produce 8801 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8802 // TRUNC=1. 8803 SDValue In2 = N->getOperand(1); 8804 // Avoid cases where the extend/round has multiple uses, as duplicating 8805 // those is typically more expensive than removing a fneg. 8806 if (!In2.hasOneUse()) 8807 break; 8808 if (In2.getOpcode() != ISD::FP_EXTEND && 8809 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8810 break; 8811 In2 = In2.getOperand(0); 8812 if (In2.getOpcode() != ISD::FNEG) 8813 break; 8814 SDLoc DL(N); 8815 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8816 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8817 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8818 } 8819 case ISD::MGATHER: 8820 case ISD::MSCATTER: 8821 case ISD::VP_GATHER: 8822 case ISD::VP_SCATTER: { 8823 if (!DCI.isBeforeLegalize()) 8824 break; 8825 SDValue Index, ScaleOp; 8826 bool IsIndexScaled = false; 8827 bool IsIndexSigned = false; 8828 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8829 Index = VPGSN->getIndex(); 8830 ScaleOp = VPGSN->getScale(); 8831 IsIndexScaled = VPGSN->isIndexScaled(); 8832 IsIndexSigned = VPGSN->isIndexSigned(); 8833 } else { 8834 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8835 Index = MGSN->getIndex(); 8836 ScaleOp = MGSN->getScale(); 8837 IsIndexScaled = MGSN->isIndexScaled(); 8838 IsIndexSigned = MGSN->isIndexSigned(); 8839 } 8840 EVT IndexVT = Index.getValueType(); 8841 MVT XLenVT = Subtarget.getXLenVT(); 8842 // RISCV indexed loads only support the "unsigned unscaled" addressing 8843 // mode, so anything else must be manually legalized. 8844 bool NeedsIdxLegalization = 8845 IsIndexScaled || 8846 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8847 if (!NeedsIdxLegalization) 8848 break; 8849 8850 SDLoc DL(N); 8851 8852 // Any index legalization should first promote to XLenVT, so we don't lose 8853 // bits when scaling. This may create an illegal index type so we let 8854 // LLVM's legalization take care of the splitting. 8855 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8856 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8857 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8858 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8859 DL, IndexVT, Index); 8860 } 8861 8862 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8863 if (IsIndexScaled && Scale != 1) { 8864 // Manually scale the indices by the element size. 8865 // TODO: Sanitize the scale operand here? 8866 // TODO: For VP nodes, should we use VP_SHL here? 8867 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8868 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8869 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8870 } 8871 8872 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8873 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8874 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8875 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8876 VPGN->getScale(), VPGN->getMask(), 8877 VPGN->getVectorLength()}, 8878 VPGN->getMemOperand(), NewIndexTy); 8879 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8880 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8881 {VPSN->getChain(), VPSN->getValue(), 8882 VPSN->getBasePtr(), Index, VPSN->getScale(), 8883 VPSN->getMask(), VPSN->getVectorLength()}, 8884 VPSN->getMemOperand(), NewIndexTy); 8885 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8886 return DAG.getMaskedGather( 8887 N->getVTList(), MGN->getMemoryVT(), DL, 8888 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8889 MGN->getBasePtr(), Index, MGN->getScale()}, 8890 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8891 const auto *MSN = cast<MaskedScatterSDNode>(N); 8892 return DAG.getMaskedScatter( 8893 N->getVTList(), MSN->getMemoryVT(), DL, 8894 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8895 Index, MSN->getScale()}, 8896 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8897 } 8898 case RISCVISD::SRA_VL: 8899 case RISCVISD::SRL_VL: 8900 case RISCVISD::SHL_VL: { 8901 SDValue ShAmt = N->getOperand(1); 8902 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8903 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8904 SDLoc DL(N); 8905 SDValue VL = N->getOperand(3); 8906 EVT VT = N->getValueType(0); 8907 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8908 ShAmt.getOperand(1), VL); 8909 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8910 N->getOperand(2), N->getOperand(3)); 8911 } 8912 break; 8913 } 8914 case ISD::SRA: 8915 case ISD::SRL: 8916 case ISD::SHL: { 8917 SDValue ShAmt = N->getOperand(1); 8918 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8919 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8920 SDLoc DL(N); 8921 EVT VT = N->getValueType(0); 8922 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8923 ShAmt.getOperand(1), 8924 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8925 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8926 } 8927 break; 8928 } 8929 case RISCVISD::ADD_VL: 8930 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8931 return V; 8932 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8933 case RISCVISD::SUB_VL: 8934 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8935 case RISCVISD::VWADD_W_VL: 8936 case RISCVISD::VWADDU_W_VL: 8937 case RISCVISD::VWSUB_W_VL: 8938 case RISCVISD::VWSUBU_W_VL: 8939 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8940 case RISCVISD::MUL_VL: 8941 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8942 return V; 8943 // Mul is commutative. 8944 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8945 case ISD::STORE: { 8946 auto *Store = cast<StoreSDNode>(N); 8947 SDValue Val = Store->getValue(); 8948 // Combine store of vmv.x.s to vse with VL of 1. 8949 // FIXME: Support FP. 8950 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8951 SDValue Src = Val.getOperand(0); 8952 EVT VecVT = Src.getValueType(); 8953 EVT MemVT = Store->getMemoryVT(); 8954 // The memory VT and the element type must match. 8955 if (VecVT.getVectorElementType() == MemVT) { 8956 SDLoc DL(N); 8957 MVT MaskVT = getMaskTypeFor(VecVT); 8958 return DAG.getStoreVP( 8959 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8960 DAG.getConstant(1, DL, MaskVT), 8961 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8962 Store->getMemOperand(), Store->getAddressingMode(), 8963 Store->isTruncatingStore(), /*IsCompress*/ false); 8964 } 8965 } 8966 8967 break; 8968 } 8969 case ISD::SPLAT_VECTOR: { 8970 EVT VT = N->getValueType(0); 8971 // Only perform this combine on legal MVT types. 8972 if (!isTypeLegal(VT)) 8973 break; 8974 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8975 DAG, Subtarget)) 8976 return Gather; 8977 break; 8978 } 8979 case RISCVISD::VMV_V_X_VL: { 8980 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8981 // scalar input. 8982 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8983 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8984 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8985 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8986 return SDValue(N, 0); 8987 8988 break; 8989 } 8990 case ISD::INTRINSIC_WO_CHAIN: { 8991 unsigned IntNo = N->getConstantOperandVal(0); 8992 switch (IntNo) { 8993 // By default we do not combine any intrinsic. 8994 default: 8995 return SDValue(); 8996 case Intrinsic::riscv_vcpop: 8997 case Intrinsic::riscv_vcpop_mask: 8998 case Intrinsic::riscv_vfirst: 8999 case Intrinsic::riscv_vfirst_mask: { 9000 SDValue VL = N->getOperand(2); 9001 if (IntNo == Intrinsic::riscv_vcpop_mask || 9002 IntNo == Intrinsic::riscv_vfirst_mask) 9003 VL = N->getOperand(3); 9004 if (!isNullConstant(VL)) 9005 return SDValue(); 9006 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9007 SDLoc DL(N); 9008 EVT VT = N->getValueType(0); 9009 if (IntNo == Intrinsic::riscv_vfirst || 9010 IntNo == Intrinsic::riscv_vfirst_mask) 9011 return DAG.getConstant(-1, DL, VT); 9012 return DAG.getConstant(0, DL, VT); 9013 } 9014 } 9015 } 9016 } 9017 9018 return SDValue(); 9019 } 9020 9021 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9022 const SDNode *N, CombineLevel Level) const { 9023 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9024 // materialised in fewer instructions than `(OP _, c1)`: 9025 // 9026 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9027 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9028 SDValue N0 = N->getOperand(0); 9029 EVT Ty = N0.getValueType(); 9030 if (Ty.isScalarInteger() && 9031 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9032 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9033 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9034 if (C1 && C2) { 9035 const APInt &C1Int = C1->getAPIntValue(); 9036 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9037 9038 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9039 // and the combine should happen, to potentially allow further combines 9040 // later. 9041 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9042 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9043 return true; 9044 9045 // We can materialise `c1` in an add immediate, so it's "free", and the 9046 // combine should be prevented. 9047 if (C1Int.getMinSignedBits() <= 64 && 9048 isLegalAddImmediate(C1Int.getSExtValue())) 9049 return false; 9050 9051 // Neither constant will fit into an immediate, so find materialisation 9052 // costs. 9053 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9054 Subtarget.getFeatureBits(), 9055 /*CompressionCost*/true); 9056 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9057 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9058 /*CompressionCost*/true); 9059 9060 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9061 // combine should be prevented. 9062 if (C1Cost < ShiftedC1Cost) 9063 return false; 9064 } 9065 } 9066 return true; 9067 } 9068 9069 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9070 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9071 TargetLoweringOpt &TLO) const { 9072 // Delay this optimization as late as possible. 9073 if (!TLO.LegalOps) 9074 return false; 9075 9076 EVT VT = Op.getValueType(); 9077 if (VT.isVector()) 9078 return false; 9079 9080 // Only handle AND for now. 9081 if (Op.getOpcode() != ISD::AND) 9082 return false; 9083 9084 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9085 if (!C) 9086 return false; 9087 9088 const APInt &Mask = C->getAPIntValue(); 9089 9090 // Clear all non-demanded bits initially. 9091 APInt ShrunkMask = Mask & DemandedBits; 9092 9093 // Try to make a smaller immediate by setting undemanded bits. 9094 9095 APInt ExpandedMask = Mask | ~DemandedBits; 9096 9097 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9098 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9099 }; 9100 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9101 if (NewMask == Mask) 9102 return true; 9103 SDLoc DL(Op); 9104 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9105 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9106 return TLO.CombineTo(Op, NewOp); 9107 }; 9108 9109 // If the shrunk mask fits in sign extended 12 bits, let the target 9110 // independent code apply it. 9111 if (ShrunkMask.isSignedIntN(12)) 9112 return false; 9113 9114 // Preserve (and X, 0xffff) when zext.h is supported. 9115 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9116 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9117 if (IsLegalMask(NewMask)) 9118 return UseMask(NewMask); 9119 } 9120 9121 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9122 if (VT == MVT::i64) { 9123 APInt NewMask = APInt(64, 0xffffffff); 9124 if (IsLegalMask(NewMask)) 9125 return UseMask(NewMask); 9126 } 9127 9128 // For the remaining optimizations, we need to be able to make a negative 9129 // number through a combination of mask and undemanded bits. 9130 if (!ExpandedMask.isNegative()) 9131 return false; 9132 9133 // What is the fewest number of bits we need to represent the negative number. 9134 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9135 9136 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9137 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9138 APInt NewMask = ShrunkMask; 9139 if (MinSignedBits <= 12) 9140 NewMask.setBitsFrom(11); 9141 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9142 NewMask.setBitsFrom(31); 9143 else 9144 return false; 9145 9146 // Check that our new mask is a subset of the demanded mask. 9147 assert(IsLegalMask(NewMask)); 9148 return UseMask(NewMask); 9149 } 9150 9151 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9152 static const uint64_t GREVMasks[] = { 9153 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9154 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9155 9156 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9157 unsigned Shift = 1 << Stage; 9158 if (ShAmt & Shift) { 9159 uint64_t Mask = GREVMasks[Stage]; 9160 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9161 if (IsGORC) 9162 Res |= x; 9163 x = Res; 9164 } 9165 } 9166 9167 return x; 9168 } 9169 9170 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9171 KnownBits &Known, 9172 const APInt &DemandedElts, 9173 const SelectionDAG &DAG, 9174 unsigned Depth) const { 9175 unsigned BitWidth = Known.getBitWidth(); 9176 unsigned Opc = Op.getOpcode(); 9177 assert((Opc >= ISD::BUILTIN_OP_END || 9178 Opc == ISD::INTRINSIC_WO_CHAIN || 9179 Opc == ISD::INTRINSIC_W_CHAIN || 9180 Opc == ISD::INTRINSIC_VOID) && 9181 "Should use MaskedValueIsZero if you don't know whether Op" 9182 " is a target node!"); 9183 9184 Known.resetAll(); 9185 switch (Opc) { 9186 default: break; 9187 case RISCVISD::SELECT_CC: { 9188 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9189 // If we don't know any bits, early out. 9190 if (Known.isUnknown()) 9191 break; 9192 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9193 9194 // Only known if known in both the LHS and RHS. 9195 Known = KnownBits::commonBits(Known, Known2); 9196 break; 9197 } 9198 case RISCVISD::REMUW: { 9199 KnownBits Known2; 9200 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9201 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9202 // We only care about the lower 32 bits. 9203 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9204 // Restore the original width by sign extending. 9205 Known = Known.sext(BitWidth); 9206 break; 9207 } 9208 case RISCVISD::DIVUW: { 9209 KnownBits Known2; 9210 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9211 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9212 // We only care about the lower 32 bits. 9213 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9214 // Restore the original width by sign extending. 9215 Known = Known.sext(BitWidth); 9216 break; 9217 } 9218 case RISCVISD::CTZW: { 9219 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9220 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9221 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9222 Known.Zero.setBitsFrom(LowBits); 9223 break; 9224 } 9225 case RISCVISD::CLZW: { 9226 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9227 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9228 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9229 Known.Zero.setBitsFrom(LowBits); 9230 break; 9231 } 9232 case RISCVISD::GREV: 9233 case RISCVISD::GORC: { 9234 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9235 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9236 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9237 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9238 // To compute zeros, we need to invert the value and invert it back after. 9239 Known.Zero = 9240 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9241 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9242 } 9243 break; 9244 } 9245 case RISCVISD::READ_VLENB: { 9246 // If we know the minimum VLen from Zvl extensions, we can use that to 9247 // determine the trailing zeros of VLENB. 9248 // FIXME: Limit to 128 bit vectors until we have more testing. 9249 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9250 if (MinVLenB > 0) 9251 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9252 // We assume VLENB is no more than 65536 / 8 bytes. 9253 Known.Zero.setBitsFrom(14); 9254 break; 9255 } 9256 case ISD::INTRINSIC_W_CHAIN: 9257 case ISD::INTRINSIC_WO_CHAIN: { 9258 unsigned IntNo = 9259 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9260 switch (IntNo) { 9261 default: 9262 // We can't do anything for most intrinsics. 9263 break; 9264 case Intrinsic::riscv_vsetvli: 9265 case Intrinsic::riscv_vsetvlimax: 9266 case Intrinsic::riscv_vsetvli_opt: 9267 case Intrinsic::riscv_vsetvlimax_opt: 9268 // Assume that VL output is positive and would fit in an int32_t. 9269 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9270 if (BitWidth >= 32) 9271 Known.Zero.setBitsFrom(31); 9272 break; 9273 } 9274 break; 9275 } 9276 } 9277 } 9278 9279 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9280 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9281 unsigned Depth) const { 9282 switch (Op.getOpcode()) { 9283 default: 9284 break; 9285 case RISCVISD::SELECT_CC: { 9286 unsigned Tmp = 9287 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9288 if (Tmp == 1) return 1; // Early out. 9289 unsigned Tmp2 = 9290 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9291 return std::min(Tmp, Tmp2); 9292 } 9293 case RISCVISD::SLLW: 9294 case RISCVISD::SRAW: 9295 case RISCVISD::SRLW: 9296 case RISCVISD::DIVW: 9297 case RISCVISD::DIVUW: 9298 case RISCVISD::REMUW: 9299 case RISCVISD::ROLW: 9300 case RISCVISD::RORW: 9301 case RISCVISD::GREVW: 9302 case RISCVISD::GORCW: 9303 case RISCVISD::FSLW: 9304 case RISCVISD::FSRW: 9305 case RISCVISD::SHFLW: 9306 case RISCVISD::UNSHFLW: 9307 case RISCVISD::BCOMPRESSW: 9308 case RISCVISD::BDECOMPRESSW: 9309 case RISCVISD::BFPW: 9310 case RISCVISD::FCVT_W_RV64: 9311 case RISCVISD::FCVT_WU_RV64: 9312 case RISCVISD::STRICT_FCVT_W_RV64: 9313 case RISCVISD::STRICT_FCVT_WU_RV64: 9314 // TODO: As the result is sign-extended, this is conservatively correct. A 9315 // more precise answer could be calculated for SRAW depending on known 9316 // bits in the shift amount. 9317 return 33; 9318 case RISCVISD::SHFL: 9319 case RISCVISD::UNSHFL: { 9320 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9321 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9322 // will stay within the upper 32 bits. If there were more than 32 sign bits 9323 // before there will be at least 33 sign bits after. 9324 if (Op.getValueType() == MVT::i64 && 9325 isa<ConstantSDNode>(Op.getOperand(1)) && 9326 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9327 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9328 if (Tmp > 32) 9329 return 33; 9330 } 9331 break; 9332 } 9333 case RISCVISD::VMV_X_S: { 9334 // The number of sign bits of the scalar result is computed by obtaining the 9335 // element type of the input vector operand, subtracting its width from the 9336 // XLEN, and then adding one (sign bit within the element type). If the 9337 // element type is wider than XLen, the least-significant XLEN bits are 9338 // taken. 9339 unsigned XLen = Subtarget.getXLen(); 9340 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9341 if (EltBits <= XLen) 9342 return XLen - EltBits + 1; 9343 break; 9344 } 9345 } 9346 9347 return 1; 9348 } 9349 9350 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9351 MachineBasicBlock *BB) { 9352 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9353 9354 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9355 // Should the count have wrapped while it was being read, we need to try 9356 // again. 9357 // ... 9358 // read: 9359 // rdcycleh x3 # load high word of cycle 9360 // rdcycle x2 # load low word of cycle 9361 // rdcycleh x4 # load high word of cycle 9362 // bne x3, x4, read # check if high word reads match, otherwise try again 9363 // ... 9364 9365 MachineFunction &MF = *BB->getParent(); 9366 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9367 MachineFunction::iterator It = ++BB->getIterator(); 9368 9369 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9370 MF.insert(It, LoopMBB); 9371 9372 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9373 MF.insert(It, DoneMBB); 9374 9375 // Transfer the remainder of BB and its successor edges to DoneMBB. 9376 DoneMBB->splice(DoneMBB->begin(), BB, 9377 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9378 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9379 9380 BB->addSuccessor(LoopMBB); 9381 9382 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9383 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9384 Register LoReg = MI.getOperand(0).getReg(); 9385 Register HiReg = MI.getOperand(1).getReg(); 9386 DebugLoc DL = MI.getDebugLoc(); 9387 9388 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9389 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9390 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9391 .addReg(RISCV::X0); 9392 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9393 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9394 .addReg(RISCV::X0); 9395 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9396 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9397 .addReg(RISCV::X0); 9398 9399 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9400 .addReg(HiReg) 9401 .addReg(ReadAgainReg) 9402 .addMBB(LoopMBB); 9403 9404 LoopMBB->addSuccessor(LoopMBB); 9405 LoopMBB->addSuccessor(DoneMBB); 9406 9407 MI.eraseFromParent(); 9408 9409 return DoneMBB; 9410 } 9411 9412 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9413 MachineBasicBlock *BB) { 9414 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9415 9416 MachineFunction &MF = *BB->getParent(); 9417 DebugLoc DL = MI.getDebugLoc(); 9418 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9419 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9420 Register LoReg = MI.getOperand(0).getReg(); 9421 Register HiReg = MI.getOperand(1).getReg(); 9422 Register SrcReg = MI.getOperand(2).getReg(); 9423 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9424 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9425 9426 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9427 RI); 9428 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9429 MachineMemOperand *MMOLo = 9430 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9431 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9432 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9433 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9434 .addFrameIndex(FI) 9435 .addImm(0) 9436 .addMemOperand(MMOLo); 9437 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9438 .addFrameIndex(FI) 9439 .addImm(4) 9440 .addMemOperand(MMOHi); 9441 MI.eraseFromParent(); // The pseudo instruction is gone now. 9442 return BB; 9443 } 9444 9445 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9446 MachineBasicBlock *BB) { 9447 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9448 "Unexpected instruction"); 9449 9450 MachineFunction &MF = *BB->getParent(); 9451 DebugLoc DL = MI.getDebugLoc(); 9452 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9453 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9454 Register DstReg = MI.getOperand(0).getReg(); 9455 Register LoReg = MI.getOperand(1).getReg(); 9456 Register HiReg = MI.getOperand(2).getReg(); 9457 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9458 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9459 9460 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9461 MachineMemOperand *MMOLo = 9462 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9463 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9464 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9465 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9466 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9467 .addFrameIndex(FI) 9468 .addImm(0) 9469 .addMemOperand(MMOLo); 9470 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9471 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9472 .addFrameIndex(FI) 9473 .addImm(4) 9474 .addMemOperand(MMOHi); 9475 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9476 MI.eraseFromParent(); // The pseudo instruction is gone now. 9477 return BB; 9478 } 9479 9480 static bool isSelectPseudo(MachineInstr &MI) { 9481 switch (MI.getOpcode()) { 9482 default: 9483 return false; 9484 case RISCV::Select_GPR_Using_CC_GPR: 9485 case RISCV::Select_FPR16_Using_CC_GPR: 9486 case RISCV::Select_FPR32_Using_CC_GPR: 9487 case RISCV::Select_FPR64_Using_CC_GPR: 9488 return true; 9489 } 9490 } 9491 9492 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9493 unsigned RelOpcode, unsigned EqOpcode, 9494 const RISCVSubtarget &Subtarget) { 9495 DebugLoc DL = MI.getDebugLoc(); 9496 Register DstReg = MI.getOperand(0).getReg(); 9497 Register Src1Reg = MI.getOperand(1).getReg(); 9498 Register Src2Reg = MI.getOperand(2).getReg(); 9499 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9500 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9501 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9502 9503 // Save the current FFLAGS. 9504 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9505 9506 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9507 .addReg(Src1Reg) 9508 .addReg(Src2Reg); 9509 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9510 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9511 9512 // Restore the FFLAGS. 9513 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9514 .addReg(SavedFFlags, RegState::Kill); 9515 9516 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9517 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9518 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9519 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9520 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9521 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9522 9523 // Erase the pseudoinstruction. 9524 MI.eraseFromParent(); 9525 return BB; 9526 } 9527 9528 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9529 MachineBasicBlock *BB, 9530 const RISCVSubtarget &Subtarget) { 9531 // To "insert" Select_* instructions, we actually have to insert the triangle 9532 // control-flow pattern. The incoming instructions know the destination vreg 9533 // to set, the condition code register to branch on, the true/false values to 9534 // select between, and the condcode to use to select the appropriate branch. 9535 // 9536 // We produce the following control flow: 9537 // HeadMBB 9538 // | \ 9539 // | IfFalseMBB 9540 // | / 9541 // TailMBB 9542 // 9543 // When we find a sequence of selects we attempt to optimize their emission 9544 // by sharing the control flow. Currently we only handle cases where we have 9545 // multiple selects with the exact same condition (same LHS, RHS and CC). 9546 // The selects may be interleaved with other instructions if the other 9547 // instructions meet some requirements we deem safe: 9548 // - They are debug instructions. Otherwise, 9549 // - They do not have side-effects, do not access memory and their inputs do 9550 // not depend on the results of the select pseudo-instructions. 9551 // The TrueV/FalseV operands of the selects cannot depend on the result of 9552 // previous selects in the sequence. 9553 // These conditions could be further relaxed. See the X86 target for a 9554 // related approach and more information. 9555 Register LHS = MI.getOperand(1).getReg(); 9556 Register RHS = MI.getOperand(2).getReg(); 9557 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9558 9559 SmallVector<MachineInstr *, 4> SelectDebugValues; 9560 SmallSet<Register, 4> SelectDests; 9561 SelectDests.insert(MI.getOperand(0).getReg()); 9562 9563 MachineInstr *LastSelectPseudo = &MI; 9564 9565 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9566 SequenceMBBI != E; ++SequenceMBBI) { 9567 if (SequenceMBBI->isDebugInstr()) 9568 continue; 9569 if (isSelectPseudo(*SequenceMBBI)) { 9570 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9571 SequenceMBBI->getOperand(2).getReg() != RHS || 9572 SequenceMBBI->getOperand(3).getImm() != CC || 9573 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9574 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9575 break; 9576 LastSelectPseudo = &*SequenceMBBI; 9577 SequenceMBBI->collectDebugValues(SelectDebugValues); 9578 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9579 } else { 9580 if (SequenceMBBI->hasUnmodeledSideEffects() || 9581 SequenceMBBI->mayLoadOrStore()) 9582 break; 9583 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9584 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9585 })) 9586 break; 9587 } 9588 } 9589 9590 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9591 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9592 DebugLoc DL = MI.getDebugLoc(); 9593 MachineFunction::iterator I = ++BB->getIterator(); 9594 9595 MachineBasicBlock *HeadMBB = BB; 9596 MachineFunction *F = BB->getParent(); 9597 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9598 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9599 9600 F->insert(I, IfFalseMBB); 9601 F->insert(I, TailMBB); 9602 9603 // Transfer debug instructions associated with the selects to TailMBB. 9604 for (MachineInstr *DebugInstr : SelectDebugValues) { 9605 TailMBB->push_back(DebugInstr->removeFromParent()); 9606 } 9607 9608 // Move all instructions after the sequence to TailMBB. 9609 TailMBB->splice(TailMBB->end(), HeadMBB, 9610 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9611 // Update machine-CFG edges by transferring all successors of the current 9612 // block to the new block which will contain the Phi nodes for the selects. 9613 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9614 // Set the successors for HeadMBB. 9615 HeadMBB->addSuccessor(IfFalseMBB); 9616 HeadMBB->addSuccessor(TailMBB); 9617 9618 // Insert appropriate branch. 9619 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9620 .addReg(LHS) 9621 .addReg(RHS) 9622 .addMBB(TailMBB); 9623 9624 // IfFalseMBB just falls through to TailMBB. 9625 IfFalseMBB->addSuccessor(TailMBB); 9626 9627 // Create PHIs for all of the select pseudo-instructions. 9628 auto SelectMBBI = MI.getIterator(); 9629 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9630 auto InsertionPoint = TailMBB->begin(); 9631 while (SelectMBBI != SelectEnd) { 9632 auto Next = std::next(SelectMBBI); 9633 if (isSelectPseudo(*SelectMBBI)) { 9634 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9635 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9636 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9637 .addReg(SelectMBBI->getOperand(4).getReg()) 9638 .addMBB(HeadMBB) 9639 .addReg(SelectMBBI->getOperand(5).getReg()) 9640 .addMBB(IfFalseMBB); 9641 SelectMBBI->eraseFromParent(); 9642 } 9643 SelectMBBI = Next; 9644 } 9645 9646 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9647 return TailMBB; 9648 } 9649 9650 MachineBasicBlock * 9651 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9652 MachineBasicBlock *BB) const { 9653 switch (MI.getOpcode()) { 9654 default: 9655 llvm_unreachable("Unexpected instr type to insert"); 9656 case RISCV::ReadCycleWide: 9657 assert(!Subtarget.is64Bit() && 9658 "ReadCycleWrite is only to be used on riscv32"); 9659 return emitReadCycleWidePseudo(MI, BB); 9660 case RISCV::Select_GPR_Using_CC_GPR: 9661 case RISCV::Select_FPR16_Using_CC_GPR: 9662 case RISCV::Select_FPR32_Using_CC_GPR: 9663 case RISCV::Select_FPR64_Using_CC_GPR: 9664 return emitSelectPseudo(MI, BB, Subtarget); 9665 case RISCV::BuildPairF64Pseudo: 9666 return emitBuildPairF64Pseudo(MI, BB); 9667 case RISCV::SplitF64Pseudo: 9668 return emitSplitF64Pseudo(MI, BB); 9669 case RISCV::PseudoQuietFLE_H: 9670 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9671 case RISCV::PseudoQuietFLT_H: 9672 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9673 case RISCV::PseudoQuietFLE_S: 9674 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9675 case RISCV::PseudoQuietFLT_S: 9676 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9677 case RISCV::PseudoQuietFLE_D: 9678 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9679 case RISCV::PseudoQuietFLT_D: 9680 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9681 } 9682 } 9683 9684 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9685 SDNode *Node) const { 9686 // Add FRM dependency to any instructions with dynamic rounding mode. 9687 unsigned Opc = MI.getOpcode(); 9688 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9689 if (Idx < 0) 9690 return; 9691 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9692 return; 9693 // If the instruction already reads FRM, don't add another read. 9694 if (MI.readsRegister(RISCV::FRM)) 9695 return; 9696 MI.addOperand( 9697 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9698 } 9699 9700 // Calling Convention Implementation. 9701 // The expectations for frontend ABI lowering vary from target to target. 9702 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9703 // details, but this is a longer term goal. For now, we simply try to keep the 9704 // role of the frontend as simple and well-defined as possible. The rules can 9705 // be summarised as: 9706 // * Never split up large scalar arguments. We handle them here. 9707 // * If a hardfloat calling convention is being used, and the struct may be 9708 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9709 // available, then pass as two separate arguments. If either the GPRs or FPRs 9710 // are exhausted, then pass according to the rule below. 9711 // * If a struct could never be passed in registers or directly in a stack 9712 // slot (as it is larger than 2*XLEN and the floating point rules don't 9713 // apply), then pass it using a pointer with the byval attribute. 9714 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9715 // word-sized array or a 2*XLEN scalar (depending on alignment). 9716 // * The frontend can determine whether a struct is returned by reference or 9717 // not based on its size and fields. If it will be returned by reference, the 9718 // frontend must modify the prototype so a pointer with the sret annotation is 9719 // passed as the first argument. This is not necessary for large scalar 9720 // returns. 9721 // * Struct return values and varargs should be coerced to structs containing 9722 // register-size fields in the same situations they would be for fixed 9723 // arguments. 9724 9725 static const MCPhysReg ArgGPRs[] = { 9726 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9727 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9728 }; 9729 static const MCPhysReg ArgFPR16s[] = { 9730 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9731 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9732 }; 9733 static const MCPhysReg ArgFPR32s[] = { 9734 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9735 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9736 }; 9737 static const MCPhysReg ArgFPR64s[] = { 9738 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9739 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9740 }; 9741 // This is an interim calling convention and it may be changed in the future. 9742 static const MCPhysReg ArgVRs[] = { 9743 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9744 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9745 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9746 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9747 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9748 RISCV::V20M2, RISCV::V22M2}; 9749 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9750 RISCV::V20M4}; 9751 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9752 9753 // Pass a 2*XLEN argument that has been split into two XLEN values through 9754 // registers or the stack as necessary. 9755 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9756 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9757 MVT ValVT2, MVT LocVT2, 9758 ISD::ArgFlagsTy ArgFlags2) { 9759 unsigned XLenInBytes = XLen / 8; 9760 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9761 // At least one half can be passed via register. 9762 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9763 VA1.getLocVT(), CCValAssign::Full)); 9764 } else { 9765 // Both halves must be passed on the stack, with proper alignment. 9766 Align StackAlign = 9767 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9768 State.addLoc( 9769 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9770 State.AllocateStack(XLenInBytes, StackAlign), 9771 VA1.getLocVT(), CCValAssign::Full)); 9772 State.addLoc(CCValAssign::getMem( 9773 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9774 LocVT2, CCValAssign::Full)); 9775 return false; 9776 } 9777 9778 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9779 // The second half can also be passed via register. 9780 State.addLoc( 9781 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9782 } else { 9783 // The second half is passed via the stack, without additional alignment. 9784 State.addLoc(CCValAssign::getMem( 9785 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9786 LocVT2, CCValAssign::Full)); 9787 } 9788 9789 return false; 9790 } 9791 9792 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9793 Optional<unsigned> FirstMaskArgument, 9794 CCState &State, const RISCVTargetLowering &TLI) { 9795 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9796 if (RC == &RISCV::VRRegClass) { 9797 // Assign the first mask argument to V0. 9798 // This is an interim calling convention and it may be changed in the 9799 // future. 9800 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9801 return State.AllocateReg(RISCV::V0); 9802 return State.AllocateReg(ArgVRs); 9803 } 9804 if (RC == &RISCV::VRM2RegClass) 9805 return State.AllocateReg(ArgVRM2s); 9806 if (RC == &RISCV::VRM4RegClass) 9807 return State.AllocateReg(ArgVRM4s); 9808 if (RC == &RISCV::VRM8RegClass) 9809 return State.AllocateReg(ArgVRM8s); 9810 llvm_unreachable("Unhandled register class for ValueType"); 9811 } 9812 9813 // Implements the RISC-V calling convention. Returns true upon failure. 9814 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9815 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9816 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9817 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9818 Optional<unsigned> FirstMaskArgument) { 9819 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9820 assert(XLen == 32 || XLen == 64); 9821 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9822 9823 // Any return value split in to more than two values can't be returned 9824 // directly. Vectors are returned via the available vector registers. 9825 if (!LocVT.isVector() && IsRet && ValNo > 1) 9826 return true; 9827 9828 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9829 // variadic argument, or if no F16/F32 argument registers are available. 9830 bool UseGPRForF16_F32 = true; 9831 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9832 // variadic argument, or if no F64 argument registers are available. 9833 bool UseGPRForF64 = true; 9834 9835 switch (ABI) { 9836 default: 9837 llvm_unreachable("Unexpected ABI"); 9838 case RISCVABI::ABI_ILP32: 9839 case RISCVABI::ABI_LP64: 9840 break; 9841 case RISCVABI::ABI_ILP32F: 9842 case RISCVABI::ABI_LP64F: 9843 UseGPRForF16_F32 = !IsFixed; 9844 break; 9845 case RISCVABI::ABI_ILP32D: 9846 case RISCVABI::ABI_LP64D: 9847 UseGPRForF16_F32 = !IsFixed; 9848 UseGPRForF64 = !IsFixed; 9849 break; 9850 } 9851 9852 // FPR16, FPR32, and FPR64 alias each other. 9853 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9854 UseGPRForF16_F32 = true; 9855 UseGPRForF64 = true; 9856 } 9857 9858 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9859 // similar local variables rather than directly checking against the target 9860 // ABI. 9861 9862 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9863 LocVT = XLenVT; 9864 LocInfo = CCValAssign::BCvt; 9865 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9866 LocVT = MVT::i64; 9867 LocInfo = CCValAssign::BCvt; 9868 } 9869 9870 // If this is a variadic argument, the RISC-V calling convention requires 9871 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9872 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9873 // be used regardless of whether the original argument was split during 9874 // legalisation or not. The argument will not be passed by registers if the 9875 // original type is larger than 2*XLEN, so the register alignment rule does 9876 // not apply. 9877 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9878 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9879 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9880 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9881 // Skip 'odd' register if necessary. 9882 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9883 State.AllocateReg(ArgGPRs); 9884 } 9885 9886 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9887 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9888 State.getPendingArgFlags(); 9889 9890 assert(PendingLocs.size() == PendingArgFlags.size() && 9891 "PendingLocs and PendingArgFlags out of sync"); 9892 9893 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9894 // registers are exhausted. 9895 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9896 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9897 "Can't lower f64 if it is split"); 9898 // Depending on available argument GPRS, f64 may be passed in a pair of 9899 // GPRs, split between a GPR and the stack, or passed completely on the 9900 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9901 // cases. 9902 Register Reg = State.AllocateReg(ArgGPRs); 9903 LocVT = MVT::i32; 9904 if (!Reg) { 9905 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9906 State.addLoc( 9907 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9908 return false; 9909 } 9910 if (!State.AllocateReg(ArgGPRs)) 9911 State.AllocateStack(4, Align(4)); 9912 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9913 return false; 9914 } 9915 9916 // Fixed-length vectors are located in the corresponding scalable-vector 9917 // container types. 9918 if (ValVT.isFixedLengthVector()) 9919 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9920 9921 // Split arguments might be passed indirectly, so keep track of the pending 9922 // values. Split vectors are passed via a mix of registers and indirectly, so 9923 // treat them as we would any other argument. 9924 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9925 LocVT = XLenVT; 9926 LocInfo = CCValAssign::Indirect; 9927 PendingLocs.push_back( 9928 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9929 PendingArgFlags.push_back(ArgFlags); 9930 if (!ArgFlags.isSplitEnd()) { 9931 return false; 9932 } 9933 } 9934 9935 // If the split argument only had two elements, it should be passed directly 9936 // in registers or on the stack. 9937 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9938 PendingLocs.size() <= 2) { 9939 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9940 // Apply the normal calling convention rules to the first half of the 9941 // split argument. 9942 CCValAssign VA = PendingLocs[0]; 9943 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9944 PendingLocs.clear(); 9945 PendingArgFlags.clear(); 9946 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9947 ArgFlags); 9948 } 9949 9950 // Allocate to a register if possible, or else a stack slot. 9951 Register Reg; 9952 unsigned StoreSizeBytes = XLen / 8; 9953 Align StackAlign = Align(XLen / 8); 9954 9955 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9956 Reg = State.AllocateReg(ArgFPR16s); 9957 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9958 Reg = State.AllocateReg(ArgFPR32s); 9959 else if (ValVT == MVT::f64 && !UseGPRForF64) 9960 Reg = State.AllocateReg(ArgFPR64s); 9961 else if (ValVT.isVector()) { 9962 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9963 if (!Reg) { 9964 // For return values, the vector must be passed fully via registers or 9965 // via the stack. 9966 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9967 // but we're using all of them. 9968 if (IsRet) 9969 return true; 9970 // Try using a GPR to pass the address 9971 if ((Reg = State.AllocateReg(ArgGPRs))) { 9972 LocVT = XLenVT; 9973 LocInfo = CCValAssign::Indirect; 9974 } else if (ValVT.isScalableVector()) { 9975 LocVT = XLenVT; 9976 LocInfo = CCValAssign::Indirect; 9977 } else { 9978 // Pass fixed-length vectors on the stack. 9979 LocVT = ValVT; 9980 StoreSizeBytes = ValVT.getStoreSize(); 9981 // Align vectors to their element sizes, being careful for vXi1 9982 // vectors. 9983 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9984 } 9985 } 9986 } else { 9987 Reg = State.AllocateReg(ArgGPRs); 9988 } 9989 9990 unsigned StackOffset = 9991 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9992 9993 // If we reach this point and PendingLocs is non-empty, we must be at the 9994 // end of a split argument that must be passed indirectly. 9995 if (!PendingLocs.empty()) { 9996 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9997 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9998 9999 for (auto &It : PendingLocs) { 10000 if (Reg) 10001 It.convertToReg(Reg); 10002 else 10003 It.convertToMem(StackOffset); 10004 State.addLoc(It); 10005 } 10006 PendingLocs.clear(); 10007 PendingArgFlags.clear(); 10008 return false; 10009 } 10010 10011 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10012 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10013 "Expected an XLenVT or vector types at this stage"); 10014 10015 if (Reg) { 10016 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10017 return false; 10018 } 10019 10020 // When a floating-point value is passed on the stack, no bit-conversion is 10021 // needed. 10022 if (ValVT.isFloatingPoint()) { 10023 LocVT = ValVT; 10024 LocInfo = CCValAssign::Full; 10025 } 10026 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10027 return false; 10028 } 10029 10030 template <typename ArgTy> 10031 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10032 for (const auto &ArgIdx : enumerate(Args)) { 10033 MVT ArgVT = ArgIdx.value().VT; 10034 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10035 return ArgIdx.index(); 10036 } 10037 return None; 10038 } 10039 10040 void RISCVTargetLowering::analyzeInputArgs( 10041 MachineFunction &MF, CCState &CCInfo, 10042 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10043 RISCVCCAssignFn Fn) const { 10044 unsigned NumArgs = Ins.size(); 10045 FunctionType *FType = MF.getFunction().getFunctionType(); 10046 10047 Optional<unsigned> FirstMaskArgument; 10048 if (Subtarget.hasVInstructions()) 10049 FirstMaskArgument = preAssignMask(Ins); 10050 10051 for (unsigned i = 0; i != NumArgs; ++i) { 10052 MVT ArgVT = Ins[i].VT; 10053 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10054 10055 Type *ArgTy = nullptr; 10056 if (IsRet) 10057 ArgTy = FType->getReturnType(); 10058 else if (Ins[i].isOrigArg()) 10059 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10060 10061 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10062 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10063 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10064 FirstMaskArgument)) { 10065 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10066 << EVT(ArgVT).getEVTString() << '\n'); 10067 llvm_unreachable(nullptr); 10068 } 10069 } 10070 } 10071 10072 void RISCVTargetLowering::analyzeOutputArgs( 10073 MachineFunction &MF, CCState &CCInfo, 10074 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10075 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10076 unsigned NumArgs = Outs.size(); 10077 10078 Optional<unsigned> FirstMaskArgument; 10079 if (Subtarget.hasVInstructions()) 10080 FirstMaskArgument = preAssignMask(Outs); 10081 10082 for (unsigned i = 0; i != NumArgs; i++) { 10083 MVT ArgVT = Outs[i].VT; 10084 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10085 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10086 10087 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10088 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10089 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10090 FirstMaskArgument)) { 10091 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10092 << EVT(ArgVT).getEVTString() << "\n"); 10093 llvm_unreachable(nullptr); 10094 } 10095 } 10096 } 10097 10098 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10099 // values. 10100 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10101 const CCValAssign &VA, const SDLoc &DL, 10102 const RISCVSubtarget &Subtarget) { 10103 switch (VA.getLocInfo()) { 10104 default: 10105 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10106 case CCValAssign::Full: 10107 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10108 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10109 break; 10110 case CCValAssign::BCvt: 10111 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10112 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10113 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10114 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10115 else 10116 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10117 break; 10118 } 10119 return Val; 10120 } 10121 10122 // The caller is responsible for loading the full value if the argument is 10123 // passed with CCValAssign::Indirect. 10124 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10125 const CCValAssign &VA, const SDLoc &DL, 10126 const RISCVTargetLowering &TLI) { 10127 MachineFunction &MF = DAG.getMachineFunction(); 10128 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10129 EVT LocVT = VA.getLocVT(); 10130 SDValue Val; 10131 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10132 Register VReg = RegInfo.createVirtualRegister(RC); 10133 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10134 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10135 10136 if (VA.getLocInfo() == CCValAssign::Indirect) 10137 return Val; 10138 10139 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10140 } 10141 10142 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10143 const CCValAssign &VA, const SDLoc &DL, 10144 const RISCVSubtarget &Subtarget) { 10145 EVT LocVT = VA.getLocVT(); 10146 10147 switch (VA.getLocInfo()) { 10148 default: 10149 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10150 case CCValAssign::Full: 10151 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10152 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10153 break; 10154 case CCValAssign::BCvt: 10155 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10156 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10157 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10158 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10159 else 10160 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10161 break; 10162 } 10163 return Val; 10164 } 10165 10166 // The caller is responsible for loading the full value if the argument is 10167 // passed with CCValAssign::Indirect. 10168 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10169 const CCValAssign &VA, const SDLoc &DL) { 10170 MachineFunction &MF = DAG.getMachineFunction(); 10171 MachineFrameInfo &MFI = MF.getFrameInfo(); 10172 EVT LocVT = VA.getLocVT(); 10173 EVT ValVT = VA.getValVT(); 10174 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10175 if (ValVT.isScalableVector()) { 10176 // When the value is a scalable vector, we save the pointer which points to 10177 // the scalable vector value in the stack. The ValVT will be the pointer 10178 // type, instead of the scalable vector type. 10179 ValVT = LocVT; 10180 } 10181 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10182 /*IsImmutable=*/true); 10183 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10184 SDValue Val; 10185 10186 ISD::LoadExtType ExtType; 10187 switch (VA.getLocInfo()) { 10188 default: 10189 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10190 case CCValAssign::Full: 10191 case CCValAssign::Indirect: 10192 case CCValAssign::BCvt: 10193 ExtType = ISD::NON_EXTLOAD; 10194 break; 10195 } 10196 Val = DAG.getExtLoad( 10197 ExtType, DL, LocVT, Chain, FIN, 10198 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10199 return Val; 10200 } 10201 10202 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10203 const CCValAssign &VA, const SDLoc &DL) { 10204 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10205 "Unexpected VA"); 10206 MachineFunction &MF = DAG.getMachineFunction(); 10207 MachineFrameInfo &MFI = MF.getFrameInfo(); 10208 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10209 10210 if (VA.isMemLoc()) { 10211 // f64 is passed on the stack. 10212 int FI = 10213 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10214 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10215 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10216 MachinePointerInfo::getFixedStack(MF, FI)); 10217 } 10218 10219 assert(VA.isRegLoc() && "Expected register VA assignment"); 10220 10221 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10222 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10223 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10224 SDValue Hi; 10225 if (VA.getLocReg() == RISCV::X17) { 10226 // Second half of f64 is passed on the stack. 10227 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10228 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10229 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10230 MachinePointerInfo::getFixedStack(MF, FI)); 10231 } else { 10232 // Second half of f64 is passed in another GPR. 10233 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10234 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10235 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10236 } 10237 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10238 } 10239 10240 // FastCC has less than 1% performance improvement for some particular 10241 // benchmark. But theoretically, it may has benenfit for some cases. 10242 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10243 unsigned ValNo, MVT ValVT, MVT LocVT, 10244 CCValAssign::LocInfo LocInfo, 10245 ISD::ArgFlagsTy ArgFlags, CCState &State, 10246 bool IsFixed, bool IsRet, Type *OrigTy, 10247 const RISCVTargetLowering &TLI, 10248 Optional<unsigned> FirstMaskArgument) { 10249 10250 // X5 and X6 might be used for save-restore libcall. 10251 static const MCPhysReg GPRList[] = { 10252 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10253 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10254 RISCV::X29, RISCV::X30, RISCV::X31}; 10255 10256 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10257 if (unsigned Reg = State.AllocateReg(GPRList)) { 10258 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10259 return false; 10260 } 10261 } 10262 10263 if (LocVT == MVT::f16) { 10264 static const MCPhysReg FPR16List[] = { 10265 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10266 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10267 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10268 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10269 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10270 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10271 return false; 10272 } 10273 } 10274 10275 if (LocVT == MVT::f32) { 10276 static const MCPhysReg FPR32List[] = { 10277 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10278 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10279 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10280 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10281 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10282 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10283 return false; 10284 } 10285 } 10286 10287 if (LocVT == MVT::f64) { 10288 static const MCPhysReg FPR64List[] = { 10289 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10290 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10291 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10292 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10293 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10294 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10295 return false; 10296 } 10297 } 10298 10299 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10300 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10301 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10302 return false; 10303 } 10304 10305 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10306 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10307 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10308 return false; 10309 } 10310 10311 if (LocVT.isVector()) { 10312 if (unsigned Reg = 10313 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10314 // Fixed-length vectors are located in the corresponding scalable-vector 10315 // container types. 10316 if (ValVT.isFixedLengthVector()) 10317 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10318 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10319 } else { 10320 // Try and pass the address via a "fast" GPR. 10321 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10322 LocInfo = CCValAssign::Indirect; 10323 LocVT = TLI.getSubtarget().getXLenVT(); 10324 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10325 } else if (ValVT.isFixedLengthVector()) { 10326 auto StackAlign = 10327 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10328 unsigned StackOffset = 10329 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10330 State.addLoc( 10331 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10332 } else { 10333 // Can't pass scalable vectors on the stack. 10334 return true; 10335 } 10336 } 10337 10338 return false; 10339 } 10340 10341 return true; // CC didn't match. 10342 } 10343 10344 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10345 CCValAssign::LocInfo LocInfo, 10346 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10347 10348 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10349 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10350 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10351 static const MCPhysReg GPRList[] = { 10352 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10353 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10354 if (unsigned Reg = State.AllocateReg(GPRList)) { 10355 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10356 return false; 10357 } 10358 } 10359 10360 if (LocVT == MVT::f32) { 10361 // Pass in STG registers: F1, ..., F6 10362 // fs0 ... fs5 10363 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10364 RISCV::F18_F, RISCV::F19_F, 10365 RISCV::F20_F, RISCV::F21_F}; 10366 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10367 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10368 return false; 10369 } 10370 } 10371 10372 if (LocVT == MVT::f64) { 10373 // Pass in STG registers: D1, ..., D6 10374 // fs6 ... fs11 10375 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10376 RISCV::F24_D, RISCV::F25_D, 10377 RISCV::F26_D, RISCV::F27_D}; 10378 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10379 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10380 return false; 10381 } 10382 } 10383 10384 report_fatal_error("No registers left in GHC calling convention"); 10385 return true; 10386 } 10387 10388 // Transform physical registers into virtual registers. 10389 SDValue RISCVTargetLowering::LowerFormalArguments( 10390 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10391 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10392 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10393 10394 MachineFunction &MF = DAG.getMachineFunction(); 10395 10396 switch (CallConv) { 10397 default: 10398 report_fatal_error("Unsupported calling convention"); 10399 case CallingConv::C: 10400 case CallingConv::Fast: 10401 break; 10402 case CallingConv::GHC: 10403 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10404 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10405 report_fatal_error( 10406 "GHC calling convention requires the F and D instruction set extensions"); 10407 } 10408 10409 const Function &Func = MF.getFunction(); 10410 if (Func.hasFnAttribute("interrupt")) { 10411 if (!Func.arg_empty()) 10412 report_fatal_error( 10413 "Functions with the interrupt attribute cannot have arguments!"); 10414 10415 StringRef Kind = 10416 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10417 10418 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10419 report_fatal_error( 10420 "Function interrupt attribute argument not supported!"); 10421 } 10422 10423 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10424 MVT XLenVT = Subtarget.getXLenVT(); 10425 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10426 // Used with vargs to acumulate store chains. 10427 std::vector<SDValue> OutChains; 10428 10429 // Assign locations to all of the incoming arguments. 10430 SmallVector<CCValAssign, 16> ArgLocs; 10431 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10432 10433 if (CallConv == CallingConv::GHC) 10434 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10435 else 10436 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10437 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10438 : CC_RISCV); 10439 10440 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10441 CCValAssign &VA = ArgLocs[i]; 10442 SDValue ArgValue; 10443 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10444 // case. 10445 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10446 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10447 else if (VA.isRegLoc()) 10448 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10449 else 10450 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10451 10452 if (VA.getLocInfo() == CCValAssign::Indirect) { 10453 // If the original argument was split and passed by reference (e.g. i128 10454 // on RV32), we need to load all parts of it here (using the same 10455 // address). Vectors may be partly split to registers and partly to the 10456 // stack, in which case the base address is partly offset and subsequent 10457 // stores are relative to that. 10458 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10459 MachinePointerInfo())); 10460 unsigned ArgIndex = Ins[i].OrigArgIndex; 10461 unsigned ArgPartOffset = Ins[i].PartOffset; 10462 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10463 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10464 CCValAssign &PartVA = ArgLocs[i + 1]; 10465 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10466 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10467 if (PartVA.getValVT().isScalableVector()) 10468 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10469 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10470 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10471 MachinePointerInfo())); 10472 ++i; 10473 } 10474 continue; 10475 } 10476 InVals.push_back(ArgValue); 10477 } 10478 10479 if (IsVarArg) { 10480 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10481 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10482 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10483 MachineFrameInfo &MFI = MF.getFrameInfo(); 10484 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10485 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10486 10487 // Offset of the first variable argument from stack pointer, and size of 10488 // the vararg save area. For now, the varargs save area is either zero or 10489 // large enough to hold a0-a7. 10490 int VaArgOffset, VarArgsSaveSize; 10491 10492 // If all registers are allocated, then all varargs must be passed on the 10493 // stack and we don't need to save any argregs. 10494 if (ArgRegs.size() == Idx) { 10495 VaArgOffset = CCInfo.getNextStackOffset(); 10496 VarArgsSaveSize = 0; 10497 } else { 10498 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10499 VaArgOffset = -VarArgsSaveSize; 10500 } 10501 10502 // Record the frame index of the first variable argument 10503 // which is a value necessary to VASTART. 10504 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10505 RVFI->setVarArgsFrameIndex(FI); 10506 10507 // If saving an odd number of registers then create an extra stack slot to 10508 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10509 // offsets to even-numbered registered remain 2*XLEN-aligned. 10510 if (Idx % 2) { 10511 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10512 VarArgsSaveSize += XLenInBytes; 10513 } 10514 10515 // Copy the integer registers that may have been used for passing varargs 10516 // to the vararg save area. 10517 for (unsigned I = Idx; I < ArgRegs.size(); 10518 ++I, VaArgOffset += XLenInBytes) { 10519 const Register Reg = RegInfo.createVirtualRegister(RC); 10520 RegInfo.addLiveIn(ArgRegs[I], Reg); 10521 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10522 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10523 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10524 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10525 MachinePointerInfo::getFixedStack(MF, FI)); 10526 cast<StoreSDNode>(Store.getNode()) 10527 ->getMemOperand() 10528 ->setValue((Value *)nullptr); 10529 OutChains.push_back(Store); 10530 } 10531 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10532 } 10533 10534 // All stores are grouped in one node to allow the matching between 10535 // the size of Ins and InVals. This only happens for vararg functions. 10536 if (!OutChains.empty()) { 10537 OutChains.push_back(Chain); 10538 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10539 } 10540 10541 return Chain; 10542 } 10543 10544 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10545 /// for tail call optimization. 10546 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10547 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10548 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10549 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10550 10551 auto &Callee = CLI.Callee; 10552 auto CalleeCC = CLI.CallConv; 10553 auto &Outs = CLI.Outs; 10554 auto &Caller = MF.getFunction(); 10555 auto CallerCC = Caller.getCallingConv(); 10556 10557 // Exception-handling functions need a special set of instructions to 10558 // indicate a return to the hardware. Tail-calling another function would 10559 // probably break this. 10560 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10561 // should be expanded as new function attributes are introduced. 10562 if (Caller.hasFnAttribute("interrupt")) 10563 return false; 10564 10565 // Do not tail call opt if the stack is used to pass parameters. 10566 if (CCInfo.getNextStackOffset() != 0) 10567 return false; 10568 10569 // Do not tail call opt if any parameters need to be passed indirectly. 10570 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10571 // passed indirectly. So the address of the value will be passed in a 10572 // register, or if not available, then the address is put on the stack. In 10573 // order to pass indirectly, space on the stack often needs to be allocated 10574 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10575 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10576 // are passed CCValAssign::Indirect. 10577 for (auto &VA : ArgLocs) 10578 if (VA.getLocInfo() == CCValAssign::Indirect) 10579 return false; 10580 10581 // Do not tail call opt if either caller or callee uses struct return 10582 // semantics. 10583 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10584 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10585 if (IsCallerStructRet || IsCalleeStructRet) 10586 return false; 10587 10588 // Externally-defined functions with weak linkage should not be 10589 // tail-called. The behaviour of branch instructions in this situation (as 10590 // used for tail calls) is implementation-defined, so we cannot rely on the 10591 // linker replacing the tail call with a return. 10592 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10593 const GlobalValue *GV = G->getGlobal(); 10594 if (GV->hasExternalWeakLinkage()) 10595 return false; 10596 } 10597 10598 // The callee has to preserve all registers the caller needs to preserve. 10599 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10600 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10601 if (CalleeCC != CallerCC) { 10602 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10603 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10604 return false; 10605 } 10606 10607 // Byval parameters hand the function a pointer directly into the stack area 10608 // we want to reuse during a tail call. Working around this *is* possible 10609 // but less efficient and uglier in LowerCall. 10610 for (auto &Arg : Outs) 10611 if (Arg.Flags.isByVal()) 10612 return false; 10613 10614 return true; 10615 } 10616 10617 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10618 return DAG.getDataLayout().getPrefTypeAlign( 10619 VT.getTypeForEVT(*DAG.getContext())); 10620 } 10621 10622 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10623 // and output parameter nodes. 10624 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10625 SmallVectorImpl<SDValue> &InVals) const { 10626 SelectionDAG &DAG = CLI.DAG; 10627 SDLoc &DL = CLI.DL; 10628 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10629 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10630 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10631 SDValue Chain = CLI.Chain; 10632 SDValue Callee = CLI.Callee; 10633 bool &IsTailCall = CLI.IsTailCall; 10634 CallingConv::ID CallConv = CLI.CallConv; 10635 bool IsVarArg = CLI.IsVarArg; 10636 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10637 MVT XLenVT = Subtarget.getXLenVT(); 10638 10639 MachineFunction &MF = DAG.getMachineFunction(); 10640 10641 // Analyze the operands of the call, assigning locations to each operand. 10642 SmallVector<CCValAssign, 16> ArgLocs; 10643 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10644 10645 if (CallConv == CallingConv::GHC) 10646 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10647 else 10648 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10649 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10650 : CC_RISCV); 10651 10652 // Check if it's really possible to do a tail call. 10653 if (IsTailCall) 10654 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10655 10656 if (IsTailCall) 10657 ++NumTailCalls; 10658 else if (CLI.CB && CLI.CB->isMustTailCall()) 10659 report_fatal_error("failed to perform tail call elimination on a call " 10660 "site marked musttail"); 10661 10662 // Get a count of how many bytes are to be pushed on the stack. 10663 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10664 10665 // Create local copies for byval args 10666 SmallVector<SDValue, 8> ByValArgs; 10667 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10668 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10669 if (!Flags.isByVal()) 10670 continue; 10671 10672 SDValue Arg = OutVals[i]; 10673 unsigned Size = Flags.getByValSize(); 10674 Align Alignment = Flags.getNonZeroByValAlign(); 10675 10676 int FI = 10677 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10678 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10679 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10680 10681 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10682 /*IsVolatile=*/false, 10683 /*AlwaysInline=*/false, IsTailCall, 10684 MachinePointerInfo(), MachinePointerInfo()); 10685 ByValArgs.push_back(FIPtr); 10686 } 10687 10688 if (!IsTailCall) 10689 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10690 10691 // Copy argument values to their designated locations. 10692 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10693 SmallVector<SDValue, 8> MemOpChains; 10694 SDValue StackPtr; 10695 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10696 CCValAssign &VA = ArgLocs[i]; 10697 SDValue ArgValue = OutVals[i]; 10698 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10699 10700 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10701 bool IsF64OnRV32DSoftABI = 10702 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10703 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10704 SDValue SplitF64 = DAG.getNode( 10705 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10706 SDValue Lo = SplitF64.getValue(0); 10707 SDValue Hi = SplitF64.getValue(1); 10708 10709 Register RegLo = VA.getLocReg(); 10710 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10711 10712 if (RegLo == RISCV::X17) { 10713 // Second half of f64 is passed on the stack. 10714 // Work out the address of the stack slot. 10715 if (!StackPtr.getNode()) 10716 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10717 // Emit the store. 10718 MemOpChains.push_back( 10719 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10720 } else { 10721 // Second half of f64 is passed in another GPR. 10722 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10723 Register RegHigh = RegLo + 1; 10724 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10725 } 10726 continue; 10727 } 10728 10729 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10730 // as any other MemLoc. 10731 10732 // Promote the value if needed. 10733 // For now, only handle fully promoted and indirect arguments. 10734 if (VA.getLocInfo() == CCValAssign::Indirect) { 10735 // Store the argument in a stack slot and pass its address. 10736 Align StackAlign = 10737 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10738 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10739 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10740 // If the original argument was split (e.g. i128), we need 10741 // to store the required parts of it here (and pass just one address). 10742 // Vectors may be partly split to registers and partly to the stack, in 10743 // which case the base address is partly offset and subsequent stores are 10744 // relative to that. 10745 unsigned ArgIndex = Outs[i].OrigArgIndex; 10746 unsigned ArgPartOffset = Outs[i].PartOffset; 10747 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10748 // Calculate the total size to store. We don't have access to what we're 10749 // actually storing other than performing the loop and collecting the 10750 // info. 10751 SmallVector<std::pair<SDValue, SDValue>> Parts; 10752 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10753 SDValue PartValue = OutVals[i + 1]; 10754 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10755 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10756 EVT PartVT = PartValue.getValueType(); 10757 if (PartVT.isScalableVector()) 10758 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10759 StoredSize += PartVT.getStoreSize(); 10760 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10761 Parts.push_back(std::make_pair(PartValue, Offset)); 10762 ++i; 10763 } 10764 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10765 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10766 MemOpChains.push_back( 10767 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10768 MachinePointerInfo::getFixedStack(MF, FI))); 10769 for (const auto &Part : Parts) { 10770 SDValue PartValue = Part.first; 10771 SDValue PartOffset = Part.second; 10772 SDValue Address = 10773 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10774 MemOpChains.push_back( 10775 DAG.getStore(Chain, DL, PartValue, Address, 10776 MachinePointerInfo::getFixedStack(MF, FI))); 10777 } 10778 ArgValue = SpillSlot; 10779 } else { 10780 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10781 } 10782 10783 // Use local copy if it is a byval arg. 10784 if (Flags.isByVal()) 10785 ArgValue = ByValArgs[j++]; 10786 10787 if (VA.isRegLoc()) { 10788 // Queue up the argument copies and emit them at the end. 10789 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10790 } else { 10791 assert(VA.isMemLoc() && "Argument not register or memory"); 10792 assert(!IsTailCall && "Tail call not allowed if stack is used " 10793 "for passing parameters"); 10794 10795 // Work out the address of the stack slot. 10796 if (!StackPtr.getNode()) 10797 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10798 SDValue Address = 10799 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10800 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10801 10802 // Emit the store. 10803 MemOpChains.push_back( 10804 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10805 } 10806 } 10807 10808 // Join the stores, which are independent of one another. 10809 if (!MemOpChains.empty()) 10810 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10811 10812 SDValue Glue; 10813 10814 // Build a sequence of copy-to-reg nodes, chained and glued together. 10815 for (auto &Reg : RegsToPass) { 10816 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10817 Glue = Chain.getValue(1); 10818 } 10819 10820 // Validate that none of the argument registers have been marked as 10821 // reserved, if so report an error. Do the same for the return address if this 10822 // is not a tailcall. 10823 validateCCReservedRegs(RegsToPass, MF); 10824 if (!IsTailCall && 10825 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10826 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10827 MF.getFunction(), 10828 "Return address register required, but has been reserved."}); 10829 10830 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10831 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10832 // split it and then direct call can be matched by PseudoCALL. 10833 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10834 const GlobalValue *GV = S->getGlobal(); 10835 10836 unsigned OpFlags = RISCVII::MO_CALL; 10837 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10838 OpFlags = RISCVII::MO_PLT; 10839 10840 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10841 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10842 unsigned OpFlags = RISCVII::MO_CALL; 10843 10844 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10845 nullptr)) 10846 OpFlags = RISCVII::MO_PLT; 10847 10848 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10849 } 10850 10851 // The first call operand is the chain and the second is the target address. 10852 SmallVector<SDValue, 8> Ops; 10853 Ops.push_back(Chain); 10854 Ops.push_back(Callee); 10855 10856 // Add argument registers to the end of the list so that they are 10857 // known live into the call. 10858 for (auto &Reg : RegsToPass) 10859 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10860 10861 if (!IsTailCall) { 10862 // Add a register mask operand representing the call-preserved registers. 10863 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10864 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10865 assert(Mask && "Missing call preserved mask for calling convention"); 10866 Ops.push_back(DAG.getRegisterMask(Mask)); 10867 } 10868 10869 // Glue the call to the argument copies, if any. 10870 if (Glue.getNode()) 10871 Ops.push_back(Glue); 10872 10873 // Emit the call. 10874 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10875 10876 if (IsTailCall) { 10877 MF.getFrameInfo().setHasTailCall(); 10878 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10879 } 10880 10881 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10882 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10883 Glue = Chain.getValue(1); 10884 10885 // Mark the end of the call, which is glued to the call itself. 10886 Chain = DAG.getCALLSEQ_END(Chain, 10887 DAG.getConstant(NumBytes, DL, PtrVT, true), 10888 DAG.getConstant(0, DL, PtrVT, true), 10889 Glue, DL); 10890 Glue = Chain.getValue(1); 10891 10892 // Assign locations to each value returned by this call. 10893 SmallVector<CCValAssign, 16> RVLocs; 10894 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10895 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10896 10897 // Copy all of the result registers out of their specified physreg. 10898 for (auto &VA : RVLocs) { 10899 // Copy the value out 10900 SDValue RetValue = 10901 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10902 // Glue the RetValue to the end of the call sequence 10903 Chain = RetValue.getValue(1); 10904 Glue = RetValue.getValue(2); 10905 10906 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10907 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10908 SDValue RetValue2 = 10909 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10910 Chain = RetValue2.getValue(1); 10911 Glue = RetValue2.getValue(2); 10912 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10913 RetValue2); 10914 } 10915 10916 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10917 10918 InVals.push_back(RetValue); 10919 } 10920 10921 return Chain; 10922 } 10923 10924 bool RISCVTargetLowering::CanLowerReturn( 10925 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10926 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10927 SmallVector<CCValAssign, 16> RVLocs; 10928 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10929 10930 Optional<unsigned> FirstMaskArgument; 10931 if (Subtarget.hasVInstructions()) 10932 FirstMaskArgument = preAssignMask(Outs); 10933 10934 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10935 MVT VT = Outs[i].VT; 10936 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10937 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10938 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10939 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10940 *this, FirstMaskArgument)) 10941 return false; 10942 } 10943 return true; 10944 } 10945 10946 SDValue 10947 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10948 bool IsVarArg, 10949 const SmallVectorImpl<ISD::OutputArg> &Outs, 10950 const SmallVectorImpl<SDValue> &OutVals, 10951 const SDLoc &DL, SelectionDAG &DAG) const { 10952 const MachineFunction &MF = DAG.getMachineFunction(); 10953 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10954 10955 // Stores the assignment of the return value to a location. 10956 SmallVector<CCValAssign, 16> RVLocs; 10957 10958 // Info about the registers and stack slot. 10959 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10960 *DAG.getContext()); 10961 10962 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10963 nullptr, CC_RISCV); 10964 10965 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10966 report_fatal_error("GHC functions return void only"); 10967 10968 SDValue Glue; 10969 SmallVector<SDValue, 4> RetOps(1, Chain); 10970 10971 // Copy the result values into the output registers. 10972 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10973 SDValue Val = OutVals[i]; 10974 CCValAssign &VA = RVLocs[i]; 10975 assert(VA.isRegLoc() && "Can only return in registers!"); 10976 10977 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10978 // Handle returning f64 on RV32D with a soft float ABI. 10979 assert(VA.isRegLoc() && "Expected return via registers"); 10980 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10981 DAG.getVTList(MVT::i32, MVT::i32), Val); 10982 SDValue Lo = SplitF64.getValue(0); 10983 SDValue Hi = SplitF64.getValue(1); 10984 Register RegLo = VA.getLocReg(); 10985 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10986 Register RegHi = RegLo + 1; 10987 10988 if (STI.isRegisterReservedByUser(RegLo) || 10989 STI.isRegisterReservedByUser(RegHi)) 10990 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10991 MF.getFunction(), 10992 "Return value register required, but has been reserved."}); 10993 10994 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10995 Glue = Chain.getValue(1); 10996 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10997 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10998 Glue = Chain.getValue(1); 10999 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11000 } else { 11001 // Handle a 'normal' return. 11002 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11003 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11004 11005 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11006 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11007 MF.getFunction(), 11008 "Return value register required, but has been reserved."}); 11009 11010 // Guarantee that all emitted copies are stuck together. 11011 Glue = Chain.getValue(1); 11012 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11013 } 11014 } 11015 11016 RetOps[0] = Chain; // Update chain. 11017 11018 // Add the glue node if we have it. 11019 if (Glue.getNode()) { 11020 RetOps.push_back(Glue); 11021 } 11022 11023 unsigned RetOpc = RISCVISD::RET_FLAG; 11024 // Interrupt service routines use different return instructions. 11025 const Function &Func = DAG.getMachineFunction().getFunction(); 11026 if (Func.hasFnAttribute("interrupt")) { 11027 if (!Func.getReturnType()->isVoidTy()) 11028 report_fatal_error( 11029 "Functions with the interrupt attribute must have void return type!"); 11030 11031 MachineFunction &MF = DAG.getMachineFunction(); 11032 StringRef Kind = 11033 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11034 11035 if (Kind == "user") 11036 RetOpc = RISCVISD::URET_FLAG; 11037 else if (Kind == "supervisor") 11038 RetOpc = RISCVISD::SRET_FLAG; 11039 else 11040 RetOpc = RISCVISD::MRET_FLAG; 11041 } 11042 11043 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11044 } 11045 11046 void RISCVTargetLowering::validateCCReservedRegs( 11047 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11048 MachineFunction &MF) const { 11049 const Function &F = MF.getFunction(); 11050 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11051 11052 if (llvm::any_of(Regs, [&STI](auto Reg) { 11053 return STI.isRegisterReservedByUser(Reg.first); 11054 })) 11055 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11056 F, "Argument register required, but has been reserved."}); 11057 } 11058 11059 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11060 return CI->isTailCall(); 11061 } 11062 11063 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11064 #define NODE_NAME_CASE(NODE) \ 11065 case RISCVISD::NODE: \ 11066 return "RISCVISD::" #NODE; 11067 // clang-format off 11068 switch ((RISCVISD::NodeType)Opcode) { 11069 case RISCVISD::FIRST_NUMBER: 11070 break; 11071 NODE_NAME_CASE(RET_FLAG) 11072 NODE_NAME_CASE(URET_FLAG) 11073 NODE_NAME_CASE(SRET_FLAG) 11074 NODE_NAME_CASE(MRET_FLAG) 11075 NODE_NAME_CASE(CALL) 11076 NODE_NAME_CASE(SELECT_CC) 11077 NODE_NAME_CASE(BR_CC) 11078 NODE_NAME_CASE(BuildPairF64) 11079 NODE_NAME_CASE(SplitF64) 11080 NODE_NAME_CASE(TAIL) 11081 NODE_NAME_CASE(MULHSU) 11082 NODE_NAME_CASE(SLLW) 11083 NODE_NAME_CASE(SRAW) 11084 NODE_NAME_CASE(SRLW) 11085 NODE_NAME_CASE(DIVW) 11086 NODE_NAME_CASE(DIVUW) 11087 NODE_NAME_CASE(REMUW) 11088 NODE_NAME_CASE(ROLW) 11089 NODE_NAME_CASE(RORW) 11090 NODE_NAME_CASE(CLZW) 11091 NODE_NAME_CASE(CTZW) 11092 NODE_NAME_CASE(FSLW) 11093 NODE_NAME_CASE(FSRW) 11094 NODE_NAME_CASE(FSL) 11095 NODE_NAME_CASE(FSR) 11096 NODE_NAME_CASE(FMV_H_X) 11097 NODE_NAME_CASE(FMV_X_ANYEXTH) 11098 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11099 NODE_NAME_CASE(FMV_W_X_RV64) 11100 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11101 NODE_NAME_CASE(FCVT_X) 11102 NODE_NAME_CASE(FCVT_XU) 11103 NODE_NAME_CASE(FCVT_W_RV64) 11104 NODE_NAME_CASE(FCVT_WU_RV64) 11105 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11106 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11107 NODE_NAME_CASE(READ_CYCLE_WIDE) 11108 NODE_NAME_CASE(GREV) 11109 NODE_NAME_CASE(GREVW) 11110 NODE_NAME_CASE(GORC) 11111 NODE_NAME_CASE(GORCW) 11112 NODE_NAME_CASE(SHFL) 11113 NODE_NAME_CASE(SHFLW) 11114 NODE_NAME_CASE(UNSHFL) 11115 NODE_NAME_CASE(UNSHFLW) 11116 NODE_NAME_CASE(BFP) 11117 NODE_NAME_CASE(BFPW) 11118 NODE_NAME_CASE(BCOMPRESS) 11119 NODE_NAME_CASE(BCOMPRESSW) 11120 NODE_NAME_CASE(BDECOMPRESS) 11121 NODE_NAME_CASE(BDECOMPRESSW) 11122 NODE_NAME_CASE(VMV_V_X_VL) 11123 NODE_NAME_CASE(VFMV_V_F_VL) 11124 NODE_NAME_CASE(VMV_X_S) 11125 NODE_NAME_CASE(VMV_S_X_VL) 11126 NODE_NAME_CASE(VFMV_S_F_VL) 11127 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11128 NODE_NAME_CASE(READ_VLENB) 11129 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11130 NODE_NAME_CASE(VSLIDEUP_VL) 11131 NODE_NAME_CASE(VSLIDE1UP_VL) 11132 NODE_NAME_CASE(VSLIDEDOWN_VL) 11133 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11134 NODE_NAME_CASE(VID_VL) 11135 NODE_NAME_CASE(VFNCVT_ROD_VL) 11136 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11137 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11138 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11139 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11140 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11141 NODE_NAME_CASE(VECREDUCE_AND_VL) 11142 NODE_NAME_CASE(VECREDUCE_OR_VL) 11143 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11144 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11145 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11146 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11147 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11148 NODE_NAME_CASE(ADD_VL) 11149 NODE_NAME_CASE(AND_VL) 11150 NODE_NAME_CASE(MUL_VL) 11151 NODE_NAME_CASE(OR_VL) 11152 NODE_NAME_CASE(SDIV_VL) 11153 NODE_NAME_CASE(SHL_VL) 11154 NODE_NAME_CASE(SREM_VL) 11155 NODE_NAME_CASE(SRA_VL) 11156 NODE_NAME_CASE(SRL_VL) 11157 NODE_NAME_CASE(SUB_VL) 11158 NODE_NAME_CASE(UDIV_VL) 11159 NODE_NAME_CASE(UREM_VL) 11160 NODE_NAME_CASE(XOR_VL) 11161 NODE_NAME_CASE(SADDSAT_VL) 11162 NODE_NAME_CASE(UADDSAT_VL) 11163 NODE_NAME_CASE(SSUBSAT_VL) 11164 NODE_NAME_CASE(USUBSAT_VL) 11165 NODE_NAME_CASE(FADD_VL) 11166 NODE_NAME_CASE(FSUB_VL) 11167 NODE_NAME_CASE(FMUL_VL) 11168 NODE_NAME_CASE(FDIV_VL) 11169 NODE_NAME_CASE(FNEG_VL) 11170 NODE_NAME_CASE(FABS_VL) 11171 NODE_NAME_CASE(FSQRT_VL) 11172 NODE_NAME_CASE(FMA_VL) 11173 NODE_NAME_CASE(FCOPYSIGN_VL) 11174 NODE_NAME_CASE(SMIN_VL) 11175 NODE_NAME_CASE(SMAX_VL) 11176 NODE_NAME_CASE(UMIN_VL) 11177 NODE_NAME_CASE(UMAX_VL) 11178 NODE_NAME_CASE(FMINNUM_VL) 11179 NODE_NAME_CASE(FMAXNUM_VL) 11180 NODE_NAME_CASE(MULHS_VL) 11181 NODE_NAME_CASE(MULHU_VL) 11182 NODE_NAME_CASE(FP_TO_SINT_VL) 11183 NODE_NAME_CASE(FP_TO_UINT_VL) 11184 NODE_NAME_CASE(SINT_TO_FP_VL) 11185 NODE_NAME_CASE(UINT_TO_FP_VL) 11186 NODE_NAME_CASE(FP_EXTEND_VL) 11187 NODE_NAME_CASE(FP_ROUND_VL) 11188 NODE_NAME_CASE(VWMUL_VL) 11189 NODE_NAME_CASE(VWMULU_VL) 11190 NODE_NAME_CASE(VWMULSU_VL) 11191 NODE_NAME_CASE(VWADD_VL) 11192 NODE_NAME_CASE(VWADDU_VL) 11193 NODE_NAME_CASE(VWSUB_VL) 11194 NODE_NAME_CASE(VWSUBU_VL) 11195 NODE_NAME_CASE(VWADD_W_VL) 11196 NODE_NAME_CASE(VWADDU_W_VL) 11197 NODE_NAME_CASE(VWSUB_W_VL) 11198 NODE_NAME_CASE(VWSUBU_W_VL) 11199 NODE_NAME_CASE(SETCC_VL) 11200 NODE_NAME_CASE(VSELECT_VL) 11201 NODE_NAME_CASE(VP_MERGE_VL) 11202 NODE_NAME_CASE(VMAND_VL) 11203 NODE_NAME_CASE(VMOR_VL) 11204 NODE_NAME_CASE(VMXOR_VL) 11205 NODE_NAME_CASE(VMCLR_VL) 11206 NODE_NAME_CASE(VMSET_VL) 11207 NODE_NAME_CASE(VRGATHER_VX_VL) 11208 NODE_NAME_CASE(VRGATHER_VV_VL) 11209 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11210 NODE_NAME_CASE(VSEXT_VL) 11211 NODE_NAME_CASE(VZEXT_VL) 11212 NODE_NAME_CASE(VCPOP_VL) 11213 NODE_NAME_CASE(READ_CSR) 11214 NODE_NAME_CASE(WRITE_CSR) 11215 NODE_NAME_CASE(SWAP_CSR) 11216 } 11217 // clang-format on 11218 return nullptr; 11219 #undef NODE_NAME_CASE 11220 } 11221 11222 /// getConstraintType - Given a constraint letter, return the type of 11223 /// constraint it is for this target. 11224 RISCVTargetLowering::ConstraintType 11225 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11226 if (Constraint.size() == 1) { 11227 switch (Constraint[0]) { 11228 default: 11229 break; 11230 case 'f': 11231 return C_RegisterClass; 11232 case 'I': 11233 case 'J': 11234 case 'K': 11235 return C_Immediate; 11236 case 'A': 11237 return C_Memory; 11238 case 'S': // A symbolic address 11239 return C_Other; 11240 } 11241 } else { 11242 if (Constraint == "vr" || Constraint == "vm") 11243 return C_RegisterClass; 11244 } 11245 return TargetLowering::getConstraintType(Constraint); 11246 } 11247 11248 std::pair<unsigned, const TargetRegisterClass *> 11249 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11250 StringRef Constraint, 11251 MVT VT) const { 11252 // First, see if this is a constraint that directly corresponds to a 11253 // RISCV register class. 11254 if (Constraint.size() == 1) { 11255 switch (Constraint[0]) { 11256 case 'r': 11257 // TODO: Support fixed vectors up to XLen for P extension? 11258 if (VT.isVector()) 11259 break; 11260 return std::make_pair(0U, &RISCV::GPRRegClass); 11261 case 'f': 11262 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11263 return std::make_pair(0U, &RISCV::FPR16RegClass); 11264 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11265 return std::make_pair(0U, &RISCV::FPR32RegClass); 11266 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11267 return std::make_pair(0U, &RISCV::FPR64RegClass); 11268 break; 11269 default: 11270 break; 11271 } 11272 } else if (Constraint == "vr") { 11273 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11274 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11275 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11276 return std::make_pair(0U, RC); 11277 } 11278 } else if (Constraint == "vm") { 11279 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11280 return std::make_pair(0U, &RISCV::VMV0RegClass); 11281 } 11282 11283 // Clang will correctly decode the usage of register name aliases into their 11284 // official names. However, other frontends like `rustc` do not. This allows 11285 // users of these frontends to use the ABI names for registers in LLVM-style 11286 // register constraints. 11287 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11288 .Case("{zero}", RISCV::X0) 11289 .Case("{ra}", RISCV::X1) 11290 .Case("{sp}", RISCV::X2) 11291 .Case("{gp}", RISCV::X3) 11292 .Case("{tp}", RISCV::X4) 11293 .Case("{t0}", RISCV::X5) 11294 .Case("{t1}", RISCV::X6) 11295 .Case("{t2}", RISCV::X7) 11296 .Cases("{s0}", "{fp}", RISCV::X8) 11297 .Case("{s1}", RISCV::X9) 11298 .Case("{a0}", RISCV::X10) 11299 .Case("{a1}", RISCV::X11) 11300 .Case("{a2}", RISCV::X12) 11301 .Case("{a3}", RISCV::X13) 11302 .Case("{a4}", RISCV::X14) 11303 .Case("{a5}", RISCV::X15) 11304 .Case("{a6}", RISCV::X16) 11305 .Case("{a7}", RISCV::X17) 11306 .Case("{s2}", RISCV::X18) 11307 .Case("{s3}", RISCV::X19) 11308 .Case("{s4}", RISCV::X20) 11309 .Case("{s5}", RISCV::X21) 11310 .Case("{s6}", RISCV::X22) 11311 .Case("{s7}", RISCV::X23) 11312 .Case("{s8}", RISCV::X24) 11313 .Case("{s9}", RISCV::X25) 11314 .Case("{s10}", RISCV::X26) 11315 .Case("{s11}", RISCV::X27) 11316 .Case("{t3}", RISCV::X28) 11317 .Case("{t4}", RISCV::X29) 11318 .Case("{t5}", RISCV::X30) 11319 .Case("{t6}", RISCV::X31) 11320 .Default(RISCV::NoRegister); 11321 if (XRegFromAlias != RISCV::NoRegister) 11322 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11323 11324 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11325 // TableGen record rather than the AsmName to choose registers for InlineAsm 11326 // constraints, plus we want to match those names to the widest floating point 11327 // register type available, manually select floating point registers here. 11328 // 11329 // The second case is the ABI name of the register, so that frontends can also 11330 // use the ABI names in register constraint lists. 11331 if (Subtarget.hasStdExtF()) { 11332 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11333 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11334 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11335 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11336 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11337 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11338 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11339 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11340 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11341 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11342 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11343 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11344 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11345 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11346 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11347 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11348 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11349 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11350 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11351 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11352 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11353 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11354 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11355 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11356 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11357 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11358 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11359 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11360 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11361 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11362 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11363 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11364 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11365 .Default(RISCV::NoRegister); 11366 if (FReg != RISCV::NoRegister) { 11367 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11368 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11369 unsigned RegNo = FReg - RISCV::F0_F; 11370 unsigned DReg = RISCV::F0_D + RegNo; 11371 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11372 } 11373 if (VT == MVT::f32 || VT == MVT::Other) 11374 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11375 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11376 unsigned RegNo = FReg - RISCV::F0_F; 11377 unsigned HReg = RISCV::F0_H + RegNo; 11378 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11379 } 11380 } 11381 } 11382 11383 if (Subtarget.hasVInstructions()) { 11384 Register VReg = StringSwitch<Register>(Constraint.lower()) 11385 .Case("{v0}", RISCV::V0) 11386 .Case("{v1}", RISCV::V1) 11387 .Case("{v2}", RISCV::V2) 11388 .Case("{v3}", RISCV::V3) 11389 .Case("{v4}", RISCV::V4) 11390 .Case("{v5}", RISCV::V5) 11391 .Case("{v6}", RISCV::V6) 11392 .Case("{v7}", RISCV::V7) 11393 .Case("{v8}", RISCV::V8) 11394 .Case("{v9}", RISCV::V9) 11395 .Case("{v10}", RISCV::V10) 11396 .Case("{v11}", RISCV::V11) 11397 .Case("{v12}", RISCV::V12) 11398 .Case("{v13}", RISCV::V13) 11399 .Case("{v14}", RISCV::V14) 11400 .Case("{v15}", RISCV::V15) 11401 .Case("{v16}", RISCV::V16) 11402 .Case("{v17}", RISCV::V17) 11403 .Case("{v18}", RISCV::V18) 11404 .Case("{v19}", RISCV::V19) 11405 .Case("{v20}", RISCV::V20) 11406 .Case("{v21}", RISCV::V21) 11407 .Case("{v22}", RISCV::V22) 11408 .Case("{v23}", RISCV::V23) 11409 .Case("{v24}", RISCV::V24) 11410 .Case("{v25}", RISCV::V25) 11411 .Case("{v26}", RISCV::V26) 11412 .Case("{v27}", RISCV::V27) 11413 .Case("{v28}", RISCV::V28) 11414 .Case("{v29}", RISCV::V29) 11415 .Case("{v30}", RISCV::V30) 11416 .Case("{v31}", RISCV::V31) 11417 .Default(RISCV::NoRegister); 11418 if (VReg != RISCV::NoRegister) { 11419 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11420 return std::make_pair(VReg, &RISCV::VMRegClass); 11421 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11422 return std::make_pair(VReg, &RISCV::VRRegClass); 11423 for (const auto *RC : 11424 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11425 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11426 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11427 return std::make_pair(VReg, RC); 11428 } 11429 } 11430 } 11431 } 11432 11433 std::pair<Register, const TargetRegisterClass *> Res = 11434 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11435 11436 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11437 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11438 // Subtarget into account. 11439 if (Res.second == &RISCV::GPRF16RegClass || 11440 Res.second == &RISCV::GPRF32RegClass || 11441 Res.second == &RISCV::GPRF64RegClass) 11442 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11443 11444 return Res; 11445 } 11446 11447 unsigned 11448 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11449 // Currently only support length 1 constraints. 11450 if (ConstraintCode.size() == 1) { 11451 switch (ConstraintCode[0]) { 11452 case 'A': 11453 return InlineAsm::Constraint_A; 11454 default: 11455 break; 11456 } 11457 } 11458 11459 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11460 } 11461 11462 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11463 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11464 SelectionDAG &DAG) const { 11465 // Currently only support length 1 constraints. 11466 if (Constraint.length() == 1) { 11467 switch (Constraint[0]) { 11468 case 'I': 11469 // Validate & create a 12-bit signed immediate operand. 11470 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11471 uint64_t CVal = C->getSExtValue(); 11472 if (isInt<12>(CVal)) 11473 Ops.push_back( 11474 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11475 } 11476 return; 11477 case 'J': 11478 // Validate & create an integer zero operand. 11479 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11480 if (C->getZExtValue() == 0) 11481 Ops.push_back( 11482 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11483 return; 11484 case 'K': 11485 // Validate & create a 5-bit unsigned immediate operand. 11486 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11487 uint64_t CVal = C->getZExtValue(); 11488 if (isUInt<5>(CVal)) 11489 Ops.push_back( 11490 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11491 } 11492 return; 11493 case 'S': 11494 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11495 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11496 GA->getValueType(0))); 11497 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11498 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11499 BA->getValueType(0))); 11500 } 11501 return; 11502 default: 11503 break; 11504 } 11505 } 11506 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11507 } 11508 11509 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11510 Instruction *Inst, 11511 AtomicOrdering Ord) const { 11512 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11513 return Builder.CreateFence(Ord); 11514 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11515 return Builder.CreateFence(AtomicOrdering::Release); 11516 return nullptr; 11517 } 11518 11519 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11520 Instruction *Inst, 11521 AtomicOrdering Ord) const { 11522 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11523 return Builder.CreateFence(AtomicOrdering::Acquire); 11524 return nullptr; 11525 } 11526 11527 TargetLowering::AtomicExpansionKind 11528 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11529 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11530 // point operations can't be used in an lr/sc sequence without breaking the 11531 // forward-progress guarantee. 11532 if (AI->isFloatingPointOperation()) 11533 return AtomicExpansionKind::CmpXChg; 11534 11535 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11536 if (Size == 8 || Size == 16) 11537 return AtomicExpansionKind::MaskedIntrinsic; 11538 return AtomicExpansionKind::None; 11539 } 11540 11541 static Intrinsic::ID 11542 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11543 if (XLen == 32) { 11544 switch (BinOp) { 11545 default: 11546 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11547 case AtomicRMWInst::Xchg: 11548 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11549 case AtomicRMWInst::Add: 11550 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11551 case AtomicRMWInst::Sub: 11552 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11553 case AtomicRMWInst::Nand: 11554 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11555 case AtomicRMWInst::Max: 11556 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11557 case AtomicRMWInst::Min: 11558 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11559 case AtomicRMWInst::UMax: 11560 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11561 case AtomicRMWInst::UMin: 11562 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11563 } 11564 } 11565 11566 if (XLen == 64) { 11567 switch (BinOp) { 11568 default: 11569 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11570 case AtomicRMWInst::Xchg: 11571 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11572 case AtomicRMWInst::Add: 11573 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11574 case AtomicRMWInst::Sub: 11575 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11576 case AtomicRMWInst::Nand: 11577 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11578 case AtomicRMWInst::Max: 11579 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11580 case AtomicRMWInst::Min: 11581 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11582 case AtomicRMWInst::UMax: 11583 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11584 case AtomicRMWInst::UMin: 11585 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11586 } 11587 } 11588 11589 llvm_unreachable("Unexpected XLen\n"); 11590 } 11591 11592 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11593 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11594 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11595 unsigned XLen = Subtarget.getXLen(); 11596 Value *Ordering = 11597 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11598 Type *Tys[] = {AlignedAddr->getType()}; 11599 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11600 AI->getModule(), 11601 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11602 11603 if (XLen == 64) { 11604 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11605 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11606 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11607 } 11608 11609 Value *Result; 11610 11611 // Must pass the shift amount needed to sign extend the loaded value prior 11612 // to performing a signed comparison for min/max. ShiftAmt is the number of 11613 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11614 // is the number of bits to left+right shift the value in order to 11615 // sign-extend. 11616 if (AI->getOperation() == AtomicRMWInst::Min || 11617 AI->getOperation() == AtomicRMWInst::Max) { 11618 const DataLayout &DL = AI->getModule()->getDataLayout(); 11619 unsigned ValWidth = 11620 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11621 Value *SextShamt = 11622 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11623 Result = Builder.CreateCall(LrwOpScwLoop, 11624 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11625 } else { 11626 Result = 11627 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11628 } 11629 11630 if (XLen == 64) 11631 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11632 return Result; 11633 } 11634 11635 TargetLowering::AtomicExpansionKind 11636 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11637 AtomicCmpXchgInst *CI) const { 11638 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11639 if (Size == 8 || Size == 16) 11640 return AtomicExpansionKind::MaskedIntrinsic; 11641 return AtomicExpansionKind::None; 11642 } 11643 11644 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11645 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11646 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11647 unsigned XLen = Subtarget.getXLen(); 11648 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11649 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11650 if (XLen == 64) { 11651 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11652 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11653 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11654 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11655 } 11656 Type *Tys[] = {AlignedAddr->getType()}; 11657 Function *MaskedCmpXchg = 11658 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11659 Value *Result = Builder.CreateCall( 11660 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11661 if (XLen == 64) 11662 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11663 return Result; 11664 } 11665 11666 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11667 return false; 11668 } 11669 11670 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11671 EVT VT) const { 11672 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11673 return false; 11674 11675 switch (FPVT.getSimpleVT().SimpleTy) { 11676 case MVT::f16: 11677 return Subtarget.hasStdExtZfh(); 11678 case MVT::f32: 11679 return Subtarget.hasStdExtF(); 11680 case MVT::f64: 11681 return Subtarget.hasStdExtD(); 11682 default: 11683 return false; 11684 } 11685 } 11686 11687 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11688 // If we are using the small code model, we can reduce size of jump table 11689 // entry to 4 bytes. 11690 if (Subtarget.is64Bit() && !isPositionIndependent() && 11691 getTargetMachine().getCodeModel() == CodeModel::Small) { 11692 return MachineJumpTableInfo::EK_Custom32; 11693 } 11694 return TargetLowering::getJumpTableEncoding(); 11695 } 11696 11697 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11698 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11699 unsigned uid, MCContext &Ctx) const { 11700 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11701 getTargetMachine().getCodeModel() == CodeModel::Small); 11702 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11703 } 11704 11705 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11706 EVT VT) const { 11707 VT = VT.getScalarType(); 11708 11709 if (!VT.isSimple()) 11710 return false; 11711 11712 switch (VT.getSimpleVT().SimpleTy) { 11713 case MVT::f16: 11714 return Subtarget.hasStdExtZfh(); 11715 case MVT::f32: 11716 return Subtarget.hasStdExtF(); 11717 case MVT::f64: 11718 return Subtarget.hasStdExtD(); 11719 default: 11720 break; 11721 } 11722 11723 return false; 11724 } 11725 11726 Register RISCVTargetLowering::getExceptionPointerRegister( 11727 const Constant *PersonalityFn) const { 11728 return RISCV::X10; 11729 } 11730 11731 Register RISCVTargetLowering::getExceptionSelectorRegister( 11732 const Constant *PersonalityFn) const { 11733 return RISCV::X11; 11734 } 11735 11736 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11737 // Return false to suppress the unnecessary extensions if the LibCall 11738 // arguments or return value is f32 type for LP64 ABI. 11739 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11740 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11741 return false; 11742 11743 return true; 11744 } 11745 11746 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11747 if (Subtarget.is64Bit() && Type == MVT::i32) 11748 return true; 11749 11750 return IsSigned; 11751 } 11752 11753 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11754 SDValue C) const { 11755 // Check integral scalar types. 11756 if (VT.isScalarInteger()) { 11757 // Omit the optimization if the sub target has the M extension and the data 11758 // size exceeds XLen. 11759 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11760 return false; 11761 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11762 // Break the MUL to a SLLI and an ADD/SUB. 11763 const APInt &Imm = ConstNode->getAPIntValue(); 11764 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11765 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11766 return true; 11767 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11768 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11769 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11770 (Imm - 8).isPowerOf2())) 11771 return true; 11772 // Omit the following optimization if the sub target has the M extension 11773 // and the data size >= XLen. 11774 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11775 return false; 11776 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11777 // a pair of LUI/ADDI. 11778 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11779 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11780 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11781 (1 - ImmS).isPowerOf2()) 11782 return true; 11783 } 11784 } 11785 } 11786 11787 return false; 11788 } 11789 11790 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11791 SDValue ConstNode) const { 11792 // Let the DAGCombiner decide for vectors. 11793 EVT VT = AddNode.getValueType(); 11794 if (VT.isVector()) 11795 return true; 11796 11797 // Let the DAGCombiner decide for larger types. 11798 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11799 return true; 11800 11801 // It is worse if c1 is simm12 while c1*c2 is not. 11802 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11803 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11804 const APInt &C1 = C1Node->getAPIntValue(); 11805 const APInt &C2 = C2Node->getAPIntValue(); 11806 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11807 return false; 11808 11809 // Default to true and let the DAGCombiner decide. 11810 return true; 11811 } 11812 11813 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11814 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11815 bool *Fast) const { 11816 if (!VT.isVector()) 11817 return false; 11818 11819 EVT ElemVT = VT.getVectorElementType(); 11820 if (Alignment >= ElemVT.getStoreSize()) { 11821 if (Fast) 11822 *Fast = true; 11823 return true; 11824 } 11825 11826 return false; 11827 } 11828 11829 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11830 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11831 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11832 bool IsABIRegCopy = CC.hasValue(); 11833 EVT ValueVT = Val.getValueType(); 11834 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11835 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11836 // and cast to f32. 11837 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11838 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11839 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11840 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11841 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11842 Parts[0] = Val; 11843 return true; 11844 } 11845 11846 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11847 LLVMContext &Context = *DAG.getContext(); 11848 EVT ValueEltVT = ValueVT.getVectorElementType(); 11849 EVT PartEltVT = PartVT.getVectorElementType(); 11850 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11851 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11852 if (PartVTBitSize % ValueVTBitSize == 0) { 11853 assert(PartVTBitSize >= ValueVTBitSize); 11854 // If the element types are different, bitcast to the same element type of 11855 // PartVT first. 11856 // Give an example here, we want copy a <vscale x 1 x i8> value to 11857 // <vscale x 4 x i16>. 11858 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11859 // subvector, then we can bitcast to <vscale x 4 x i16>. 11860 if (ValueEltVT != PartEltVT) { 11861 if (PartVTBitSize > ValueVTBitSize) { 11862 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11863 assert(Count != 0 && "The number of element should not be zero."); 11864 EVT SameEltTypeVT = 11865 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11866 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11867 DAG.getUNDEF(SameEltTypeVT), Val, 11868 DAG.getVectorIdxConstant(0, DL)); 11869 } 11870 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11871 } else { 11872 Val = 11873 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11874 Val, DAG.getVectorIdxConstant(0, DL)); 11875 } 11876 Parts[0] = Val; 11877 return true; 11878 } 11879 } 11880 return false; 11881 } 11882 11883 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11884 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11885 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11886 bool IsABIRegCopy = CC.hasValue(); 11887 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11888 SDValue Val = Parts[0]; 11889 11890 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11891 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11892 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11893 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11894 return Val; 11895 } 11896 11897 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11898 LLVMContext &Context = *DAG.getContext(); 11899 SDValue Val = Parts[0]; 11900 EVT ValueEltVT = ValueVT.getVectorElementType(); 11901 EVT PartEltVT = PartVT.getVectorElementType(); 11902 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11903 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11904 if (PartVTBitSize % ValueVTBitSize == 0) { 11905 assert(PartVTBitSize >= ValueVTBitSize); 11906 EVT SameEltTypeVT = ValueVT; 11907 // If the element types are different, convert it to the same element type 11908 // of PartVT. 11909 // Give an example here, we want copy a <vscale x 1 x i8> value from 11910 // <vscale x 4 x i16>. 11911 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11912 // then we can extract <vscale x 1 x i8>. 11913 if (ValueEltVT != PartEltVT) { 11914 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11915 assert(Count != 0 && "The number of element should not be zero."); 11916 SameEltTypeVT = 11917 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11918 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11919 } 11920 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11921 DAG.getVectorIdxConstant(0, DL)); 11922 return Val; 11923 } 11924 } 11925 return SDValue(); 11926 } 11927 11928 SDValue 11929 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11930 SelectionDAG &DAG, 11931 SmallVectorImpl<SDNode *> &Created) const { 11932 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11933 if (isIntDivCheap(N->getValueType(0), Attr)) 11934 return SDValue(N, 0); // Lower SDIV as SDIV 11935 11936 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11937 "Unexpected divisor!"); 11938 11939 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11940 if (!Subtarget.hasStdExtZbt()) 11941 return SDValue(); 11942 11943 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11944 // Besides, more critical path instructions will be generated when dividing 11945 // by 2. So we keep using the original DAGs for these cases. 11946 unsigned Lg2 = Divisor.countTrailingZeros(); 11947 if (Lg2 == 1 || Lg2 >= 12) 11948 return SDValue(); 11949 11950 // fold (sdiv X, pow2) 11951 EVT VT = N->getValueType(0); 11952 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11953 return SDValue(); 11954 11955 SDLoc DL(N); 11956 SDValue N0 = N->getOperand(0); 11957 SDValue Zero = DAG.getConstant(0, DL, VT); 11958 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11959 11960 // Add (N0 < 0) ? Pow2 - 1 : 0; 11961 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11962 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11963 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11964 11965 Created.push_back(Cmp.getNode()); 11966 Created.push_back(Add.getNode()); 11967 Created.push_back(Sel.getNode()); 11968 11969 // Divide by pow2. 11970 SDValue SRA = 11971 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11972 11973 // If we're dividing by a positive value, we're done. Otherwise, we must 11974 // negate the result. 11975 if (Divisor.isNonNegative()) 11976 return SRA; 11977 11978 Created.push_back(SRA.getNode()); 11979 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11980 } 11981 11982 #define GET_REGISTER_MATCHER 11983 #include "RISCVGenAsmMatcher.inc" 11984 11985 Register 11986 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11987 const MachineFunction &MF) const { 11988 Register Reg = MatchRegisterAltName(RegName); 11989 if (Reg == RISCV::NoRegister) 11990 Reg = MatchRegisterName(RegName); 11991 if (Reg == RISCV::NoRegister) 11992 report_fatal_error( 11993 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11994 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11995 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11996 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11997 StringRef(RegName) + "\".")); 11998 return Reg; 11999 } 12000 12001 namespace llvm { 12002 namespace RISCVVIntrinsicsTable { 12003 12004 #define GET_RISCVVIntrinsicsTable_IMPL 12005 #include "RISCVGenSearchableTables.inc" 12006 12007 } // namespace RISCVVIntrinsicsTable 12008 12009 } // namespace llvm 12010