1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT, 174 MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand); 188 189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 190 if (!Subtarget.hasStdExtZbb()) 191 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 192 193 if (Subtarget.is64Bit()) { 194 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 195 MVT::i32, Custom); 196 197 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 198 MVT::i32, Custom); 199 } else { 200 setLibcallName( 201 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 202 nullptr); 203 setLibcallName(RTLIB::MULO_I64, nullptr); 204 } 205 206 if (!Subtarget.hasStdExtM()) { 207 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 208 ISD::SREM, ISD::UREM}, 209 XLenVT, Expand); 210 } else { 211 if (Subtarget.is64Bit()) { 212 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 213 214 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 215 {MVT::i8, MVT::i16, MVT::i32}, Custom); 216 } else { 217 setOperationAction(ISD::MUL, MVT::i64, Custom); 218 } 219 } 220 221 setOperationAction( 222 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 223 Expand); 224 225 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 226 Custom); 227 228 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 229 Subtarget.hasStdExtZbkb()) { 230 if (Subtarget.is64Bit()) 231 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 232 } else { 233 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 234 } 235 236 if (Subtarget.hasStdExtZbp()) { 237 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 238 // more combining. 239 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 240 241 // BSWAP i8 doesn't exist. 242 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 243 244 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 245 246 if (Subtarget.is64Bit()) 247 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 248 } else { 249 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 250 // pattern match it directly in isel. 251 setOperationAction(ISD::BSWAP, XLenVT, 252 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 253 ? Legal 254 : Expand); 255 // Zbkb can use rev8+brev8 to implement bitreverse. 256 setOperationAction(ISD::BITREVERSE, XLenVT, 257 Subtarget.hasStdExtZbkb() ? Custom : Expand); 258 } 259 260 if (Subtarget.hasStdExtZbb()) { 261 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 262 Legal); 263 264 if (Subtarget.is64Bit()) 265 setOperationAction( 266 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 267 MVT::i32, Custom); 268 } else { 269 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 270 271 if (Subtarget.is64Bit()) 272 setOperationAction(ISD::ABS, MVT::i32, Custom); 273 } 274 275 if (Subtarget.hasStdExtZbt()) { 276 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 277 setOperationAction(ISD::SELECT, XLenVT, Legal); 278 279 if (Subtarget.is64Bit()) 280 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 281 } else { 282 setOperationAction(ISD::SELECT, XLenVT, Custom); 283 } 284 285 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 286 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 287 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 288 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 289 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 290 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 291 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 292 293 static const ISD::CondCode FPCCToExpand[] = { 294 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 295 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 296 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 297 298 static const ISD::NodeType FPOpToExpand[] = { 299 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 300 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 301 302 if (Subtarget.hasStdExtZfh()) 303 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 304 305 if (Subtarget.hasStdExtZfh()) { 306 for (auto NT : FPLegalNodeTypes) 307 setOperationAction(NT, MVT::f16, Legal); 308 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 309 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 310 for (auto CC : FPCCToExpand) 311 setCondCodeAction(CC, MVT::f16, Expand); 312 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 313 setOperationAction(ISD::SELECT, MVT::f16, Custom); 314 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 315 316 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 317 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 318 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 319 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 320 ISD::FLOG2, ISD::FLOG10}, 321 MVT::f16, Promote); 322 323 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 324 // complete support for all operations in LegalizeDAG. 325 326 // We need to custom promote this. 327 if (Subtarget.is64Bit()) 328 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 329 } 330 331 if (Subtarget.hasStdExtF()) { 332 for (auto NT : FPLegalNodeTypes) 333 setOperationAction(NT, MVT::f32, Legal); 334 for (auto CC : FPCCToExpand) 335 setCondCodeAction(CC, MVT::f32, Expand); 336 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 337 setOperationAction(ISD::SELECT, MVT::f32, Custom); 338 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 339 for (auto Op : FPOpToExpand) 340 setOperationAction(Op, MVT::f32, Expand); 341 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 342 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 343 } 344 345 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 346 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 347 348 if (Subtarget.hasStdExtD()) { 349 for (auto NT : FPLegalNodeTypes) 350 setOperationAction(NT, MVT::f64, Legal); 351 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 352 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 353 for (auto CC : FPCCToExpand) 354 setCondCodeAction(CC, MVT::f64, Expand); 355 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 356 setOperationAction(ISD::SELECT, MVT::f64, Custom); 357 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 358 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 359 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 360 for (auto Op : FPOpToExpand) 361 setOperationAction(Op, MVT::f64, Expand); 362 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 363 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 364 } 365 366 if (Subtarget.is64Bit()) 367 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 368 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 369 MVT::i32, Custom); 370 371 if (Subtarget.hasStdExtF()) { 372 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 373 Custom); 374 375 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 376 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 377 XLenVT, Legal); 378 379 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 380 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 381 } 382 383 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 384 ISD::JumpTable}, 385 XLenVT, Custom); 386 387 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 388 389 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 390 // Unfortunately this can't be determined just from the ISA naming string. 391 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 392 Subtarget.is64Bit() ? Legal : Custom); 393 394 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 395 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 396 if (Subtarget.is64Bit()) 397 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtA()) { 400 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 401 setMinCmpXchgSizeInBits(32); 402 } else { 403 setMaxAtomicSizeInBitsSupported(0); 404 } 405 406 setBooleanContents(ZeroOrOneBooleanContent); 407 408 if (Subtarget.hasVInstructions()) { 409 setBooleanVectorContents(ZeroOrOneBooleanContent); 410 411 setOperationAction(ISD::VSCALE, XLenVT, Custom); 412 413 // RVV intrinsics may have illegal operands. 414 // We also need to custom legalize vmv.x.s. 415 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 416 {MVT::i8, MVT::i16}, Custom); 417 if (Subtarget.is64Bit()) 418 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 419 else 420 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 421 MVT::i64, Custom); 422 423 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 424 MVT::Other, Custom); 425 426 static const unsigned IntegerVPOps[] = { 427 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 428 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 429 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 430 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 431 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 432 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 433 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 434 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 435 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SEXT, 436 ISD::VP_ZEXT, ISD::VP_TRUNC}; 437 438 static const unsigned FloatingPointVPOps[] = { 439 ISD::VP_FADD, ISD::VP_FSUB, 440 ISD::VP_FMUL, ISD::VP_FDIV, 441 ISD::VP_FNEG, ISD::VP_FMA, 442 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 443 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 444 ISD::VP_MERGE, ISD::VP_SELECT, 445 ISD::VP_SITOFP, ISD::VP_UITOFP, 446 ISD::VP_SETCC, ISD::VP_FP_ROUND}; 447 448 if (!Subtarget.is64Bit()) { 449 // We must custom-lower certain vXi64 operations on RV32 due to the vector 450 // element type being illegal. 451 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 452 MVT::i64, Custom); 453 454 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 455 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 456 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 457 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 458 MVT::i64, Custom); 459 460 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 461 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 462 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 463 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 464 MVT::i64, Custom); 465 } 466 467 for (MVT VT : BoolVecVTs) { 468 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 469 470 // Mask VTs are custom-expanded into a series of standard nodes 471 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 472 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 473 VT, Custom); 474 475 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 476 Custom); 477 478 setOperationAction(ISD::SELECT, VT, Custom); 479 setOperationAction( 480 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 481 Expand); 482 483 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 484 485 setOperationAction( 486 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 487 Custom); 488 489 setOperationAction( 490 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 491 Custom); 492 493 // RVV has native int->float & float->int conversions where the 494 // element type sizes are within one power-of-two of each other. Any 495 // wider distances between type sizes have to be lowered as sequences 496 // which progressively narrow the gap in stages. 497 setOperationAction( 498 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 499 VT, Custom); 500 501 // Expand all extending loads to types larger than this, and truncating 502 // stores from types larger than this. 503 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 504 setTruncStoreAction(OtherVT, VT, Expand); 505 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 506 VT, Expand); 507 } 508 509 setOperationAction( 510 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNC, ISD::VP_SETCC}, VT, 511 Custom); 512 } 513 514 for (MVT VT : IntVecVTs) { 515 if (VT.getVectorElementType() == MVT::i64 && 516 !Subtarget.hasVInstructionsI64()) 517 continue; 518 519 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 520 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 521 522 // Vectors implement MULHS/MULHU. 523 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 524 525 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 526 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 527 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 528 529 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 530 Legal); 531 532 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 533 534 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 535 Expand); 536 537 setOperationAction(ISD::BSWAP, VT, Expand); 538 539 // Custom-lower extensions and truncations from/to mask types. 540 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 541 VT, Custom); 542 543 // RVV has native int->float & float->int conversions where the 544 // element type sizes are within one power-of-two of each other. Any 545 // wider distances between type sizes have to be lowered as sequences 546 // which progressively narrow the gap in stages. 547 setOperationAction( 548 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 549 VT, Custom); 550 551 setOperationAction( 552 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 553 554 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 555 // nodes which truncate by one power of two at a time. 556 setOperationAction(ISD::TRUNCATE, VT, Custom); 557 558 // Custom-lower insert/extract operations to simplify patterns. 559 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 560 Custom); 561 562 // Custom-lower reduction operations to set up the corresponding custom 563 // nodes' operands. 564 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 565 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 566 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 567 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 568 VT, Custom); 569 570 for (unsigned VPOpc : IntegerVPOps) 571 setOperationAction(VPOpc, VT, Custom); 572 573 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 574 575 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 576 VT, Custom); 577 578 setOperationAction( 579 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 580 Custom); 581 582 setOperationAction( 583 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 584 VT, Custom); 585 586 setOperationAction(ISD::SELECT, VT, Custom); 587 setOperationAction(ISD::SELECT_CC, VT, Expand); 588 589 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 590 591 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 592 setTruncStoreAction(VT, OtherVT, Expand); 593 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 594 VT, Expand); 595 } 596 597 // Splice 598 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 599 600 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 601 // type that can represent the value exactly. 602 if (VT.getVectorElementType() != MVT::i64) { 603 MVT FloatEltVT = 604 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 605 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 606 if (isTypeLegal(FloatVT)) { 607 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 608 Custom); 609 } 610 } 611 } 612 613 // Expand various CCs to best match the RVV ISA, which natively supports UNE 614 // but no other unordered comparisons, and supports all ordered comparisons 615 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 616 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 617 // and we pattern-match those back to the "original", swapping operands once 618 // more. This way we catch both operations and both "vf" and "fv" forms with 619 // fewer patterns. 620 static const ISD::CondCode VFPCCToExpand[] = { 621 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 622 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 623 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 624 }; 625 626 // Sets common operation actions on RVV floating-point vector types. 627 const auto SetCommonVFPActions = [&](MVT VT) { 628 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 629 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 630 // sizes are within one power-of-two of each other. Therefore conversions 631 // between vXf16 and vXf64 must be lowered as sequences which convert via 632 // vXf32. 633 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 634 // Custom-lower insert/extract operations to simplify patterns. 635 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 636 Custom); 637 // Expand various condition codes (explained above). 638 for (auto CC : VFPCCToExpand) 639 setCondCodeAction(CC, VT, Expand); 640 641 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 642 643 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 644 VT, Custom); 645 646 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 647 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 648 VT, Custom); 649 650 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 651 652 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 653 654 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 655 VT, Custom); 656 657 setOperationAction( 658 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 659 Custom); 660 661 setOperationAction(ISD::SELECT, VT, Custom); 662 setOperationAction(ISD::SELECT_CC, VT, Expand); 663 664 setOperationAction( 665 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 666 VT, Custom); 667 668 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 669 670 for (unsigned VPOpc : FloatingPointVPOps) 671 setOperationAction(VPOpc, VT, Custom); 672 }; 673 674 // Sets common extload/truncstore actions on RVV floating-point vector 675 // types. 676 const auto SetCommonVFPExtLoadTruncStoreActions = 677 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 678 for (auto SmallVT : SmallerVTs) { 679 setTruncStoreAction(VT, SmallVT, Expand); 680 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 681 } 682 }; 683 684 if (Subtarget.hasVInstructionsF16()) 685 for (MVT VT : F16VecVTs) 686 SetCommonVFPActions(VT); 687 688 for (MVT VT : F32VecVTs) { 689 if (Subtarget.hasVInstructionsF32()) 690 SetCommonVFPActions(VT); 691 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 692 } 693 694 for (MVT VT : F64VecVTs) { 695 if (Subtarget.hasVInstructionsF64()) 696 SetCommonVFPActions(VT); 697 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 698 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 699 } 700 701 if (Subtarget.useRVVForFixedLengthVectors()) { 702 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 703 if (!useRVVForFixedLengthVectorVT(VT)) 704 continue; 705 706 // By default everything must be expanded. 707 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 708 setOperationAction(Op, VT, Expand); 709 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 710 setTruncStoreAction(VT, OtherVT, Expand); 711 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 712 OtherVT, VT, Expand); 713 } 714 715 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 716 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 717 Custom); 718 719 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 720 Custom); 721 722 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 723 VT, Custom); 724 725 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 726 727 setOperationAction(ISD::SETCC, VT, Custom); 728 729 setOperationAction(ISD::SELECT, VT, Custom); 730 731 setOperationAction(ISD::TRUNCATE, VT, Custom); 732 733 setOperationAction(ISD::BITCAST, VT, Custom); 734 735 setOperationAction( 736 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 737 Custom); 738 739 setOperationAction( 740 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 741 Custom); 742 743 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 744 ISD::FP_TO_UINT}, 745 VT, Custom); 746 747 // Operations below are different for between masks and other vectors. 748 if (VT.getVectorElementType() == MVT::i1) { 749 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 750 ISD::OR, ISD::XOR}, 751 VT, Custom); 752 753 setOperationAction( 754 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNC}, 755 VT, Custom); 756 continue; 757 } 758 759 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 760 // it before type legalization for i64 vectors on RV32. It will then be 761 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 762 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 763 // improvements first. 764 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 765 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 766 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 767 } 768 769 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 770 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 771 772 setOperationAction( 773 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 774 775 setOperationAction( 776 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 777 Custom); 778 779 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 780 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 781 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 782 VT, Custom); 783 784 setOperationAction( 785 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 786 787 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 788 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 789 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 790 791 setOperationAction( 792 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 793 Custom); 794 795 setOperationAction(ISD::VSELECT, VT, Custom); 796 setOperationAction(ISD::SELECT_CC, VT, Expand); 797 798 setOperationAction( 799 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 800 801 // Custom-lower reduction operations to set up the corresponding custom 802 // nodes' operands. 803 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 804 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 805 ISD::VECREDUCE_UMIN}, 806 VT, Custom); 807 808 for (unsigned VPOpc : IntegerVPOps) 809 setOperationAction(VPOpc, VT, Custom); 810 811 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 812 // type that can represent the value exactly. 813 if (VT.getVectorElementType() != MVT::i64) { 814 MVT FloatEltVT = 815 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 816 EVT FloatVT = 817 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 818 if (isTypeLegal(FloatVT)) 819 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 820 Custom); 821 } 822 } 823 824 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 825 if (!useRVVForFixedLengthVectorVT(VT)) 826 continue; 827 828 // By default everything must be expanded. 829 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 830 setOperationAction(Op, VT, Expand); 831 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 832 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 833 setTruncStoreAction(VT, OtherVT, Expand); 834 } 835 836 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 837 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 838 Custom); 839 840 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 841 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 842 ISD::EXTRACT_VECTOR_ELT}, 843 VT, Custom); 844 845 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 846 ISD::MGATHER, ISD::MSCATTER}, 847 VT, Custom); 848 849 setOperationAction( 850 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 851 Custom); 852 853 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 854 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 855 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 856 VT, Custom); 857 858 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 859 860 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 861 VT, Custom); 862 863 for (auto CC : VFPCCToExpand) 864 setCondCodeAction(CC, VT, Expand); 865 866 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 867 setOperationAction(ISD::SELECT_CC, VT, Expand); 868 869 setOperationAction(ISD::BITCAST, VT, Custom); 870 871 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 872 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 873 VT, Custom); 874 875 for (unsigned VPOpc : FloatingPointVPOps) 876 setOperationAction(VPOpc, VT, Custom); 877 } 878 879 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 880 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 881 Custom); 882 if (Subtarget.hasStdExtZfh()) 883 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 884 if (Subtarget.hasStdExtF()) 885 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 886 if (Subtarget.hasStdExtD()) 887 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 888 } 889 } 890 891 // Function alignments. 892 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 893 setMinFunctionAlignment(FunctionAlignment); 894 setPrefFunctionAlignment(FunctionAlignment); 895 896 setMinimumJumpTableEntries(5); 897 898 // Jumps are expensive, compared to logic 899 setJumpIsExpensive(); 900 901 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 902 ISD::OR, ISD::XOR}); 903 904 if (Subtarget.hasStdExtF()) 905 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 906 907 if (Subtarget.hasStdExtZbp()) 908 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 909 910 if (Subtarget.hasStdExtZbb()) 911 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 912 913 if (Subtarget.hasStdExtZbkb()) 914 setTargetDAGCombine(ISD::BITREVERSE); 915 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 916 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 917 if (Subtarget.hasStdExtF()) 918 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 919 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 920 if (Subtarget.hasVInstructions()) 921 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 922 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 923 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 924 925 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 926 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 927 } 928 929 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 930 LLVMContext &Context, 931 EVT VT) const { 932 if (!VT.isVector()) 933 return getPointerTy(DL); 934 if (Subtarget.hasVInstructions() && 935 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 936 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 937 return VT.changeVectorElementTypeToInteger(); 938 } 939 940 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 941 return Subtarget.getXLenVT(); 942 } 943 944 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 945 const CallInst &I, 946 MachineFunction &MF, 947 unsigned Intrinsic) const { 948 auto &DL = I.getModule()->getDataLayout(); 949 switch (Intrinsic) { 950 default: 951 return false; 952 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 953 case Intrinsic::riscv_masked_atomicrmw_add_i32: 954 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 955 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 956 case Intrinsic::riscv_masked_atomicrmw_max_i32: 957 case Intrinsic::riscv_masked_atomicrmw_min_i32: 958 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 959 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 960 case Intrinsic::riscv_masked_cmpxchg_i32: 961 Info.opc = ISD::INTRINSIC_W_CHAIN; 962 Info.memVT = MVT::i32; 963 Info.ptrVal = I.getArgOperand(0); 964 Info.offset = 0; 965 Info.align = Align(4); 966 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 967 MachineMemOperand::MOVolatile; 968 return true; 969 case Intrinsic::riscv_masked_strided_load: 970 Info.opc = ISD::INTRINSIC_W_CHAIN; 971 Info.ptrVal = I.getArgOperand(1); 972 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 973 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 974 Info.size = MemoryLocation::UnknownSize; 975 Info.flags |= MachineMemOperand::MOLoad; 976 return true; 977 case Intrinsic::riscv_masked_strided_store: 978 Info.opc = ISD::INTRINSIC_VOID; 979 Info.ptrVal = I.getArgOperand(1); 980 Info.memVT = 981 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 982 Info.align = Align( 983 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 984 8); 985 Info.size = MemoryLocation::UnknownSize; 986 Info.flags |= MachineMemOperand::MOStore; 987 return true; 988 case Intrinsic::riscv_seg2_load: 989 case Intrinsic::riscv_seg3_load: 990 case Intrinsic::riscv_seg4_load: 991 case Intrinsic::riscv_seg5_load: 992 case Intrinsic::riscv_seg6_load: 993 case Intrinsic::riscv_seg7_load: 994 case Intrinsic::riscv_seg8_load: 995 Info.opc = ISD::INTRINSIC_W_CHAIN; 996 Info.ptrVal = I.getArgOperand(0); 997 Info.memVT = 998 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 999 Info.align = 1000 Align(DL.getTypeSizeInBits( 1001 I.getType()->getStructElementType(0)->getScalarType()) / 1002 8); 1003 Info.size = MemoryLocation::UnknownSize; 1004 Info.flags |= MachineMemOperand::MOLoad; 1005 return true; 1006 } 1007 } 1008 1009 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1010 const AddrMode &AM, Type *Ty, 1011 unsigned AS, 1012 Instruction *I) const { 1013 // No global is ever allowed as a base. 1014 if (AM.BaseGV) 1015 return false; 1016 1017 // RVV instructions only support register addressing. 1018 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1019 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1020 1021 // Require a 12-bit signed offset. 1022 if (!isInt<12>(AM.BaseOffs)) 1023 return false; 1024 1025 switch (AM.Scale) { 1026 case 0: // "r+i" or just "i", depending on HasBaseReg. 1027 break; 1028 case 1: 1029 if (!AM.HasBaseReg) // allow "r+i". 1030 break; 1031 return false; // disallow "r+r" or "r+r+i". 1032 default: 1033 return false; 1034 } 1035 1036 return true; 1037 } 1038 1039 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1040 return isInt<12>(Imm); 1041 } 1042 1043 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1044 return isInt<12>(Imm); 1045 } 1046 1047 // On RV32, 64-bit integers are split into their high and low parts and held 1048 // in two different registers, so the trunc is free since the low register can 1049 // just be used. 1050 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1051 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1052 return false; 1053 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1054 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1055 return (SrcBits == 64 && DestBits == 32); 1056 } 1057 1058 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1059 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1060 !SrcVT.isInteger() || !DstVT.isInteger()) 1061 return false; 1062 unsigned SrcBits = SrcVT.getSizeInBits(); 1063 unsigned DestBits = DstVT.getSizeInBits(); 1064 return (SrcBits == 64 && DestBits == 32); 1065 } 1066 1067 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1068 // Zexts are free if they can be combined with a load. 1069 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1070 // poorly with type legalization of compares preferring sext. 1071 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1072 EVT MemVT = LD->getMemoryVT(); 1073 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1074 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1075 LD->getExtensionType() == ISD::ZEXTLOAD)) 1076 return true; 1077 } 1078 1079 return TargetLowering::isZExtFree(Val, VT2); 1080 } 1081 1082 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1083 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1084 } 1085 1086 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1087 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1088 } 1089 1090 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1091 return Subtarget.hasStdExtZbb(); 1092 } 1093 1094 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1095 return Subtarget.hasStdExtZbb(); 1096 } 1097 1098 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1099 EVT VT = Y.getValueType(); 1100 1101 // FIXME: Support vectors once we have tests. 1102 if (VT.isVector()) 1103 return false; 1104 1105 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1106 Subtarget.hasStdExtZbkb()) && 1107 !isa<ConstantSDNode>(Y); 1108 } 1109 1110 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1111 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1112 auto *C = dyn_cast<ConstantSDNode>(Y); 1113 return C && C->getAPIntValue().ule(10); 1114 } 1115 1116 /// Check if sinking \p I's operands to I's basic block is profitable, because 1117 /// the operands can be folded into a target instruction, e.g. 1118 /// splats of scalars can fold into vector instructions. 1119 bool RISCVTargetLowering::shouldSinkOperands( 1120 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1121 using namespace llvm::PatternMatch; 1122 1123 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1124 return false; 1125 1126 auto IsSinker = [&](Instruction *I, int Operand) { 1127 switch (I->getOpcode()) { 1128 case Instruction::Add: 1129 case Instruction::Sub: 1130 case Instruction::Mul: 1131 case Instruction::And: 1132 case Instruction::Or: 1133 case Instruction::Xor: 1134 case Instruction::FAdd: 1135 case Instruction::FSub: 1136 case Instruction::FMul: 1137 case Instruction::FDiv: 1138 case Instruction::ICmp: 1139 case Instruction::FCmp: 1140 return true; 1141 case Instruction::Shl: 1142 case Instruction::LShr: 1143 case Instruction::AShr: 1144 case Instruction::UDiv: 1145 case Instruction::SDiv: 1146 case Instruction::URem: 1147 case Instruction::SRem: 1148 return Operand == 1; 1149 case Instruction::Call: 1150 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1151 switch (II->getIntrinsicID()) { 1152 case Intrinsic::fma: 1153 case Intrinsic::vp_fma: 1154 return Operand == 0 || Operand == 1; 1155 // FIXME: Our patterns can only match vx/vf instructions when the splat 1156 // it on the RHS, because TableGen doesn't recognize our VP operations 1157 // as commutative. 1158 case Intrinsic::vp_add: 1159 case Intrinsic::vp_mul: 1160 case Intrinsic::vp_and: 1161 case Intrinsic::vp_or: 1162 case Intrinsic::vp_xor: 1163 case Intrinsic::vp_fadd: 1164 case Intrinsic::vp_fmul: 1165 case Intrinsic::vp_shl: 1166 case Intrinsic::vp_lshr: 1167 case Intrinsic::vp_ashr: 1168 case Intrinsic::vp_udiv: 1169 case Intrinsic::vp_sdiv: 1170 case Intrinsic::vp_urem: 1171 case Intrinsic::vp_srem: 1172 return Operand == 1; 1173 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1174 // explicit patterns for both LHS and RHS (as 'vr' versions). 1175 case Intrinsic::vp_sub: 1176 case Intrinsic::vp_fsub: 1177 case Intrinsic::vp_fdiv: 1178 return Operand == 0 || Operand == 1; 1179 default: 1180 return false; 1181 } 1182 } 1183 return false; 1184 default: 1185 return false; 1186 } 1187 }; 1188 1189 for (auto OpIdx : enumerate(I->operands())) { 1190 if (!IsSinker(I, OpIdx.index())) 1191 continue; 1192 1193 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1194 // Make sure we are not already sinking this operand 1195 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1196 continue; 1197 1198 // We are looking for a splat that can be sunk. 1199 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1200 m_Undef(), m_ZeroMask()))) 1201 continue; 1202 1203 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1204 // and vector registers 1205 for (Use &U : Op->uses()) { 1206 Instruction *Insn = cast<Instruction>(U.getUser()); 1207 if (!IsSinker(Insn, U.getOperandNo())) 1208 return false; 1209 } 1210 1211 Ops.push_back(&Op->getOperandUse(0)); 1212 Ops.push_back(&OpIdx.value()); 1213 } 1214 return true; 1215 } 1216 1217 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1218 bool ForCodeSize) const { 1219 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1220 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1221 return false; 1222 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1223 return false; 1224 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1225 return false; 1226 return Imm.isZero(); 1227 } 1228 1229 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1230 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1231 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1232 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1233 } 1234 1235 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1236 CallingConv::ID CC, 1237 EVT VT) const { 1238 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1239 // We might still end up using a GPR but that will be decided based on ABI. 1240 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1241 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1242 return MVT::f32; 1243 1244 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1245 } 1246 1247 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1248 CallingConv::ID CC, 1249 EVT VT) const { 1250 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1251 // We might still end up using a GPR but that will be decided based on ABI. 1252 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1253 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1254 return 1; 1255 1256 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1257 } 1258 1259 // Changes the condition code and swaps operands if necessary, so the SetCC 1260 // operation matches one of the comparisons supported directly by branches 1261 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1262 // with 1/-1. 1263 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1264 ISD::CondCode &CC, SelectionDAG &DAG) { 1265 // Convert X > -1 to X >= 0. 1266 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1267 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1268 CC = ISD::SETGE; 1269 return; 1270 } 1271 // Convert X < 1 to 0 >= X. 1272 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1273 RHS = LHS; 1274 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1275 CC = ISD::SETGE; 1276 return; 1277 } 1278 1279 switch (CC) { 1280 default: 1281 break; 1282 case ISD::SETGT: 1283 case ISD::SETLE: 1284 case ISD::SETUGT: 1285 case ISD::SETULE: 1286 CC = ISD::getSetCCSwappedOperands(CC); 1287 std::swap(LHS, RHS); 1288 break; 1289 } 1290 } 1291 1292 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1293 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1294 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1295 if (VT.getVectorElementType() == MVT::i1) 1296 KnownSize *= 8; 1297 1298 switch (KnownSize) { 1299 default: 1300 llvm_unreachable("Invalid LMUL."); 1301 case 8: 1302 return RISCVII::VLMUL::LMUL_F8; 1303 case 16: 1304 return RISCVII::VLMUL::LMUL_F4; 1305 case 32: 1306 return RISCVII::VLMUL::LMUL_F2; 1307 case 64: 1308 return RISCVII::VLMUL::LMUL_1; 1309 case 128: 1310 return RISCVII::VLMUL::LMUL_2; 1311 case 256: 1312 return RISCVII::VLMUL::LMUL_4; 1313 case 512: 1314 return RISCVII::VLMUL::LMUL_8; 1315 } 1316 } 1317 1318 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1319 switch (LMul) { 1320 default: 1321 llvm_unreachable("Invalid LMUL."); 1322 case RISCVII::VLMUL::LMUL_F8: 1323 case RISCVII::VLMUL::LMUL_F4: 1324 case RISCVII::VLMUL::LMUL_F2: 1325 case RISCVII::VLMUL::LMUL_1: 1326 return RISCV::VRRegClassID; 1327 case RISCVII::VLMUL::LMUL_2: 1328 return RISCV::VRM2RegClassID; 1329 case RISCVII::VLMUL::LMUL_4: 1330 return RISCV::VRM4RegClassID; 1331 case RISCVII::VLMUL::LMUL_8: 1332 return RISCV::VRM8RegClassID; 1333 } 1334 } 1335 1336 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1337 RISCVII::VLMUL LMUL = getLMUL(VT); 1338 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1339 LMUL == RISCVII::VLMUL::LMUL_F4 || 1340 LMUL == RISCVII::VLMUL::LMUL_F2 || 1341 LMUL == RISCVII::VLMUL::LMUL_1) { 1342 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1343 "Unexpected subreg numbering"); 1344 return RISCV::sub_vrm1_0 + Index; 1345 } 1346 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1347 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1348 "Unexpected subreg numbering"); 1349 return RISCV::sub_vrm2_0 + Index; 1350 } 1351 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1352 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1353 "Unexpected subreg numbering"); 1354 return RISCV::sub_vrm4_0 + Index; 1355 } 1356 llvm_unreachable("Invalid vector type."); 1357 } 1358 1359 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1360 if (VT.getVectorElementType() == MVT::i1) 1361 return RISCV::VRRegClassID; 1362 return getRegClassIDForLMUL(getLMUL(VT)); 1363 } 1364 1365 // Attempt to decompose a subvector insert/extract between VecVT and 1366 // SubVecVT via subregister indices. Returns the subregister index that 1367 // can perform the subvector insert/extract with the given element index, as 1368 // well as the index corresponding to any leftover subvectors that must be 1369 // further inserted/extracted within the register class for SubVecVT. 1370 std::pair<unsigned, unsigned> 1371 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1372 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1373 const RISCVRegisterInfo *TRI) { 1374 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1375 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1376 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1377 "Register classes not ordered"); 1378 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1379 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1380 // Try to compose a subregister index that takes us from the incoming 1381 // LMUL>1 register class down to the outgoing one. At each step we half 1382 // the LMUL: 1383 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1384 // Note that this is not guaranteed to find a subregister index, such as 1385 // when we are extracting from one VR type to another. 1386 unsigned SubRegIdx = RISCV::NoSubRegister; 1387 for (const unsigned RCID : 1388 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1389 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1390 VecVT = VecVT.getHalfNumVectorElementsVT(); 1391 bool IsHi = 1392 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1393 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1394 getSubregIndexByMVT(VecVT, IsHi)); 1395 if (IsHi) 1396 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1397 } 1398 return {SubRegIdx, InsertExtractIdx}; 1399 } 1400 1401 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1402 // stores for those types. 1403 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1404 return !Subtarget.useRVVForFixedLengthVectors() || 1405 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1406 } 1407 1408 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1409 if (ScalarTy->isPointerTy()) 1410 return true; 1411 1412 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1413 ScalarTy->isIntegerTy(32)) 1414 return true; 1415 1416 if (ScalarTy->isIntegerTy(64)) 1417 return Subtarget.hasVInstructionsI64(); 1418 1419 if (ScalarTy->isHalfTy()) 1420 return Subtarget.hasVInstructionsF16(); 1421 if (ScalarTy->isFloatTy()) 1422 return Subtarget.hasVInstructionsF32(); 1423 if (ScalarTy->isDoubleTy()) 1424 return Subtarget.hasVInstructionsF64(); 1425 1426 return false; 1427 } 1428 1429 static SDValue getVLOperand(SDValue Op) { 1430 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1431 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1432 "Unexpected opcode"); 1433 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1434 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1435 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1436 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1437 if (!II) 1438 return SDValue(); 1439 return Op.getOperand(II->VLOperand + 1 + HasChain); 1440 } 1441 1442 static bool useRVVForFixedLengthVectorVT(MVT VT, 1443 const RISCVSubtarget &Subtarget) { 1444 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1445 if (!Subtarget.useRVVForFixedLengthVectors()) 1446 return false; 1447 1448 // We only support a set of vector types with a consistent maximum fixed size 1449 // across all supported vector element types to avoid legalization issues. 1450 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1451 // fixed-length vector type we support is 1024 bytes. 1452 if (VT.getFixedSizeInBits() > 1024 * 8) 1453 return false; 1454 1455 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1456 1457 MVT EltVT = VT.getVectorElementType(); 1458 1459 // Don't use RVV for vectors we cannot scalarize if required. 1460 switch (EltVT.SimpleTy) { 1461 // i1 is supported but has different rules. 1462 default: 1463 return false; 1464 case MVT::i1: 1465 // Masks can only use a single register. 1466 if (VT.getVectorNumElements() > MinVLen) 1467 return false; 1468 MinVLen /= 8; 1469 break; 1470 case MVT::i8: 1471 case MVT::i16: 1472 case MVT::i32: 1473 break; 1474 case MVT::i64: 1475 if (!Subtarget.hasVInstructionsI64()) 1476 return false; 1477 break; 1478 case MVT::f16: 1479 if (!Subtarget.hasVInstructionsF16()) 1480 return false; 1481 break; 1482 case MVT::f32: 1483 if (!Subtarget.hasVInstructionsF32()) 1484 return false; 1485 break; 1486 case MVT::f64: 1487 if (!Subtarget.hasVInstructionsF64()) 1488 return false; 1489 break; 1490 } 1491 1492 // Reject elements larger than ELEN. 1493 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1494 return false; 1495 1496 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1497 // Don't use RVV for types that don't fit. 1498 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1499 return false; 1500 1501 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1502 // the base fixed length RVV support in place. 1503 if (!VT.isPow2VectorType()) 1504 return false; 1505 1506 return true; 1507 } 1508 1509 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1510 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1511 } 1512 1513 // Return the largest legal scalable vector type that matches VT's element type. 1514 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1515 const RISCVSubtarget &Subtarget) { 1516 // This may be called before legal types are setup. 1517 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1518 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1519 "Expected legal fixed length vector!"); 1520 1521 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1522 unsigned MaxELen = Subtarget.getELEN(); 1523 1524 MVT EltVT = VT.getVectorElementType(); 1525 switch (EltVT.SimpleTy) { 1526 default: 1527 llvm_unreachable("unexpected element type for RVV container"); 1528 case MVT::i1: 1529 case MVT::i8: 1530 case MVT::i16: 1531 case MVT::i32: 1532 case MVT::i64: 1533 case MVT::f16: 1534 case MVT::f32: 1535 case MVT::f64: { 1536 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1537 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1538 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1539 unsigned NumElts = 1540 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1541 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1542 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1543 return MVT::getScalableVectorVT(EltVT, NumElts); 1544 } 1545 } 1546 } 1547 1548 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1549 const RISCVSubtarget &Subtarget) { 1550 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1551 Subtarget); 1552 } 1553 1554 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1555 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1556 } 1557 1558 // Grow V to consume an entire RVV register. 1559 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1560 const RISCVSubtarget &Subtarget) { 1561 assert(VT.isScalableVector() && 1562 "Expected to convert into a scalable vector!"); 1563 assert(V.getValueType().isFixedLengthVector() && 1564 "Expected a fixed length vector operand!"); 1565 SDLoc DL(V); 1566 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1567 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1568 } 1569 1570 // Shrink V so it's just big enough to maintain a VT's worth of data. 1571 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1572 const RISCVSubtarget &Subtarget) { 1573 assert(VT.isFixedLengthVector() && 1574 "Expected to convert into a fixed length vector!"); 1575 assert(V.getValueType().isScalableVector() && 1576 "Expected a scalable vector operand!"); 1577 SDLoc DL(V); 1578 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1579 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1580 } 1581 1582 /// Return the type of the mask type suitable for masking the provided 1583 /// vector type. This is simply an i1 element type vector of the same 1584 /// (possibly scalable) length. 1585 static MVT getMaskTypeFor(EVT VecVT) { 1586 assert(VecVT.isVector()); 1587 ElementCount EC = VecVT.getVectorElementCount(); 1588 return MVT::getVectorVT(MVT::i1, EC); 1589 } 1590 1591 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1592 /// vector length VL. . 1593 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1594 SelectionDAG &DAG) { 1595 MVT MaskVT = getMaskTypeFor(VecVT); 1596 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1597 } 1598 1599 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1600 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1601 // the vector type that it is contained in. 1602 static std::pair<SDValue, SDValue> 1603 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1604 const RISCVSubtarget &Subtarget) { 1605 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1606 MVT XLenVT = Subtarget.getXLenVT(); 1607 SDValue VL = VecVT.isFixedLengthVector() 1608 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1609 : DAG.getRegister(RISCV::X0, XLenVT); 1610 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1611 return {Mask, VL}; 1612 } 1613 1614 // As above but assuming the given type is a scalable vector type. 1615 static std::pair<SDValue, SDValue> 1616 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1617 const RISCVSubtarget &Subtarget) { 1618 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1619 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1620 } 1621 1622 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1623 // of either is (currently) supported. This can get us into an infinite loop 1624 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1625 // as a ..., etc. 1626 // Until either (or both) of these can reliably lower any node, reporting that 1627 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1628 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1629 // which is not desirable. 1630 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1631 EVT VT, unsigned DefinedValues) const { 1632 return false; 1633 } 1634 1635 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1636 const RISCVSubtarget &Subtarget) { 1637 // RISCV FP-to-int conversions saturate to the destination register size, but 1638 // don't produce 0 for nan. We can use a conversion instruction and fix the 1639 // nan case with a compare and a select. 1640 SDValue Src = Op.getOperand(0); 1641 1642 EVT DstVT = Op.getValueType(); 1643 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1644 1645 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1646 unsigned Opc; 1647 if (SatVT == DstVT) 1648 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1649 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1650 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1651 else 1652 return SDValue(); 1653 // FIXME: Support other SatVTs by clamping before or after the conversion. 1654 1655 SDLoc DL(Op); 1656 SDValue FpToInt = DAG.getNode( 1657 Opc, DL, DstVT, Src, 1658 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1659 1660 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1661 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1662 } 1663 1664 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1665 // and back. Taking care to avoid converting values that are nan or already 1666 // correct. 1667 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1668 // have FRM dependencies modeled yet. 1669 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1670 MVT VT = Op.getSimpleValueType(); 1671 assert(VT.isVector() && "Unexpected type"); 1672 1673 SDLoc DL(Op); 1674 1675 // Freeze the source since we are increasing the number of uses. 1676 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1677 1678 // Truncate to integer and convert back to FP. 1679 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1680 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1681 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1682 1683 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1684 1685 if (Op.getOpcode() == ISD::FCEIL) { 1686 // If the truncated value is the greater than or equal to the original 1687 // value, we've computed the ceil. Otherwise, we went the wrong way and 1688 // need to increase by 1. 1689 // FIXME: This should use a masked operation. Handle here or in isel? 1690 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1691 DAG.getConstantFP(1.0, DL, VT)); 1692 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1693 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1694 } else if (Op.getOpcode() == ISD::FFLOOR) { 1695 // If the truncated value is the less than or equal to the original value, 1696 // we've computed the floor. Otherwise, we went the wrong way and need to 1697 // decrease by 1. 1698 // FIXME: This should use a masked operation. Handle here or in isel? 1699 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1700 DAG.getConstantFP(1.0, DL, VT)); 1701 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1702 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1703 } 1704 1705 // Restore the original sign so that -0.0 is preserved. 1706 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1707 1708 // Determine the largest integer that can be represented exactly. This and 1709 // values larger than it don't have any fractional bits so don't need to 1710 // be converted. 1711 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1712 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1713 APFloat MaxVal = APFloat(FltSem); 1714 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1715 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1716 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1717 1718 // If abs(Src) was larger than MaxVal or nan, keep it. 1719 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1720 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1721 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1722 } 1723 1724 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1725 // This mode isn't supported in vector hardware on RISCV. But as long as we 1726 // aren't compiling with trapping math, we can emulate this with 1727 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1728 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1729 // dependencies modeled yet. 1730 // FIXME: Use masked operations to avoid final merge. 1731 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1732 MVT VT = Op.getSimpleValueType(); 1733 assert(VT.isVector() && "Unexpected type"); 1734 1735 SDLoc DL(Op); 1736 1737 // Freeze the source since we are increasing the number of uses. 1738 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1739 1740 // We do the conversion on the absolute value and fix the sign at the end. 1741 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1742 1743 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1744 bool Ignored; 1745 APFloat Point5Pred = APFloat(0.5f); 1746 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1747 Point5Pred.next(/*nextDown*/ true); 1748 1749 // Add the adjustment. 1750 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1751 DAG.getConstantFP(Point5Pred, DL, VT)); 1752 1753 // Truncate to integer and convert back to fp. 1754 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1755 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1756 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1757 1758 // Restore the original sign. 1759 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1760 1761 // Determine the largest integer that can be represented exactly. This and 1762 // values larger than it don't have any fractional bits so don't need to 1763 // be converted. 1764 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1765 APFloat MaxVal = APFloat(FltSem); 1766 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1767 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1768 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1769 1770 // If abs(Src) was larger than MaxVal or nan, keep it. 1771 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1772 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1773 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1774 } 1775 1776 struct VIDSequence { 1777 int64_t StepNumerator; 1778 unsigned StepDenominator; 1779 int64_t Addend; 1780 }; 1781 1782 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1783 // to the (non-zero) step S and start value X. This can be then lowered as the 1784 // RVV sequence (VID * S) + X, for example. 1785 // The step S is represented as an integer numerator divided by a positive 1786 // denominator. Note that the implementation currently only identifies 1787 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1788 // cannot detect 2/3, for example. 1789 // Note that this method will also match potentially unappealing index 1790 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1791 // determine whether this is worth generating code for. 1792 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1793 unsigned NumElts = Op.getNumOperands(); 1794 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1795 if (!Op.getValueType().isInteger()) 1796 return None; 1797 1798 Optional<unsigned> SeqStepDenom; 1799 Optional<int64_t> SeqStepNum, SeqAddend; 1800 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1801 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1802 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1803 // Assume undef elements match the sequence; we just have to be careful 1804 // when interpolating across them. 1805 if (Op.getOperand(Idx).isUndef()) 1806 continue; 1807 // The BUILD_VECTOR must be all constants. 1808 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1809 return None; 1810 1811 uint64_t Val = Op.getConstantOperandVal(Idx) & 1812 maskTrailingOnes<uint64_t>(EltSizeInBits); 1813 1814 if (PrevElt) { 1815 // Calculate the step since the last non-undef element, and ensure 1816 // it's consistent across the entire sequence. 1817 unsigned IdxDiff = Idx - PrevElt->second; 1818 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1819 1820 // A zero-value value difference means that we're somewhere in the middle 1821 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1822 // step change before evaluating the sequence. 1823 if (ValDiff == 0) 1824 continue; 1825 1826 int64_t Remainder = ValDiff % IdxDiff; 1827 // Normalize the step if it's greater than 1. 1828 if (Remainder != ValDiff) { 1829 // The difference must cleanly divide the element span. 1830 if (Remainder != 0) 1831 return None; 1832 ValDiff /= IdxDiff; 1833 IdxDiff = 1; 1834 } 1835 1836 if (!SeqStepNum) 1837 SeqStepNum = ValDiff; 1838 else if (ValDiff != SeqStepNum) 1839 return None; 1840 1841 if (!SeqStepDenom) 1842 SeqStepDenom = IdxDiff; 1843 else if (IdxDiff != *SeqStepDenom) 1844 return None; 1845 } 1846 1847 // Record this non-undef element for later. 1848 if (!PrevElt || PrevElt->first != Val) 1849 PrevElt = std::make_pair(Val, Idx); 1850 } 1851 1852 // We need to have logged a step for this to count as a legal index sequence. 1853 if (!SeqStepNum || !SeqStepDenom) 1854 return None; 1855 1856 // Loop back through the sequence and validate elements we might have skipped 1857 // while waiting for a valid step. While doing this, log any sequence addend. 1858 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1859 if (Op.getOperand(Idx).isUndef()) 1860 continue; 1861 uint64_t Val = Op.getConstantOperandVal(Idx) & 1862 maskTrailingOnes<uint64_t>(EltSizeInBits); 1863 uint64_t ExpectedVal = 1864 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1865 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1866 if (!SeqAddend) 1867 SeqAddend = Addend; 1868 else if (Addend != SeqAddend) 1869 return None; 1870 } 1871 1872 assert(SeqAddend && "Must have an addend if we have a step"); 1873 1874 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1875 } 1876 1877 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1878 // and lower it as a VRGATHER_VX_VL from the source vector. 1879 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1880 SelectionDAG &DAG, 1881 const RISCVSubtarget &Subtarget) { 1882 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1883 return SDValue(); 1884 SDValue Vec = SplatVal.getOperand(0); 1885 // Only perform this optimization on vectors of the same size for simplicity. 1886 if (Vec.getValueType() != VT) 1887 return SDValue(); 1888 SDValue Idx = SplatVal.getOperand(1); 1889 // The index must be a legal type. 1890 if (Idx.getValueType() != Subtarget.getXLenVT()) 1891 return SDValue(); 1892 1893 MVT ContainerVT = VT; 1894 if (VT.isFixedLengthVector()) { 1895 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1896 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1897 } 1898 1899 SDValue Mask, VL; 1900 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1901 1902 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1903 Idx, Mask, VL); 1904 1905 if (!VT.isFixedLengthVector()) 1906 return Gather; 1907 1908 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1909 } 1910 1911 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1912 const RISCVSubtarget &Subtarget) { 1913 MVT VT = Op.getSimpleValueType(); 1914 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1915 1916 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1917 1918 SDLoc DL(Op); 1919 SDValue Mask, VL; 1920 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1921 1922 MVT XLenVT = Subtarget.getXLenVT(); 1923 unsigned NumElts = Op.getNumOperands(); 1924 1925 if (VT.getVectorElementType() == MVT::i1) { 1926 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1927 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1928 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1929 } 1930 1931 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1932 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1933 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1934 } 1935 1936 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1937 // scalar integer chunks whose bit-width depends on the number of mask 1938 // bits and XLEN. 1939 // First, determine the most appropriate scalar integer type to use. This 1940 // is at most XLenVT, but may be shrunk to a smaller vector element type 1941 // according to the size of the final vector - use i8 chunks rather than 1942 // XLenVT if we're producing a v8i1. This results in more consistent 1943 // codegen across RV32 and RV64. 1944 unsigned NumViaIntegerBits = 1945 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1946 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1947 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1948 // If we have to use more than one INSERT_VECTOR_ELT then this 1949 // optimization is likely to increase code size; avoid peforming it in 1950 // such a case. We can use a load from a constant pool in this case. 1951 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1952 return SDValue(); 1953 // Now we can create our integer vector type. Note that it may be larger 1954 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1955 MVT IntegerViaVecVT = 1956 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1957 divideCeil(NumElts, NumViaIntegerBits)); 1958 1959 uint64_t Bits = 0; 1960 unsigned BitPos = 0, IntegerEltIdx = 0; 1961 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1962 1963 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1964 // Once we accumulate enough bits to fill our scalar type, insert into 1965 // our vector and clear our accumulated data. 1966 if (I != 0 && I % NumViaIntegerBits == 0) { 1967 if (NumViaIntegerBits <= 32) 1968 Bits = SignExtend64(Bits, 32); 1969 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1970 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1971 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1972 Bits = 0; 1973 BitPos = 0; 1974 IntegerEltIdx++; 1975 } 1976 SDValue V = Op.getOperand(I); 1977 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1978 Bits |= ((uint64_t)BitValue << BitPos); 1979 } 1980 1981 // Insert the (remaining) scalar value into position in our integer 1982 // vector type. 1983 if (NumViaIntegerBits <= 32) 1984 Bits = SignExtend64(Bits, 32); 1985 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1986 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1987 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1988 1989 if (NumElts < NumViaIntegerBits) { 1990 // If we're producing a smaller vector than our minimum legal integer 1991 // type, bitcast to the equivalent (known-legal) mask type, and extract 1992 // our final mask. 1993 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1994 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1995 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1996 DAG.getConstant(0, DL, XLenVT)); 1997 } else { 1998 // Else we must have produced an integer type with the same size as the 1999 // mask type; bitcast for the final result. 2000 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2001 Vec = DAG.getBitcast(VT, Vec); 2002 } 2003 2004 return Vec; 2005 } 2006 2007 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2008 // vector type, we have a legal equivalently-sized i8 type, so we can use 2009 // that. 2010 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2011 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2012 2013 SDValue WideVec; 2014 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2015 // For a splat, perform a scalar truncate before creating the wider 2016 // vector. 2017 assert(Splat.getValueType() == XLenVT && 2018 "Unexpected type for i1 splat value"); 2019 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2020 DAG.getConstant(1, DL, XLenVT)); 2021 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2022 } else { 2023 SmallVector<SDValue, 8> Ops(Op->op_values()); 2024 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2025 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2026 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2027 } 2028 2029 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2030 } 2031 2032 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2033 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2034 return Gather; 2035 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2036 : RISCVISD::VMV_V_X_VL; 2037 Splat = 2038 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2039 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2040 } 2041 2042 // Try and match index sequences, which we can lower to the vid instruction 2043 // with optional modifications. An all-undef vector is matched by 2044 // getSplatValue, above. 2045 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2046 int64_t StepNumerator = SimpleVID->StepNumerator; 2047 unsigned StepDenominator = SimpleVID->StepDenominator; 2048 int64_t Addend = SimpleVID->Addend; 2049 2050 assert(StepNumerator != 0 && "Invalid step"); 2051 bool Negate = false; 2052 int64_t SplatStepVal = StepNumerator; 2053 unsigned StepOpcode = ISD::MUL; 2054 if (StepNumerator != 1) { 2055 if (isPowerOf2_64(std::abs(StepNumerator))) { 2056 Negate = StepNumerator < 0; 2057 StepOpcode = ISD::SHL; 2058 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2059 } 2060 } 2061 2062 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2063 // threshold since it's the immediate value many RVV instructions accept. 2064 // There is no vmul.vi instruction so ensure multiply constant can fit in 2065 // a single addi instruction. 2066 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2067 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2068 isPowerOf2_32(StepDenominator) && 2069 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2070 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2071 // Convert right out of the scalable type so we can use standard ISD 2072 // nodes for the rest of the computation. If we used scalable types with 2073 // these, we'd lose the fixed-length vector info and generate worse 2074 // vsetvli code. 2075 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2076 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2077 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2078 SDValue SplatStep = DAG.getSplatBuildVector( 2079 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2080 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2081 } 2082 if (StepDenominator != 1) { 2083 SDValue SplatStep = DAG.getSplatBuildVector( 2084 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2085 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2086 } 2087 if (Addend != 0 || Negate) { 2088 SDValue SplatAddend = DAG.getSplatBuildVector( 2089 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2090 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2091 } 2092 return VID; 2093 } 2094 } 2095 2096 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2097 // when re-interpreted as a vector with a larger element type. For example, 2098 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2099 // could be instead splat as 2100 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2101 // TODO: This optimization could also work on non-constant splats, but it 2102 // would require bit-manipulation instructions to construct the splat value. 2103 SmallVector<SDValue> Sequence; 2104 unsigned EltBitSize = VT.getScalarSizeInBits(); 2105 const auto *BV = cast<BuildVectorSDNode>(Op); 2106 if (VT.isInteger() && EltBitSize < 64 && 2107 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2108 BV->getRepeatedSequence(Sequence) && 2109 (Sequence.size() * EltBitSize) <= 64) { 2110 unsigned SeqLen = Sequence.size(); 2111 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2112 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2113 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2114 ViaIntVT == MVT::i64) && 2115 "Unexpected sequence type"); 2116 2117 unsigned EltIdx = 0; 2118 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2119 uint64_t SplatValue = 0; 2120 // Construct the amalgamated value which can be splatted as this larger 2121 // vector type. 2122 for (const auto &SeqV : Sequence) { 2123 if (!SeqV.isUndef()) 2124 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2125 << (EltIdx * EltBitSize)); 2126 EltIdx++; 2127 } 2128 2129 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2130 // achieve better constant materializion. 2131 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2132 SplatValue = SignExtend64(SplatValue, 32); 2133 2134 // Since we can't introduce illegal i64 types at this stage, we can only 2135 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2136 // way we can use RVV instructions to splat. 2137 assert((ViaIntVT.bitsLE(XLenVT) || 2138 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2139 "Unexpected bitcast sequence"); 2140 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2141 SDValue ViaVL = 2142 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2143 MVT ViaContainerVT = 2144 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2145 SDValue Splat = 2146 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2147 DAG.getUNDEF(ViaContainerVT), 2148 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2149 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2150 return DAG.getBitcast(VT, Splat); 2151 } 2152 } 2153 2154 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2155 // which constitute a large proportion of the elements. In such cases we can 2156 // splat a vector with the dominant element and make up the shortfall with 2157 // INSERT_VECTOR_ELTs. 2158 // Note that this includes vectors of 2 elements by association. The 2159 // upper-most element is the "dominant" one, allowing us to use a splat to 2160 // "insert" the upper element, and an insert of the lower element at position 2161 // 0, which improves codegen. 2162 SDValue DominantValue; 2163 unsigned MostCommonCount = 0; 2164 DenseMap<SDValue, unsigned> ValueCounts; 2165 unsigned NumUndefElts = 2166 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2167 2168 // Track the number of scalar loads we know we'd be inserting, estimated as 2169 // any non-zero floating-point constant. Other kinds of element are either 2170 // already in registers or are materialized on demand. The threshold at which 2171 // a vector load is more desirable than several scalar materializion and 2172 // vector-insertion instructions is not known. 2173 unsigned NumScalarLoads = 0; 2174 2175 for (SDValue V : Op->op_values()) { 2176 if (V.isUndef()) 2177 continue; 2178 2179 ValueCounts.insert(std::make_pair(V, 0)); 2180 unsigned &Count = ValueCounts[V]; 2181 2182 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2183 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2184 2185 // Is this value dominant? In case of a tie, prefer the highest element as 2186 // it's cheaper to insert near the beginning of a vector than it is at the 2187 // end. 2188 if (++Count >= MostCommonCount) { 2189 DominantValue = V; 2190 MostCommonCount = Count; 2191 } 2192 } 2193 2194 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2195 unsigned NumDefElts = NumElts - NumUndefElts; 2196 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2197 2198 // Don't perform this optimization when optimizing for size, since 2199 // materializing elements and inserting them tends to cause code bloat. 2200 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2201 ((MostCommonCount > DominantValueCountThreshold) || 2202 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2203 // Start by splatting the most common element. 2204 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2205 2206 DenseSet<SDValue> Processed{DominantValue}; 2207 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2208 for (const auto &OpIdx : enumerate(Op->ops())) { 2209 const SDValue &V = OpIdx.value(); 2210 if (V.isUndef() || !Processed.insert(V).second) 2211 continue; 2212 if (ValueCounts[V] == 1) { 2213 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2214 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2215 } else { 2216 // Blend in all instances of this value using a VSELECT, using a 2217 // mask where each bit signals whether that element is the one 2218 // we're after. 2219 SmallVector<SDValue> Ops; 2220 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2221 return DAG.getConstant(V == V1, DL, XLenVT); 2222 }); 2223 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2224 DAG.getBuildVector(SelMaskTy, DL, Ops), 2225 DAG.getSplatBuildVector(VT, DL, V), Vec); 2226 } 2227 } 2228 2229 return Vec; 2230 } 2231 2232 return SDValue(); 2233 } 2234 2235 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2236 SDValue Lo, SDValue Hi, SDValue VL, 2237 SelectionDAG &DAG) { 2238 if (!Passthru) 2239 Passthru = DAG.getUNDEF(VT); 2240 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2241 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2242 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2243 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2244 // node in order to try and match RVV vector/scalar instructions. 2245 if ((LoC >> 31) == HiC) 2246 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2247 2248 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2249 // vmv.v.x whose EEW = 32 to lower it. 2250 auto *Const = dyn_cast<ConstantSDNode>(VL); 2251 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2252 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2253 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2254 // access the subtarget here now. 2255 auto InterVec = DAG.getNode( 2256 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2257 DAG.getRegister(RISCV::X0, MVT::i32)); 2258 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2259 } 2260 } 2261 2262 // Fall back to a stack store and stride x0 vector load. 2263 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2264 Hi, VL); 2265 } 2266 2267 // Called by type legalization to handle splat of i64 on RV32. 2268 // FIXME: We can optimize this when the type has sign or zero bits in one 2269 // of the halves. 2270 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2271 SDValue Scalar, SDValue VL, 2272 SelectionDAG &DAG) { 2273 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2274 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2275 DAG.getConstant(0, DL, MVT::i32)); 2276 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2277 DAG.getConstant(1, DL, MVT::i32)); 2278 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2279 } 2280 2281 // This function lowers a splat of a scalar operand Splat with the vector 2282 // length VL. It ensures the final sequence is type legal, which is useful when 2283 // lowering a splat after type legalization. 2284 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2285 MVT VT, SDLoc DL, SelectionDAG &DAG, 2286 const RISCVSubtarget &Subtarget) { 2287 bool HasPassthru = Passthru && !Passthru.isUndef(); 2288 if (!HasPassthru && !Passthru) 2289 Passthru = DAG.getUNDEF(VT); 2290 if (VT.isFloatingPoint()) { 2291 // If VL is 1, we could use vfmv.s.f. 2292 if (isOneConstant(VL)) 2293 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2294 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2295 } 2296 2297 MVT XLenVT = Subtarget.getXLenVT(); 2298 2299 // Simplest case is that the operand needs to be promoted to XLenVT. 2300 if (Scalar.getValueType().bitsLE(XLenVT)) { 2301 // If the operand is a constant, sign extend to increase our chances 2302 // of being able to use a .vi instruction. ANY_EXTEND would become a 2303 // a zero extend and the simm5 check in isel would fail. 2304 // FIXME: Should we ignore the upper bits in isel instead? 2305 unsigned ExtOpc = 2306 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2307 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2308 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2309 // If VL is 1 and the scalar value won't benefit from immediate, we could 2310 // use vmv.s.x. 2311 if (isOneConstant(VL) && 2312 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2313 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2314 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2315 } 2316 2317 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2318 "Unexpected scalar for splat lowering!"); 2319 2320 if (isOneConstant(VL) && isNullConstant(Scalar)) 2321 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2322 DAG.getConstant(0, DL, XLenVT), VL); 2323 2324 // Otherwise use the more complicated splatting algorithm. 2325 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2326 } 2327 2328 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2329 const RISCVSubtarget &Subtarget) { 2330 // We need to be able to widen elements to the next larger integer type. 2331 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2332 return false; 2333 2334 int Size = Mask.size(); 2335 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2336 2337 int Srcs[] = {-1, -1}; 2338 for (int i = 0; i != Size; ++i) { 2339 // Ignore undef elements. 2340 if (Mask[i] < 0) 2341 continue; 2342 2343 // Is this an even or odd element. 2344 int Pol = i % 2; 2345 2346 // Ensure we consistently use the same source for this element polarity. 2347 int Src = Mask[i] / Size; 2348 if (Srcs[Pol] < 0) 2349 Srcs[Pol] = Src; 2350 if (Srcs[Pol] != Src) 2351 return false; 2352 2353 // Make sure the element within the source is appropriate for this element 2354 // in the destination. 2355 int Elt = Mask[i] % Size; 2356 if (Elt != i / 2) 2357 return false; 2358 } 2359 2360 // We need to find a source for each polarity and they can't be the same. 2361 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2362 return false; 2363 2364 // Swap the sources if the second source was in the even polarity. 2365 SwapSources = Srcs[0] > Srcs[1]; 2366 2367 return true; 2368 } 2369 2370 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2371 /// and then extract the original number of elements from the rotated result. 2372 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2373 /// returned rotation amount is for a rotate right, where elements move from 2374 /// higher elements to lower elements. \p LoSrc indicates the first source 2375 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2376 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2377 /// 0 or 1 if a rotation is found. 2378 /// 2379 /// NOTE: We talk about rotate to the right which matches how bit shift and 2380 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2381 /// and the table below write vectors with the lowest elements on the left. 2382 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2383 int Size = Mask.size(); 2384 2385 // We need to detect various ways of spelling a rotation: 2386 // [11, 12, 13, 14, 15, 0, 1, 2] 2387 // [-1, 12, 13, 14, -1, -1, 1, -1] 2388 // [-1, -1, -1, -1, -1, -1, 1, 2] 2389 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2390 // [-1, 4, 5, 6, -1, -1, 9, -1] 2391 // [-1, 4, 5, 6, -1, -1, -1, -1] 2392 int Rotation = 0; 2393 LoSrc = -1; 2394 HiSrc = -1; 2395 for (int i = 0; i != Size; ++i) { 2396 int M = Mask[i]; 2397 if (M < 0) 2398 continue; 2399 2400 // Determine where a rotate vector would have started. 2401 int StartIdx = i - (M % Size); 2402 // The identity rotation isn't interesting, stop. 2403 if (StartIdx == 0) 2404 return -1; 2405 2406 // If we found the tail of a vector the rotation must be the missing 2407 // front. If we found the head of a vector, it must be how much of the 2408 // head. 2409 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2410 2411 if (Rotation == 0) 2412 Rotation = CandidateRotation; 2413 else if (Rotation != CandidateRotation) 2414 // The rotations don't match, so we can't match this mask. 2415 return -1; 2416 2417 // Compute which value this mask is pointing at. 2418 int MaskSrc = M < Size ? 0 : 1; 2419 2420 // Compute which of the two target values this index should be assigned to. 2421 // This reflects whether the high elements are remaining or the low elemnts 2422 // are remaining. 2423 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2424 2425 // Either set up this value if we've not encountered it before, or check 2426 // that it remains consistent. 2427 if (TargetSrc < 0) 2428 TargetSrc = MaskSrc; 2429 else if (TargetSrc != MaskSrc) 2430 // This may be a rotation, but it pulls from the inputs in some 2431 // unsupported interleaving. 2432 return -1; 2433 } 2434 2435 // Check that we successfully analyzed the mask, and normalize the results. 2436 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2437 assert((LoSrc >= 0 || HiSrc >= 0) && 2438 "Failed to find a rotated input vector!"); 2439 2440 return Rotation; 2441 } 2442 2443 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2444 const RISCVSubtarget &Subtarget) { 2445 SDValue V1 = Op.getOperand(0); 2446 SDValue V2 = Op.getOperand(1); 2447 SDLoc DL(Op); 2448 MVT XLenVT = Subtarget.getXLenVT(); 2449 MVT VT = Op.getSimpleValueType(); 2450 unsigned NumElts = VT.getVectorNumElements(); 2451 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2452 2453 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2454 2455 SDValue TrueMask, VL; 2456 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2457 2458 if (SVN->isSplat()) { 2459 const int Lane = SVN->getSplatIndex(); 2460 if (Lane >= 0) { 2461 MVT SVT = VT.getVectorElementType(); 2462 2463 // Turn splatted vector load into a strided load with an X0 stride. 2464 SDValue V = V1; 2465 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2466 // with undef. 2467 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2468 int Offset = Lane; 2469 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2470 int OpElements = 2471 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2472 V = V.getOperand(Offset / OpElements); 2473 Offset %= OpElements; 2474 } 2475 2476 // We need to ensure the load isn't atomic or volatile. 2477 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2478 auto *Ld = cast<LoadSDNode>(V); 2479 Offset *= SVT.getStoreSize(); 2480 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2481 TypeSize::Fixed(Offset), DL); 2482 2483 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2484 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2485 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2486 SDValue IntID = 2487 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2488 SDValue Ops[] = {Ld->getChain(), 2489 IntID, 2490 DAG.getUNDEF(ContainerVT), 2491 NewAddr, 2492 DAG.getRegister(RISCV::X0, XLenVT), 2493 VL}; 2494 SDValue NewLoad = DAG.getMemIntrinsicNode( 2495 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2496 DAG.getMachineFunction().getMachineMemOperand( 2497 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2498 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2499 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2500 } 2501 2502 // Otherwise use a scalar load and splat. This will give the best 2503 // opportunity to fold a splat into the operation. ISel can turn it into 2504 // the x0 strided load if we aren't able to fold away the select. 2505 if (SVT.isFloatingPoint()) 2506 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2507 Ld->getPointerInfo().getWithOffset(Offset), 2508 Ld->getOriginalAlign(), 2509 Ld->getMemOperand()->getFlags()); 2510 else 2511 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2512 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2513 Ld->getOriginalAlign(), 2514 Ld->getMemOperand()->getFlags()); 2515 DAG.makeEquivalentMemoryOrdering(Ld, V); 2516 2517 unsigned Opc = 2518 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2519 SDValue Splat = 2520 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2521 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2522 } 2523 2524 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2525 assert(Lane < (int)NumElts && "Unexpected lane!"); 2526 SDValue Gather = 2527 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2528 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2529 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2530 } 2531 } 2532 2533 ArrayRef<int> Mask = SVN->getMask(); 2534 2535 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2536 // be undef which can be handled with a single SLIDEDOWN/UP. 2537 int LoSrc, HiSrc; 2538 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2539 if (Rotation > 0) { 2540 SDValue LoV, HiV; 2541 if (LoSrc >= 0) { 2542 LoV = LoSrc == 0 ? V1 : V2; 2543 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2544 } 2545 if (HiSrc >= 0) { 2546 HiV = HiSrc == 0 ? V1 : V2; 2547 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2548 } 2549 2550 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2551 // to slide LoV up by (NumElts - Rotation). 2552 unsigned InvRotate = NumElts - Rotation; 2553 2554 SDValue Res = DAG.getUNDEF(ContainerVT); 2555 if (HiV) { 2556 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2557 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2558 // causes multiple vsetvlis in some test cases such as lowering 2559 // reduce.mul 2560 SDValue DownVL = VL; 2561 if (LoV) 2562 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2563 Res = 2564 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2565 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2566 } 2567 if (LoV) 2568 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2569 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2570 2571 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2572 } 2573 2574 // Detect an interleave shuffle and lower to 2575 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2576 bool SwapSources; 2577 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2578 // Swap sources if needed. 2579 if (SwapSources) 2580 std::swap(V1, V2); 2581 2582 // Extract the lower half of the vectors. 2583 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2584 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2585 DAG.getConstant(0, DL, XLenVT)); 2586 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2587 DAG.getConstant(0, DL, XLenVT)); 2588 2589 // Double the element width and halve the number of elements in an int type. 2590 unsigned EltBits = VT.getScalarSizeInBits(); 2591 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2592 MVT WideIntVT = 2593 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2594 // Convert this to a scalable vector. We need to base this on the 2595 // destination size to ensure there's always a type with a smaller LMUL. 2596 MVT WideIntContainerVT = 2597 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2598 2599 // Convert sources to scalable vectors with the same element count as the 2600 // larger type. 2601 MVT HalfContainerVT = MVT::getVectorVT( 2602 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2603 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2604 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2605 2606 // Cast sources to integer. 2607 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2608 MVT IntHalfVT = 2609 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2610 V1 = DAG.getBitcast(IntHalfVT, V1); 2611 V2 = DAG.getBitcast(IntHalfVT, V2); 2612 2613 // Freeze V2 since we use it twice and we need to be sure that the add and 2614 // multiply see the same value. 2615 V2 = DAG.getFreeze(V2); 2616 2617 // Recreate TrueMask using the widened type's element count. 2618 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2619 2620 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2621 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2622 V2, TrueMask, VL); 2623 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2624 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2625 DAG.getUNDEF(IntHalfVT), 2626 DAG.getAllOnesConstant(DL, XLenVT)); 2627 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2628 V2, Multiplier, TrueMask, VL); 2629 // Add the new copies to our previous addition giving us 2^eltbits copies of 2630 // V2. This is equivalent to shifting V2 left by eltbits. This should 2631 // combine with the vwmulu.vv above to form vwmaccu.vv. 2632 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2633 TrueMask, VL); 2634 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2635 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2636 // vector VT. 2637 ContainerVT = 2638 MVT::getVectorVT(VT.getVectorElementType(), 2639 WideIntContainerVT.getVectorElementCount() * 2); 2640 Add = DAG.getBitcast(ContainerVT, Add); 2641 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2642 } 2643 2644 // Detect shuffles which can be re-expressed as vector selects; these are 2645 // shuffles in which each element in the destination is taken from an element 2646 // at the corresponding index in either source vectors. 2647 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2648 int MaskIndex = MaskIdx.value(); 2649 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2650 }); 2651 2652 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2653 2654 SmallVector<SDValue> MaskVals; 2655 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2656 // merged with a second vrgather. 2657 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2658 2659 // By default we preserve the original operand order, and use a mask to 2660 // select LHS as true and RHS as false. However, since RVV vector selects may 2661 // feature splats but only on the LHS, we may choose to invert our mask and 2662 // instead select between RHS and LHS. 2663 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2664 bool InvertMask = IsSelect == SwapOps; 2665 2666 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2667 // half. 2668 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2669 2670 // Now construct the mask that will be used by the vselect or blended 2671 // vrgather operation. For vrgathers, construct the appropriate indices into 2672 // each vector. 2673 for (int MaskIndex : Mask) { 2674 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2675 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2676 if (!IsSelect) { 2677 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2678 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2679 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2680 : DAG.getUNDEF(XLenVT)); 2681 GatherIndicesRHS.push_back( 2682 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2683 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2684 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2685 ++LHSIndexCounts[MaskIndex]; 2686 if (!IsLHSOrUndefIndex) 2687 ++RHSIndexCounts[MaskIndex - NumElts]; 2688 } 2689 } 2690 2691 if (SwapOps) { 2692 std::swap(V1, V2); 2693 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2694 } 2695 2696 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2697 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2698 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2699 2700 if (IsSelect) 2701 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2702 2703 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2704 // On such a large vector we're unable to use i8 as the index type. 2705 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2706 // may involve vector splitting if we're already at LMUL=8, or our 2707 // user-supplied maximum fixed-length LMUL. 2708 return SDValue(); 2709 } 2710 2711 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2712 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2713 MVT IndexVT = VT.changeTypeToInteger(); 2714 // Since we can't introduce illegal index types at this stage, use i16 and 2715 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2716 // than XLenVT. 2717 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2718 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2719 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2720 } 2721 2722 MVT IndexContainerVT = 2723 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2724 2725 SDValue Gather; 2726 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2727 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2728 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2729 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2730 Subtarget); 2731 } else { 2732 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2733 // If only one index is used, we can use a "splat" vrgather. 2734 // TODO: We can splat the most-common index and fix-up any stragglers, if 2735 // that's beneficial. 2736 if (LHSIndexCounts.size() == 1) { 2737 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2738 Gather = 2739 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2740 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2741 } else { 2742 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2743 LHSIndices = 2744 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2745 2746 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2747 TrueMask, VL); 2748 } 2749 } 2750 2751 // If a second vector operand is used by this shuffle, blend it in with an 2752 // additional vrgather. 2753 if (!V2.isUndef()) { 2754 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2755 // If only one index is used, we can use a "splat" vrgather. 2756 // TODO: We can splat the most-common index and fix-up any stragglers, if 2757 // that's beneficial. 2758 if (RHSIndexCounts.size() == 1) { 2759 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2760 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2761 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2762 } else { 2763 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2764 RHSIndices = 2765 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2766 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2767 VL); 2768 } 2769 2770 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2771 SelectMask = 2772 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2773 2774 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2775 Gather, VL); 2776 } 2777 2778 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2779 } 2780 2781 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2782 // Support splats for any type. These should type legalize well. 2783 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2784 return true; 2785 2786 // Only support legal VTs for other shuffles for now. 2787 if (!isTypeLegal(VT)) 2788 return false; 2789 2790 MVT SVT = VT.getSimpleVT(); 2791 2792 bool SwapSources; 2793 int LoSrc, HiSrc; 2794 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2795 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2796 } 2797 2798 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2799 SDLoc DL, SelectionDAG &DAG, 2800 const RISCVSubtarget &Subtarget) { 2801 if (VT.isScalableVector()) 2802 return DAG.getFPExtendOrRound(Op, DL, VT); 2803 assert(VT.isFixedLengthVector() && 2804 "Unexpected value type for RVV FP extend/round lowering"); 2805 SDValue Mask, VL; 2806 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2807 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2808 ? RISCVISD::FP_EXTEND_VL 2809 : RISCVISD::FP_ROUND_VL; 2810 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2811 } 2812 2813 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2814 // the exponent. 2815 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2816 MVT VT = Op.getSimpleValueType(); 2817 unsigned EltSize = VT.getScalarSizeInBits(); 2818 SDValue Src = Op.getOperand(0); 2819 SDLoc DL(Op); 2820 2821 // We need a FP type that can represent the value. 2822 // TODO: Use f16 for i8 when possible? 2823 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2824 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2825 2826 // Legal types should have been checked in the RISCVTargetLowering 2827 // constructor. 2828 // TODO: Splitting may make sense in some cases. 2829 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2830 "Expected legal float type!"); 2831 2832 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2833 // The trailing zero count is equal to log2 of this single bit value. 2834 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2835 SDValue Neg = 2836 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2837 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2838 } 2839 2840 // We have a legal FP type, convert to it. 2841 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2842 // Bitcast to integer and shift the exponent to the LSB. 2843 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2844 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2845 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2846 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2847 DAG.getConstant(ShiftAmt, DL, IntVT)); 2848 // Truncate back to original type to allow vnsrl. 2849 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2850 // The exponent contains log2 of the value in biased form. 2851 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2852 2853 // For trailing zeros, we just need to subtract the bias. 2854 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2855 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2856 DAG.getConstant(ExponentBias, DL, VT)); 2857 2858 // For leading zeros, we need to remove the bias and convert from log2 to 2859 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2860 unsigned Adjust = ExponentBias + (EltSize - 1); 2861 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2862 } 2863 2864 // While RVV has alignment restrictions, we should always be able to load as a 2865 // legal equivalently-sized byte-typed vector instead. This method is 2866 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2867 // the load is already correctly-aligned, it returns SDValue(). 2868 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2869 SelectionDAG &DAG) const { 2870 auto *Load = cast<LoadSDNode>(Op); 2871 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2872 2873 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2874 Load->getMemoryVT(), 2875 *Load->getMemOperand())) 2876 return SDValue(); 2877 2878 SDLoc DL(Op); 2879 MVT VT = Op.getSimpleValueType(); 2880 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2881 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2882 "Unexpected unaligned RVV load type"); 2883 MVT NewVT = 2884 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2885 assert(NewVT.isValid() && 2886 "Expecting equally-sized RVV vector types to be legal"); 2887 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2888 Load->getPointerInfo(), Load->getOriginalAlign(), 2889 Load->getMemOperand()->getFlags()); 2890 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2891 } 2892 2893 // While RVV has alignment restrictions, we should always be able to store as a 2894 // legal equivalently-sized byte-typed vector instead. This method is 2895 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2896 // returns SDValue() if the store is already correctly aligned. 2897 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2898 SelectionDAG &DAG) const { 2899 auto *Store = cast<StoreSDNode>(Op); 2900 assert(Store && Store->getValue().getValueType().isVector() && 2901 "Expected vector store"); 2902 2903 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2904 Store->getMemoryVT(), 2905 *Store->getMemOperand())) 2906 return SDValue(); 2907 2908 SDLoc DL(Op); 2909 SDValue StoredVal = Store->getValue(); 2910 MVT VT = StoredVal.getSimpleValueType(); 2911 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2912 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2913 "Unexpected unaligned RVV store type"); 2914 MVT NewVT = 2915 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2916 assert(NewVT.isValid() && 2917 "Expecting equally-sized RVV vector types to be legal"); 2918 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2919 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2920 Store->getPointerInfo(), Store->getOriginalAlign(), 2921 Store->getMemOperand()->getFlags()); 2922 } 2923 2924 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2925 SelectionDAG &DAG) const { 2926 switch (Op.getOpcode()) { 2927 default: 2928 report_fatal_error("unimplemented operand"); 2929 case ISD::GlobalAddress: 2930 return lowerGlobalAddress(Op, DAG); 2931 case ISD::BlockAddress: 2932 return lowerBlockAddress(Op, DAG); 2933 case ISD::ConstantPool: 2934 return lowerConstantPool(Op, DAG); 2935 case ISD::JumpTable: 2936 return lowerJumpTable(Op, DAG); 2937 case ISD::GlobalTLSAddress: 2938 return lowerGlobalTLSAddress(Op, DAG); 2939 case ISD::SELECT: 2940 return lowerSELECT(Op, DAG); 2941 case ISD::BRCOND: 2942 return lowerBRCOND(Op, DAG); 2943 case ISD::VASTART: 2944 return lowerVASTART(Op, DAG); 2945 case ISD::FRAMEADDR: 2946 return lowerFRAMEADDR(Op, DAG); 2947 case ISD::RETURNADDR: 2948 return lowerRETURNADDR(Op, DAG); 2949 case ISD::SHL_PARTS: 2950 return lowerShiftLeftParts(Op, DAG); 2951 case ISD::SRA_PARTS: 2952 return lowerShiftRightParts(Op, DAG, true); 2953 case ISD::SRL_PARTS: 2954 return lowerShiftRightParts(Op, DAG, false); 2955 case ISD::BITCAST: { 2956 SDLoc DL(Op); 2957 EVT VT = Op.getValueType(); 2958 SDValue Op0 = Op.getOperand(0); 2959 EVT Op0VT = Op0.getValueType(); 2960 MVT XLenVT = Subtarget.getXLenVT(); 2961 if (VT.isFixedLengthVector()) { 2962 // We can handle fixed length vector bitcasts with a simple replacement 2963 // in isel. 2964 if (Op0VT.isFixedLengthVector()) 2965 return Op; 2966 // When bitcasting from scalar to fixed-length vector, insert the scalar 2967 // into a one-element vector of the result type, and perform a vector 2968 // bitcast. 2969 if (!Op0VT.isVector()) { 2970 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2971 if (!isTypeLegal(BVT)) 2972 return SDValue(); 2973 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2974 DAG.getUNDEF(BVT), Op0, 2975 DAG.getConstant(0, DL, XLenVT))); 2976 } 2977 return SDValue(); 2978 } 2979 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2980 // thus: bitcast the vector to a one-element vector type whose element type 2981 // is the same as the result type, and extract the first element. 2982 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2983 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2984 if (!isTypeLegal(BVT)) 2985 return SDValue(); 2986 SDValue BVec = DAG.getBitcast(BVT, Op0); 2987 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2988 DAG.getConstant(0, DL, XLenVT)); 2989 } 2990 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2991 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2992 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2993 return FPConv; 2994 } 2995 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2996 Subtarget.hasStdExtF()) { 2997 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2998 SDValue FPConv = 2999 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3000 return FPConv; 3001 } 3002 return SDValue(); 3003 } 3004 case ISD::INTRINSIC_WO_CHAIN: 3005 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3006 case ISD::INTRINSIC_W_CHAIN: 3007 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3008 case ISD::INTRINSIC_VOID: 3009 return LowerINTRINSIC_VOID(Op, DAG); 3010 case ISD::BSWAP: 3011 case ISD::BITREVERSE: { 3012 MVT VT = Op.getSimpleValueType(); 3013 SDLoc DL(Op); 3014 if (Subtarget.hasStdExtZbp()) { 3015 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3016 // Start with the maximum immediate value which is the bitwidth - 1. 3017 unsigned Imm = VT.getSizeInBits() - 1; 3018 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3019 if (Op.getOpcode() == ISD::BSWAP) 3020 Imm &= ~0x7U; 3021 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3022 DAG.getConstant(Imm, DL, VT)); 3023 } 3024 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3025 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3026 // Expand bitreverse to a bswap(rev8) followed by brev8. 3027 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3028 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3029 // as brev8 by an isel pattern. 3030 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3031 DAG.getConstant(7, DL, VT)); 3032 } 3033 case ISD::FSHL: 3034 case ISD::FSHR: { 3035 MVT VT = Op.getSimpleValueType(); 3036 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3037 SDLoc DL(Op); 3038 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3039 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3040 // accidentally setting the extra bit. 3041 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3042 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3043 DAG.getConstant(ShAmtWidth, DL, VT)); 3044 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3045 // instruction use different orders. fshl will return its first operand for 3046 // shift of zero, fshr will return its second operand. fsl and fsr both 3047 // return rs1 so the ISD nodes need to have different operand orders. 3048 // Shift amount is in rs2. 3049 SDValue Op0 = Op.getOperand(0); 3050 SDValue Op1 = Op.getOperand(1); 3051 unsigned Opc = RISCVISD::FSL; 3052 if (Op.getOpcode() == ISD::FSHR) { 3053 std::swap(Op0, Op1); 3054 Opc = RISCVISD::FSR; 3055 } 3056 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3057 } 3058 case ISD::TRUNCATE: 3059 // Only custom-lower vector truncates 3060 if (!Op.getSimpleValueType().isVector()) 3061 return Op; 3062 return lowerVectorTruncLike(Op, DAG); 3063 case ISD::ANY_EXTEND: 3064 case ISD::ZERO_EXTEND: 3065 if (Op.getOperand(0).getValueType().isVector() && 3066 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3067 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3068 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3069 case ISD::SIGN_EXTEND: 3070 if (Op.getOperand(0).getValueType().isVector() && 3071 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3072 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3073 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3074 case ISD::SPLAT_VECTOR_PARTS: 3075 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3076 case ISD::INSERT_VECTOR_ELT: 3077 return lowerINSERT_VECTOR_ELT(Op, DAG); 3078 case ISD::EXTRACT_VECTOR_ELT: 3079 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3080 case ISD::VSCALE: { 3081 MVT VT = Op.getSimpleValueType(); 3082 SDLoc DL(Op); 3083 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3084 // We define our scalable vector types for lmul=1 to use a 64 bit known 3085 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3086 // vscale as VLENB / 8. 3087 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3088 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3089 report_fatal_error("Support for VLEN==32 is incomplete."); 3090 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3091 // We assume VLENB is a multiple of 8. We manually choose the best shift 3092 // here because SimplifyDemandedBits isn't always able to simplify it. 3093 uint64_t Val = Op.getConstantOperandVal(0); 3094 if (isPowerOf2_64(Val)) { 3095 uint64_t Log2 = Log2_64(Val); 3096 if (Log2 < 3) 3097 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3098 DAG.getConstant(3 - Log2, DL, VT)); 3099 if (Log2 > 3) 3100 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3101 DAG.getConstant(Log2 - 3, DL, VT)); 3102 return VLENB; 3103 } 3104 // If the multiplier is a multiple of 8, scale it down to avoid needing 3105 // to shift the VLENB value. 3106 if ((Val % 8) == 0) 3107 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3108 DAG.getConstant(Val / 8, DL, VT)); 3109 } 3110 3111 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3112 DAG.getConstant(3, DL, VT)); 3113 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3114 } 3115 case ISD::FPOWI: { 3116 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3117 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3118 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3119 Op.getOperand(1).getValueType() == MVT::i32) { 3120 SDLoc DL(Op); 3121 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3122 SDValue Powi = 3123 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3124 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3125 DAG.getIntPtrConstant(0, DL)); 3126 } 3127 return SDValue(); 3128 } 3129 case ISD::FP_EXTEND: { 3130 // RVV can only do fp_extend to types double the size as the source. We 3131 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3132 // via f32. 3133 SDLoc DL(Op); 3134 MVT VT = Op.getSimpleValueType(); 3135 SDValue Src = Op.getOperand(0); 3136 MVT SrcVT = Src.getSimpleValueType(); 3137 3138 // Prepare any fixed-length vector operands. 3139 MVT ContainerVT = VT; 3140 if (SrcVT.isFixedLengthVector()) { 3141 ContainerVT = getContainerForFixedLengthVector(VT); 3142 MVT SrcContainerVT = 3143 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3144 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3145 } 3146 3147 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3148 SrcVT.getVectorElementType() != MVT::f16) { 3149 // For scalable vectors, we only need to close the gap between 3150 // vXf16->vXf64. 3151 if (!VT.isFixedLengthVector()) 3152 return Op; 3153 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3154 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3155 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3156 } 3157 3158 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3159 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3160 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3161 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3162 3163 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3164 DL, DAG, Subtarget); 3165 if (VT.isFixedLengthVector()) 3166 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3167 return Extend; 3168 } 3169 case ISD::FP_ROUND: 3170 if (!Op.getValueType().isVector()) 3171 return Op; 3172 return lowerVectorFPRoundLike(Op, DAG); 3173 case ISD::FP_TO_SINT: 3174 case ISD::FP_TO_UINT: 3175 case ISD::SINT_TO_FP: 3176 case ISD::UINT_TO_FP: { 3177 // RVV can only do fp<->int conversions to types half/double the size as 3178 // the source. We custom-lower any conversions that do two hops into 3179 // sequences. 3180 MVT VT = Op.getSimpleValueType(); 3181 if (!VT.isVector()) 3182 return Op; 3183 SDLoc DL(Op); 3184 SDValue Src = Op.getOperand(0); 3185 MVT EltVT = VT.getVectorElementType(); 3186 MVT SrcVT = Src.getSimpleValueType(); 3187 MVT SrcEltVT = SrcVT.getVectorElementType(); 3188 unsigned EltSize = EltVT.getSizeInBits(); 3189 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3190 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3191 "Unexpected vector element types"); 3192 3193 bool IsInt2FP = SrcEltVT.isInteger(); 3194 // Widening conversions 3195 if (EltSize > (2 * SrcEltSize)) { 3196 if (IsInt2FP) { 3197 // Do a regular integer sign/zero extension then convert to float. 3198 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3199 VT.getVectorElementCount()); 3200 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3201 ? ISD::ZERO_EXTEND 3202 : ISD::SIGN_EXTEND; 3203 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3204 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3205 } 3206 // FP2Int 3207 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3208 // Do one doubling fp_extend then complete the operation by converting 3209 // to int. 3210 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3211 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3212 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3213 } 3214 3215 // Narrowing conversions 3216 if (SrcEltSize > (2 * EltSize)) { 3217 if (IsInt2FP) { 3218 // One narrowing int_to_fp, then an fp_round. 3219 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3220 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3221 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3222 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3223 } 3224 // FP2Int 3225 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3226 // representable by the integer, the result is poison. 3227 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3228 VT.getVectorElementCount()); 3229 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3230 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3231 } 3232 3233 // Scalable vectors can exit here. Patterns will handle equally-sized 3234 // conversions halving/doubling ones. 3235 if (!VT.isFixedLengthVector()) 3236 return Op; 3237 3238 // For fixed-length vectors we lower to a custom "VL" node. 3239 unsigned RVVOpc = 0; 3240 switch (Op.getOpcode()) { 3241 default: 3242 llvm_unreachable("Impossible opcode"); 3243 case ISD::FP_TO_SINT: 3244 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3245 break; 3246 case ISD::FP_TO_UINT: 3247 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3248 break; 3249 case ISD::SINT_TO_FP: 3250 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3251 break; 3252 case ISD::UINT_TO_FP: 3253 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3254 break; 3255 } 3256 3257 MVT ContainerVT, SrcContainerVT; 3258 // Derive the reference container type from the larger vector type. 3259 if (SrcEltSize > EltSize) { 3260 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3261 ContainerVT = 3262 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3263 } else { 3264 ContainerVT = getContainerForFixedLengthVector(VT); 3265 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3266 } 3267 3268 SDValue Mask, VL; 3269 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3270 3271 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3272 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3273 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3274 } 3275 case ISD::FP_TO_SINT_SAT: 3276 case ISD::FP_TO_UINT_SAT: 3277 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3278 case ISD::FTRUNC: 3279 case ISD::FCEIL: 3280 case ISD::FFLOOR: 3281 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3282 case ISD::FROUND: 3283 return lowerFROUND(Op, DAG); 3284 case ISD::VECREDUCE_ADD: 3285 case ISD::VECREDUCE_UMAX: 3286 case ISD::VECREDUCE_SMAX: 3287 case ISD::VECREDUCE_UMIN: 3288 case ISD::VECREDUCE_SMIN: 3289 return lowerVECREDUCE(Op, DAG); 3290 case ISD::VECREDUCE_AND: 3291 case ISD::VECREDUCE_OR: 3292 case ISD::VECREDUCE_XOR: 3293 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3294 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3295 return lowerVECREDUCE(Op, DAG); 3296 case ISD::VECREDUCE_FADD: 3297 case ISD::VECREDUCE_SEQ_FADD: 3298 case ISD::VECREDUCE_FMIN: 3299 case ISD::VECREDUCE_FMAX: 3300 return lowerFPVECREDUCE(Op, DAG); 3301 case ISD::VP_REDUCE_ADD: 3302 case ISD::VP_REDUCE_UMAX: 3303 case ISD::VP_REDUCE_SMAX: 3304 case ISD::VP_REDUCE_UMIN: 3305 case ISD::VP_REDUCE_SMIN: 3306 case ISD::VP_REDUCE_FADD: 3307 case ISD::VP_REDUCE_SEQ_FADD: 3308 case ISD::VP_REDUCE_FMIN: 3309 case ISD::VP_REDUCE_FMAX: 3310 return lowerVPREDUCE(Op, DAG); 3311 case ISD::VP_REDUCE_AND: 3312 case ISD::VP_REDUCE_OR: 3313 case ISD::VP_REDUCE_XOR: 3314 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3315 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3316 return lowerVPREDUCE(Op, DAG); 3317 case ISD::INSERT_SUBVECTOR: 3318 return lowerINSERT_SUBVECTOR(Op, DAG); 3319 case ISD::EXTRACT_SUBVECTOR: 3320 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3321 case ISD::STEP_VECTOR: 3322 return lowerSTEP_VECTOR(Op, DAG); 3323 case ISD::VECTOR_REVERSE: 3324 return lowerVECTOR_REVERSE(Op, DAG); 3325 case ISD::VECTOR_SPLICE: 3326 return lowerVECTOR_SPLICE(Op, DAG); 3327 case ISD::BUILD_VECTOR: 3328 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3329 case ISD::SPLAT_VECTOR: 3330 if (Op.getValueType().getVectorElementType() == MVT::i1) 3331 return lowerVectorMaskSplat(Op, DAG); 3332 return SDValue(); 3333 case ISD::VECTOR_SHUFFLE: 3334 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3335 case ISD::CONCAT_VECTORS: { 3336 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3337 // better than going through the stack, as the default expansion does. 3338 SDLoc DL(Op); 3339 MVT VT = Op.getSimpleValueType(); 3340 unsigned NumOpElts = 3341 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3342 SDValue Vec = DAG.getUNDEF(VT); 3343 for (const auto &OpIdx : enumerate(Op->ops())) { 3344 SDValue SubVec = OpIdx.value(); 3345 // Don't insert undef subvectors. 3346 if (SubVec.isUndef()) 3347 continue; 3348 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3349 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3350 } 3351 return Vec; 3352 } 3353 case ISD::LOAD: 3354 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3355 return V; 3356 if (Op.getValueType().isFixedLengthVector()) 3357 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3358 return Op; 3359 case ISD::STORE: 3360 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3361 return V; 3362 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3363 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3364 return Op; 3365 case ISD::MLOAD: 3366 case ISD::VP_LOAD: 3367 return lowerMaskedLoad(Op, DAG); 3368 case ISD::MSTORE: 3369 case ISD::VP_STORE: 3370 return lowerMaskedStore(Op, DAG); 3371 case ISD::SETCC: 3372 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3373 case ISD::ADD: 3374 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3375 case ISD::SUB: 3376 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3377 case ISD::MUL: 3378 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3379 case ISD::MULHS: 3380 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3381 case ISD::MULHU: 3382 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3383 case ISD::AND: 3384 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3385 RISCVISD::AND_VL); 3386 case ISD::OR: 3387 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3388 RISCVISD::OR_VL); 3389 case ISD::XOR: 3390 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3391 RISCVISD::XOR_VL); 3392 case ISD::SDIV: 3393 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3394 case ISD::SREM: 3395 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3396 case ISD::UDIV: 3397 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3398 case ISD::UREM: 3399 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3400 case ISD::SHL: 3401 case ISD::SRA: 3402 case ISD::SRL: 3403 if (Op.getSimpleValueType().isFixedLengthVector()) 3404 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3405 // This can be called for an i32 shift amount that needs to be promoted. 3406 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3407 "Unexpected custom legalisation"); 3408 return SDValue(); 3409 case ISD::SADDSAT: 3410 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3411 case ISD::UADDSAT: 3412 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3413 case ISD::SSUBSAT: 3414 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3415 case ISD::USUBSAT: 3416 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3417 case ISD::FADD: 3418 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3419 case ISD::FSUB: 3420 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3421 case ISD::FMUL: 3422 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3423 case ISD::FDIV: 3424 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3425 case ISD::FNEG: 3426 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3427 case ISD::FABS: 3428 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3429 case ISD::FSQRT: 3430 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3431 case ISD::FMA: 3432 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3433 case ISD::SMIN: 3434 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3435 case ISD::SMAX: 3436 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3437 case ISD::UMIN: 3438 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3439 case ISD::UMAX: 3440 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3441 case ISD::FMINNUM: 3442 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3443 case ISD::FMAXNUM: 3444 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3445 case ISD::ABS: 3446 return lowerABS(Op, DAG); 3447 case ISD::CTLZ_ZERO_UNDEF: 3448 case ISD::CTTZ_ZERO_UNDEF: 3449 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3450 case ISD::VSELECT: 3451 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3452 case ISD::FCOPYSIGN: 3453 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3454 case ISD::MGATHER: 3455 case ISD::VP_GATHER: 3456 return lowerMaskedGather(Op, DAG); 3457 case ISD::MSCATTER: 3458 case ISD::VP_SCATTER: 3459 return lowerMaskedScatter(Op, DAG); 3460 case ISD::FLT_ROUNDS_: 3461 return lowerGET_ROUNDING(Op, DAG); 3462 case ISD::SET_ROUNDING: 3463 return lowerSET_ROUNDING(Op, DAG); 3464 case ISD::VP_SELECT: 3465 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3466 case ISD::VP_MERGE: 3467 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3468 case ISD::VP_ADD: 3469 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3470 case ISD::VP_SUB: 3471 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3472 case ISD::VP_MUL: 3473 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3474 case ISD::VP_SDIV: 3475 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3476 case ISD::VP_UDIV: 3477 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3478 case ISD::VP_SREM: 3479 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3480 case ISD::VP_UREM: 3481 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3482 case ISD::VP_AND: 3483 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3484 case ISD::VP_OR: 3485 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3486 case ISD::VP_XOR: 3487 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3488 case ISD::VP_ASHR: 3489 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3490 case ISD::VP_LSHR: 3491 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3492 case ISD::VP_SHL: 3493 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3494 case ISD::VP_FADD: 3495 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3496 case ISD::VP_FSUB: 3497 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3498 case ISD::VP_FMUL: 3499 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3500 case ISD::VP_FDIV: 3501 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3502 case ISD::VP_FNEG: 3503 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3504 case ISD::VP_FMA: 3505 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3506 case ISD::VP_SEXT: 3507 case ISD::VP_ZEXT: 3508 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3509 return lowerVPExtMaskOp(Op, DAG); 3510 return lowerVPOp(Op, DAG, 3511 Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL 3512 : RISCVISD::VZEXT_VL); 3513 case ISD::VP_TRUNC: 3514 return lowerVectorTruncLike(Op, DAG); 3515 case ISD::VP_FP_ROUND: 3516 return lowerVectorFPRoundLike(Op, DAG); 3517 case ISD::VP_FPTOSI: 3518 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3519 case ISD::VP_FPTOUI: 3520 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3521 case ISD::VP_SITOFP: 3522 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3523 case ISD::VP_UITOFP: 3524 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3525 case ISD::VP_SETCC: 3526 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3527 return lowerVPSetCCMaskOp(Op, DAG); 3528 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3529 } 3530 } 3531 3532 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3533 SelectionDAG &DAG, unsigned Flags) { 3534 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3535 } 3536 3537 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3538 SelectionDAG &DAG, unsigned Flags) { 3539 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3540 Flags); 3541 } 3542 3543 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3544 SelectionDAG &DAG, unsigned Flags) { 3545 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3546 N->getOffset(), Flags); 3547 } 3548 3549 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3550 SelectionDAG &DAG, unsigned Flags) { 3551 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3552 } 3553 3554 template <class NodeTy> 3555 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3556 bool IsLocal) const { 3557 SDLoc DL(N); 3558 EVT Ty = getPointerTy(DAG.getDataLayout()); 3559 3560 if (isPositionIndependent()) { 3561 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3562 if (IsLocal) 3563 // Use PC-relative addressing to access the symbol. This generates the 3564 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3565 // %pcrel_lo(auipc)). 3566 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3567 3568 // Use PC-relative addressing to access the GOT for this symbol, then load 3569 // the address from the GOT. This generates the pattern (PseudoLA sym), 3570 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3571 SDValue Load = 3572 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3573 MachineFunction &MF = DAG.getMachineFunction(); 3574 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3575 MachinePointerInfo::getGOT(MF), 3576 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3577 MachineMemOperand::MOInvariant, 3578 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3579 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3580 return Load; 3581 } 3582 3583 switch (getTargetMachine().getCodeModel()) { 3584 default: 3585 report_fatal_error("Unsupported code model for lowering"); 3586 case CodeModel::Small: { 3587 // Generate a sequence for accessing addresses within the first 2 GiB of 3588 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3589 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3590 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3591 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3592 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3593 } 3594 case CodeModel::Medium: { 3595 // Generate a sequence for accessing addresses within any 2GiB range within 3596 // the address space. This generates the pattern (PseudoLLA sym), which 3597 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3598 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3599 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3600 } 3601 } 3602 } 3603 3604 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3605 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3606 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3607 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3608 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3609 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3610 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3611 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3612 3613 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3614 SelectionDAG &DAG) const { 3615 SDLoc DL(Op); 3616 EVT Ty = Op.getValueType(); 3617 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3618 int64_t Offset = N->getOffset(); 3619 MVT XLenVT = Subtarget.getXLenVT(); 3620 3621 const GlobalValue *GV = N->getGlobal(); 3622 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3623 SDValue Addr = getAddr(N, DAG, IsLocal); 3624 3625 // In order to maximise the opportunity for common subexpression elimination, 3626 // emit a separate ADD node for the global address offset instead of folding 3627 // it in the global address node. Later peephole optimisations may choose to 3628 // fold it back in when profitable. 3629 if (Offset != 0) 3630 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3631 DAG.getConstant(Offset, DL, XLenVT)); 3632 return Addr; 3633 } 3634 3635 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3636 SelectionDAG &DAG) const { 3637 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3638 3639 return getAddr(N, DAG); 3640 } 3641 3642 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3643 SelectionDAG &DAG) const { 3644 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3645 3646 return getAddr(N, DAG); 3647 } 3648 3649 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3650 SelectionDAG &DAG) const { 3651 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3652 3653 return getAddr(N, DAG); 3654 } 3655 3656 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3657 SelectionDAG &DAG, 3658 bool UseGOT) const { 3659 SDLoc DL(N); 3660 EVT Ty = getPointerTy(DAG.getDataLayout()); 3661 const GlobalValue *GV = N->getGlobal(); 3662 MVT XLenVT = Subtarget.getXLenVT(); 3663 3664 if (UseGOT) { 3665 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3666 // load the address from the GOT and add the thread pointer. This generates 3667 // the pattern (PseudoLA_TLS_IE sym), which expands to 3668 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3669 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3670 SDValue Load = 3671 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3672 MachineFunction &MF = DAG.getMachineFunction(); 3673 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3674 MachinePointerInfo::getGOT(MF), 3675 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3676 MachineMemOperand::MOInvariant, 3677 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3678 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3679 3680 // Add the thread pointer. 3681 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3682 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3683 } 3684 3685 // Generate a sequence for accessing the address relative to the thread 3686 // pointer, with the appropriate adjustment for the thread pointer offset. 3687 // This generates the pattern 3688 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3689 SDValue AddrHi = 3690 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3691 SDValue AddrAdd = 3692 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3693 SDValue AddrLo = 3694 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3695 3696 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3697 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3698 SDValue MNAdd = SDValue( 3699 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3700 0); 3701 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3702 } 3703 3704 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3705 SelectionDAG &DAG) const { 3706 SDLoc DL(N); 3707 EVT Ty = getPointerTy(DAG.getDataLayout()); 3708 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3709 const GlobalValue *GV = N->getGlobal(); 3710 3711 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3712 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3713 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3714 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3715 SDValue Load = 3716 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3717 3718 // Prepare argument list to generate call. 3719 ArgListTy Args; 3720 ArgListEntry Entry; 3721 Entry.Node = Load; 3722 Entry.Ty = CallTy; 3723 Args.push_back(Entry); 3724 3725 // Setup call to __tls_get_addr. 3726 TargetLowering::CallLoweringInfo CLI(DAG); 3727 CLI.setDebugLoc(DL) 3728 .setChain(DAG.getEntryNode()) 3729 .setLibCallee(CallingConv::C, CallTy, 3730 DAG.getExternalSymbol("__tls_get_addr", Ty), 3731 std::move(Args)); 3732 3733 return LowerCallTo(CLI).first; 3734 } 3735 3736 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3737 SelectionDAG &DAG) const { 3738 SDLoc DL(Op); 3739 EVT Ty = Op.getValueType(); 3740 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3741 int64_t Offset = N->getOffset(); 3742 MVT XLenVT = Subtarget.getXLenVT(); 3743 3744 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3745 3746 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3747 CallingConv::GHC) 3748 report_fatal_error("In GHC calling convention TLS is not supported"); 3749 3750 SDValue Addr; 3751 switch (Model) { 3752 case TLSModel::LocalExec: 3753 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3754 break; 3755 case TLSModel::InitialExec: 3756 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3757 break; 3758 case TLSModel::LocalDynamic: 3759 case TLSModel::GeneralDynamic: 3760 Addr = getDynamicTLSAddr(N, DAG); 3761 break; 3762 } 3763 3764 // In order to maximise the opportunity for common subexpression elimination, 3765 // emit a separate ADD node for the global address offset instead of folding 3766 // it in the global address node. Later peephole optimisations may choose to 3767 // fold it back in when profitable. 3768 if (Offset != 0) 3769 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3770 DAG.getConstant(Offset, DL, XLenVT)); 3771 return Addr; 3772 } 3773 3774 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3775 SDValue CondV = Op.getOperand(0); 3776 SDValue TrueV = Op.getOperand(1); 3777 SDValue FalseV = Op.getOperand(2); 3778 SDLoc DL(Op); 3779 MVT VT = Op.getSimpleValueType(); 3780 MVT XLenVT = Subtarget.getXLenVT(); 3781 3782 // Lower vector SELECTs to VSELECTs by splatting the condition. 3783 if (VT.isVector()) { 3784 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3785 SDValue CondSplat = VT.isScalableVector() 3786 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3787 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3788 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3789 } 3790 3791 // If the result type is XLenVT and CondV is the output of a SETCC node 3792 // which also operated on XLenVT inputs, then merge the SETCC node into the 3793 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3794 // compare+branch instructions. i.e.: 3795 // (select (setcc lhs, rhs, cc), truev, falsev) 3796 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3797 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3798 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3799 SDValue LHS = CondV.getOperand(0); 3800 SDValue RHS = CondV.getOperand(1); 3801 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3802 ISD::CondCode CCVal = CC->get(); 3803 3804 // Special case for a select of 2 constants that have a diffence of 1. 3805 // Normally this is done by DAGCombine, but if the select is introduced by 3806 // type legalization or op legalization, we miss it. Restricting to SETLT 3807 // case for now because that is what signed saturating add/sub need. 3808 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3809 // but we would probably want to swap the true/false values if the condition 3810 // is SETGE/SETLE to avoid an XORI. 3811 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3812 CCVal == ISD::SETLT) { 3813 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3814 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3815 if (TrueVal - 1 == FalseVal) 3816 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3817 if (TrueVal + 1 == FalseVal) 3818 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3819 } 3820 3821 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3822 3823 SDValue TargetCC = DAG.getCondCode(CCVal); 3824 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3825 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3826 } 3827 3828 // Otherwise: 3829 // (select condv, truev, falsev) 3830 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3831 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3832 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3833 3834 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3835 3836 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3837 } 3838 3839 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3840 SDValue CondV = Op.getOperand(1); 3841 SDLoc DL(Op); 3842 MVT XLenVT = Subtarget.getXLenVT(); 3843 3844 if (CondV.getOpcode() == ISD::SETCC && 3845 CondV.getOperand(0).getValueType() == XLenVT) { 3846 SDValue LHS = CondV.getOperand(0); 3847 SDValue RHS = CondV.getOperand(1); 3848 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3849 3850 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3851 3852 SDValue TargetCC = DAG.getCondCode(CCVal); 3853 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3854 LHS, RHS, TargetCC, Op.getOperand(2)); 3855 } 3856 3857 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3858 CondV, DAG.getConstant(0, DL, XLenVT), 3859 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3860 } 3861 3862 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3863 MachineFunction &MF = DAG.getMachineFunction(); 3864 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3865 3866 SDLoc DL(Op); 3867 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3868 getPointerTy(MF.getDataLayout())); 3869 3870 // vastart just stores the address of the VarArgsFrameIndex slot into the 3871 // memory location argument. 3872 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3873 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3874 MachinePointerInfo(SV)); 3875 } 3876 3877 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3878 SelectionDAG &DAG) const { 3879 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3880 MachineFunction &MF = DAG.getMachineFunction(); 3881 MachineFrameInfo &MFI = MF.getFrameInfo(); 3882 MFI.setFrameAddressIsTaken(true); 3883 Register FrameReg = RI.getFrameRegister(MF); 3884 int XLenInBytes = Subtarget.getXLen() / 8; 3885 3886 EVT VT = Op.getValueType(); 3887 SDLoc DL(Op); 3888 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3889 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3890 while (Depth--) { 3891 int Offset = -(XLenInBytes * 2); 3892 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3893 DAG.getIntPtrConstant(Offset, DL)); 3894 FrameAddr = 3895 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3896 } 3897 return FrameAddr; 3898 } 3899 3900 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3901 SelectionDAG &DAG) const { 3902 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3903 MachineFunction &MF = DAG.getMachineFunction(); 3904 MachineFrameInfo &MFI = MF.getFrameInfo(); 3905 MFI.setReturnAddressIsTaken(true); 3906 MVT XLenVT = Subtarget.getXLenVT(); 3907 int XLenInBytes = Subtarget.getXLen() / 8; 3908 3909 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3910 return SDValue(); 3911 3912 EVT VT = Op.getValueType(); 3913 SDLoc DL(Op); 3914 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3915 if (Depth) { 3916 int Off = -XLenInBytes; 3917 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3918 SDValue Offset = DAG.getConstant(Off, DL, VT); 3919 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3920 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3921 MachinePointerInfo()); 3922 } 3923 3924 // Return the value of the return address register, marking it an implicit 3925 // live-in. 3926 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3927 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3928 } 3929 3930 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3931 SelectionDAG &DAG) const { 3932 SDLoc DL(Op); 3933 SDValue Lo = Op.getOperand(0); 3934 SDValue Hi = Op.getOperand(1); 3935 SDValue Shamt = Op.getOperand(2); 3936 EVT VT = Lo.getValueType(); 3937 3938 // if Shamt-XLEN < 0: // Shamt < XLEN 3939 // Lo = Lo << Shamt 3940 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3941 // else: 3942 // Lo = 0 3943 // Hi = Lo << (Shamt-XLEN) 3944 3945 SDValue Zero = DAG.getConstant(0, DL, VT); 3946 SDValue One = DAG.getConstant(1, DL, VT); 3947 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3948 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3949 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3950 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3951 3952 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3953 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3954 SDValue ShiftRightLo = 3955 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3956 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3957 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3958 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3959 3960 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3961 3962 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3963 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3964 3965 SDValue Parts[2] = {Lo, Hi}; 3966 return DAG.getMergeValues(Parts, DL); 3967 } 3968 3969 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3970 bool IsSRA) const { 3971 SDLoc DL(Op); 3972 SDValue Lo = Op.getOperand(0); 3973 SDValue Hi = Op.getOperand(1); 3974 SDValue Shamt = Op.getOperand(2); 3975 EVT VT = Lo.getValueType(); 3976 3977 // SRA expansion: 3978 // if Shamt-XLEN < 0: // Shamt < XLEN 3979 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3980 // Hi = Hi >>s Shamt 3981 // else: 3982 // Lo = Hi >>s (Shamt-XLEN); 3983 // Hi = Hi >>s (XLEN-1) 3984 // 3985 // SRL expansion: 3986 // if Shamt-XLEN < 0: // Shamt < XLEN 3987 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3988 // Hi = Hi >>u Shamt 3989 // else: 3990 // Lo = Hi >>u (Shamt-XLEN); 3991 // Hi = 0; 3992 3993 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3994 3995 SDValue Zero = DAG.getConstant(0, DL, VT); 3996 SDValue One = DAG.getConstant(1, DL, VT); 3997 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3998 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3999 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4000 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4001 4002 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4003 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4004 SDValue ShiftLeftHi = 4005 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4006 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4007 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4008 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4009 SDValue HiFalse = 4010 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4011 4012 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4013 4014 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4015 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4016 4017 SDValue Parts[2] = {Lo, Hi}; 4018 return DAG.getMergeValues(Parts, DL); 4019 } 4020 4021 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4022 // legal equivalently-sized i8 type, so we can use that as a go-between. 4023 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4024 SelectionDAG &DAG) const { 4025 SDLoc DL(Op); 4026 MVT VT = Op.getSimpleValueType(); 4027 SDValue SplatVal = Op.getOperand(0); 4028 // All-zeros or all-ones splats are handled specially. 4029 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4030 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4031 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4032 } 4033 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4034 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4035 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4036 } 4037 MVT XLenVT = Subtarget.getXLenVT(); 4038 assert(SplatVal.getValueType() == XLenVT && 4039 "Unexpected type for i1 splat value"); 4040 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4041 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4042 DAG.getConstant(1, DL, XLenVT)); 4043 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4044 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4045 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4046 } 4047 4048 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4049 // illegal (currently only vXi64 RV32). 4050 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4051 // them to VMV_V_X_VL. 4052 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4053 SelectionDAG &DAG) const { 4054 SDLoc DL(Op); 4055 MVT VecVT = Op.getSimpleValueType(); 4056 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4057 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4058 4059 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4060 SDValue Lo = Op.getOperand(0); 4061 SDValue Hi = Op.getOperand(1); 4062 4063 if (VecVT.isFixedLengthVector()) { 4064 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4065 SDLoc DL(Op); 4066 SDValue Mask, VL; 4067 std::tie(Mask, VL) = 4068 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4069 4070 SDValue Res = 4071 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4072 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4073 } 4074 4075 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4076 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4077 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4078 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4079 // node in order to try and match RVV vector/scalar instructions. 4080 if ((LoC >> 31) == HiC) 4081 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4082 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4083 } 4084 4085 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4086 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4087 isa<ConstantSDNode>(Hi.getOperand(1)) && 4088 Hi.getConstantOperandVal(1) == 31) 4089 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4090 DAG.getRegister(RISCV::X0, MVT::i32)); 4091 4092 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4093 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4094 DAG.getUNDEF(VecVT), Lo, Hi, 4095 DAG.getRegister(RISCV::X0, MVT::i32)); 4096 } 4097 4098 // Custom-lower extensions from mask vectors by using a vselect either with 1 4099 // for zero/any-extension or -1 for sign-extension: 4100 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4101 // Note that any-extension is lowered identically to zero-extension. 4102 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4103 int64_t ExtTrueVal) const { 4104 SDLoc DL(Op); 4105 MVT VecVT = Op.getSimpleValueType(); 4106 SDValue Src = Op.getOperand(0); 4107 // Only custom-lower extensions from mask types 4108 assert(Src.getValueType().isVector() && 4109 Src.getValueType().getVectorElementType() == MVT::i1); 4110 4111 if (VecVT.isScalableVector()) { 4112 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4113 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4114 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4115 } 4116 4117 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4118 MVT I1ContainerVT = 4119 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4120 4121 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4122 4123 SDValue Mask, VL; 4124 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4125 4126 MVT XLenVT = Subtarget.getXLenVT(); 4127 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4128 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4129 4130 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4131 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4132 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4133 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4134 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4135 SplatTrueVal, SplatZero, VL); 4136 4137 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4138 } 4139 4140 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4141 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4142 MVT ExtVT = Op.getSimpleValueType(); 4143 // Only custom-lower extensions from fixed-length vector types. 4144 if (!ExtVT.isFixedLengthVector()) 4145 return Op; 4146 MVT VT = Op.getOperand(0).getSimpleValueType(); 4147 // Grab the canonical container type for the extended type. Infer the smaller 4148 // type from that to ensure the same number of vector elements, as we know 4149 // the LMUL will be sufficient to hold the smaller type. 4150 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4151 // Get the extended container type manually to ensure the same number of 4152 // vector elements between source and dest. 4153 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4154 ContainerExtVT.getVectorElementCount()); 4155 4156 SDValue Op1 = 4157 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4158 4159 SDLoc DL(Op); 4160 SDValue Mask, VL; 4161 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4162 4163 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4164 4165 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4166 } 4167 4168 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4169 // setcc operation: 4170 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4171 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4172 SelectionDAG &DAG) const { 4173 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4174 SDLoc DL(Op); 4175 EVT MaskVT = Op.getValueType(); 4176 // Only expect to custom-lower truncations to mask types 4177 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4178 "Unexpected type for vector mask lowering"); 4179 SDValue Src = Op.getOperand(0); 4180 MVT VecVT = Src.getSimpleValueType(); 4181 SDValue Mask, VL; 4182 if (IsVPTrunc) { 4183 Mask = Op.getOperand(1); 4184 VL = Op.getOperand(2); 4185 } 4186 // If this is a fixed vector, we need to convert it to a scalable vector. 4187 MVT ContainerVT = VecVT; 4188 4189 if (VecVT.isFixedLengthVector()) { 4190 ContainerVT = getContainerForFixedLengthVector(VecVT); 4191 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4192 if (IsVPTrunc) { 4193 MVT MaskContainerVT = 4194 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4195 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4196 } 4197 } 4198 4199 if (!IsVPTrunc) { 4200 std::tie(Mask, VL) = 4201 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4202 } 4203 4204 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4205 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4206 4207 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4208 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4209 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4210 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4211 4212 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4213 SDValue Trunc = 4214 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4215 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4216 DAG.getCondCode(ISD::SETNE), Mask, VL); 4217 if (MaskVT.isFixedLengthVector()) 4218 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4219 return Trunc; 4220 } 4221 4222 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4223 SelectionDAG &DAG) const { 4224 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4225 SDLoc DL(Op); 4226 4227 MVT VT = Op.getSimpleValueType(); 4228 // Only custom-lower vector truncates 4229 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4230 4231 // Truncates to mask types are handled differently 4232 if (VT.getVectorElementType() == MVT::i1) 4233 return lowerVectorMaskTruncLike(Op, DAG); 4234 4235 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4236 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4237 // truncate by one power of two at a time. 4238 MVT DstEltVT = VT.getVectorElementType(); 4239 4240 SDValue Src = Op.getOperand(0); 4241 MVT SrcVT = Src.getSimpleValueType(); 4242 MVT SrcEltVT = SrcVT.getVectorElementType(); 4243 4244 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4245 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4246 "Unexpected vector truncate lowering"); 4247 4248 MVT ContainerVT = SrcVT; 4249 SDValue Mask, VL; 4250 if (IsVPTrunc) { 4251 Mask = Op.getOperand(1); 4252 VL = Op.getOperand(2); 4253 } 4254 if (SrcVT.isFixedLengthVector()) { 4255 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4256 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4257 if (IsVPTrunc) { 4258 MVT MaskVT = getMaskTypeFor(ContainerVT); 4259 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4260 } 4261 } 4262 4263 SDValue Result = Src; 4264 if (!IsVPTrunc) { 4265 std::tie(Mask, VL) = 4266 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4267 } 4268 4269 LLVMContext &Context = *DAG.getContext(); 4270 const ElementCount Count = ContainerVT.getVectorElementCount(); 4271 do { 4272 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4273 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4274 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4275 Mask, VL); 4276 } while (SrcEltVT != DstEltVT); 4277 4278 if (SrcVT.isFixedLengthVector()) 4279 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4280 4281 return Result; 4282 } 4283 4284 SDValue RISCVTargetLowering::lowerVectorFPRoundLike(SDValue Op, 4285 SelectionDAG &DAG) const { 4286 bool IsVPFPTrunc = Op.getOpcode() == ISD::VP_FP_ROUND; 4287 // RVV can only do truncate fp to types half the size as the source. We 4288 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4289 // conversion instruction. 4290 SDLoc DL(Op); 4291 MVT VT = Op.getSimpleValueType(); 4292 4293 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4294 4295 SDValue Src = Op.getOperand(0); 4296 MVT SrcVT = Src.getSimpleValueType(); 4297 4298 bool IsDirectConv = VT.getVectorElementType() != MVT::f16 || 4299 SrcVT.getVectorElementType() != MVT::f64; 4300 4301 // For FP_ROUND of scalable vectors, leave it to the pattern. 4302 if (!VT.isFixedLengthVector() && !IsVPFPTrunc && IsDirectConv) 4303 return Op; 4304 4305 // Prepare any fixed-length vector operands. 4306 MVT ContainerVT = VT; 4307 SDValue Mask, VL; 4308 if (IsVPFPTrunc) { 4309 Mask = Op.getOperand(1); 4310 VL = Op.getOperand(2); 4311 } 4312 if (VT.isFixedLengthVector()) { 4313 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4314 ContainerVT = 4315 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4316 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4317 if (IsVPFPTrunc) { 4318 MVT MaskVT = getMaskTypeFor(ContainerVT); 4319 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4320 } 4321 } 4322 4323 if (!IsVPFPTrunc) 4324 std::tie(Mask, VL) = 4325 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4326 4327 if (IsDirectConv) { 4328 Src = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, Src, Mask, VL); 4329 if (VT.isFixedLengthVector()) 4330 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4331 return Src; 4332 } 4333 4334 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4335 SDValue IntermediateRound = 4336 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 4337 SDValue Round = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, 4338 IntermediateRound, Mask, VL); 4339 if (VT.isFixedLengthVector()) 4340 return convertFromScalableVector(VT, Round, DAG, Subtarget); 4341 return Round; 4342 } 4343 4344 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4345 // first position of a vector, and that vector is slid up to the insert index. 4346 // By limiting the active vector length to index+1 and merging with the 4347 // original vector (with an undisturbed tail policy for elements >= VL), we 4348 // achieve the desired result of leaving all elements untouched except the one 4349 // at VL-1, which is replaced with the desired value. 4350 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4351 SelectionDAG &DAG) const { 4352 SDLoc DL(Op); 4353 MVT VecVT = Op.getSimpleValueType(); 4354 SDValue Vec = Op.getOperand(0); 4355 SDValue Val = Op.getOperand(1); 4356 SDValue Idx = Op.getOperand(2); 4357 4358 if (VecVT.getVectorElementType() == MVT::i1) { 4359 // FIXME: For now we just promote to an i8 vector and insert into that, 4360 // but this is probably not optimal. 4361 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4362 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4363 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4364 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4365 } 4366 4367 MVT ContainerVT = VecVT; 4368 // If the operand is a fixed-length vector, convert to a scalable one. 4369 if (VecVT.isFixedLengthVector()) { 4370 ContainerVT = getContainerForFixedLengthVector(VecVT); 4371 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4372 } 4373 4374 MVT XLenVT = Subtarget.getXLenVT(); 4375 4376 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4377 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4378 // Even i64-element vectors on RV32 can be lowered without scalar 4379 // legalization if the most-significant 32 bits of the value are not affected 4380 // by the sign-extension of the lower 32 bits. 4381 // TODO: We could also catch sign extensions of a 32-bit value. 4382 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4383 const auto *CVal = cast<ConstantSDNode>(Val); 4384 if (isInt<32>(CVal->getSExtValue())) { 4385 IsLegalInsert = true; 4386 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4387 } 4388 } 4389 4390 SDValue Mask, VL; 4391 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4392 4393 SDValue ValInVec; 4394 4395 if (IsLegalInsert) { 4396 unsigned Opc = 4397 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4398 if (isNullConstant(Idx)) { 4399 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4400 if (!VecVT.isFixedLengthVector()) 4401 return Vec; 4402 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4403 } 4404 ValInVec = 4405 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4406 } else { 4407 // On RV32, i64-element vectors must be specially handled to place the 4408 // value at element 0, by using two vslide1up instructions in sequence on 4409 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4410 // this. 4411 SDValue One = DAG.getConstant(1, DL, XLenVT); 4412 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4413 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4414 MVT I32ContainerVT = 4415 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4416 SDValue I32Mask = 4417 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4418 // Limit the active VL to two. 4419 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4420 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4421 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4422 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4423 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4424 // First slide in the hi value, then the lo in underneath it. 4425 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4426 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4427 I32Mask, InsertI64VL); 4428 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4429 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4430 I32Mask, InsertI64VL); 4431 // Bitcast back to the right container type. 4432 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4433 } 4434 4435 // Now that the value is in a vector, slide it into position. 4436 SDValue InsertVL = 4437 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4438 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4439 ValInVec, Idx, Mask, InsertVL); 4440 if (!VecVT.isFixedLengthVector()) 4441 return Slideup; 4442 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4443 } 4444 4445 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4446 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4447 // types this is done using VMV_X_S to allow us to glean information about the 4448 // sign bits of the result. 4449 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4450 SelectionDAG &DAG) const { 4451 SDLoc DL(Op); 4452 SDValue Idx = Op.getOperand(1); 4453 SDValue Vec = Op.getOperand(0); 4454 EVT EltVT = Op.getValueType(); 4455 MVT VecVT = Vec.getSimpleValueType(); 4456 MVT XLenVT = Subtarget.getXLenVT(); 4457 4458 if (VecVT.getVectorElementType() == MVT::i1) { 4459 if (VecVT.isFixedLengthVector()) { 4460 unsigned NumElts = VecVT.getVectorNumElements(); 4461 if (NumElts >= 8) { 4462 MVT WideEltVT; 4463 unsigned WidenVecLen; 4464 SDValue ExtractElementIdx; 4465 SDValue ExtractBitIdx; 4466 unsigned MaxEEW = Subtarget.getELEN(); 4467 MVT LargestEltVT = MVT::getIntegerVT( 4468 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4469 if (NumElts <= LargestEltVT.getSizeInBits()) { 4470 assert(isPowerOf2_32(NumElts) && 4471 "the number of elements should be power of 2"); 4472 WideEltVT = MVT::getIntegerVT(NumElts); 4473 WidenVecLen = 1; 4474 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4475 ExtractBitIdx = Idx; 4476 } else { 4477 WideEltVT = LargestEltVT; 4478 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4479 // extract element index = index / element width 4480 ExtractElementIdx = DAG.getNode( 4481 ISD::SRL, DL, XLenVT, Idx, 4482 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4483 // mask bit index = index % element width 4484 ExtractBitIdx = DAG.getNode( 4485 ISD::AND, DL, XLenVT, Idx, 4486 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4487 } 4488 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4489 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4490 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4491 Vec, ExtractElementIdx); 4492 // Extract the bit from GPR. 4493 SDValue ShiftRight = 4494 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4495 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4496 DAG.getConstant(1, DL, XLenVT)); 4497 } 4498 } 4499 // Otherwise, promote to an i8 vector and extract from that. 4500 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4501 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4502 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4503 } 4504 4505 // If this is a fixed vector, we need to convert it to a scalable vector. 4506 MVT ContainerVT = VecVT; 4507 if (VecVT.isFixedLengthVector()) { 4508 ContainerVT = getContainerForFixedLengthVector(VecVT); 4509 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4510 } 4511 4512 // If the index is 0, the vector is already in the right position. 4513 if (!isNullConstant(Idx)) { 4514 // Use a VL of 1 to avoid processing more elements than we need. 4515 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4516 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4517 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4518 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4519 } 4520 4521 if (!EltVT.isInteger()) { 4522 // Floating-point extracts are handled in TableGen. 4523 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4524 DAG.getConstant(0, DL, XLenVT)); 4525 } 4526 4527 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4528 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4529 } 4530 4531 // Some RVV intrinsics may claim that they want an integer operand to be 4532 // promoted or expanded. 4533 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4534 const RISCVSubtarget &Subtarget) { 4535 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4536 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4537 "Unexpected opcode"); 4538 4539 if (!Subtarget.hasVInstructions()) 4540 return SDValue(); 4541 4542 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4543 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4544 SDLoc DL(Op); 4545 4546 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4547 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4548 if (!II || !II->hasScalarOperand()) 4549 return SDValue(); 4550 4551 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4552 assert(SplatOp < Op.getNumOperands()); 4553 4554 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4555 SDValue &ScalarOp = Operands[SplatOp]; 4556 MVT OpVT = ScalarOp.getSimpleValueType(); 4557 MVT XLenVT = Subtarget.getXLenVT(); 4558 4559 // If this isn't a scalar, or its type is XLenVT we're done. 4560 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4561 return SDValue(); 4562 4563 // Simplest case is that the operand needs to be promoted to XLenVT. 4564 if (OpVT.bitsLT(XLenVT)) { 4565 // If the operand is a constant, sign extend to increase our chances 4566 // of being able to use a .vi instruction. ANY_EXTEND would become a 4567 // a zero extend and the simm5 check in isel would fail. 4568 // FIXME: Should we ignore the upper bits in isel instead? 4569 unsigned ExtOpc = 4570 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4571 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4572 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4573 } 4574 4575 // Use the previous operand to get the vXi64 VT. The result might be a mask 4576 // VT for compares. Using the previous operand assumes that the previous 4577 // operand will never have a smaller element size than a scalar operand and 4578 // that a widening operation never uses SEW=64. 4579 // NOTE: If this fails the below assert, we can probably just find the 4580 // element count from any operand or result and use it to construct the VT. 4581 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4582 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4583 4584 // The more complex case is when the scalar is larger than XLenVT. 4585 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4586 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4587 4588 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4589 // instruction to sign-extend since SEW>XLEN. 4590 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4591 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4592 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4593 } 4594 4595 switch (IntNo) { 4596 case Intrinsic::riscv_vslide1up: 4597 case Intrinsic::riscv_vslide1down: 4598 case Intrinsic::riscv_vslide1up_mask: 4599 case Intrinsic::riscv_vslide1down_mask: { 4600 // We need to special case these when the scalar is larger than XLen. 4601 unsigned NumOps = Op.getNumOperands(); 4602 bool IsMasked = NumOps == 7; 4603 4604 // Convert the vector source to the equivalent nxvXi32 vector. 4605 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4606 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4607 4608 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4609 DAG.getConstant(0, DL, XLenVT)); 4610 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4611 DAG.getConstant(1, DL, XLenVT)); 4612 4613 // Double the VL since we halved SEW. 4614 SDValue AVL = getVLOperand(Op); 4615 SDValue I32VL; 4616 4617 // Optimize for constant AVL 4618 if (isa<ConstantSDNode>(AVL)) { 4619 unsigned EltSize = VT.getScalarSizeInBits(); 4620 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4621 4622 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4623 unsigned MaxVLMAX = 4624 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4625 4626 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4627 unsigned MinVLMAX = 4628 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4629 4630 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4631 if (AVLInt <= MinVLMAX) { 4632 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4633 } else if (AVLInt >= 2 * MaxVLMAX) { 4634 // Just set vl to VLMAX in this situation 4635 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4636 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4637 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4638 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4639 SDValue SETVLMAX = DAG.getTargetConstant( 4640 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4641 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4642 LMUL); 4643 } else { 4644 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4645 // is related to the hardware implementation. 4646 // So let the following code handle 4647 } 4648 } 4649 if (!I32VL) { 4650 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4651 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4652 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4653 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4654 SDValue SETVL = 4655 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4656 // Using vsetvli instruction to get actually used length which related to 4657 // the hardware implementation 4658 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4659 SEW, LMUL); 4660 I32VL = 4661 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4662 } 4663 4664 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4665 4666 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4667 // instructions. 4668 SDValue Passthru; 4669 if (IsMasked) 4670 Passthru = DAG.getUNDEF(I32VT); 4671 else 4672 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4673 4674 if (IntNo == Intrinsic::riscv_vslide1up || 4675 IntNo == Intrinsic::riscv_vslide1up_mask) { 4676 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4677 ScalarHi, I32Mask, I32VL); 4678 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4679 ScalarLo, I32Mask, I32VL); 4680 } else { 4681 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4682 ScalarLo, I32Mask, I32VL); 4683 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4684 ScalarHi, I32Mask, I32VL); 4685 } 4686 4687 // Convert back to nxvXi64. 4688 Vec = DAG.getBitcast(VT, Vec); 4689 4690 if (!IsMasked) 4691 return Vec; 4692 // Apply mask after the operation. 4693 SDValue Mask = Operands[NumOps - 3]; 4694 SDValue MaskedOff = Operands[1]; 4695 // Assume Policy operand is the last operand. 4696 uint64_t Policy = 4697 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4698 // We don't need to select maskedoff if it's undef. 4699 if (MaskedOff.isUndef()) 4700 return Vec; 4701 // TAMU 4702 if (Policy == RISCVII::TAIL_AGNOSTIC) 4703 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4704 AVL); 4705 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4706 // It's fine because vmerge does not care mask policy. 4707 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4708 AVL); 4709 } 4710 } 4711 4712 // We need to convert the scalar to a splat vector. 4713 SDValue VL = getVLOperand(Op); 4714 assert(VL.getValueType() == XLenVT); 4715 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4716 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4717 } 4718 4719 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4720 SelectionDAG &DAG) const { 4721 unsigned IntNo = Op.getConstantOperandVal(0); 4722 SDLoc DL(Op); 4723 MVT XLenVT = Subtarget.getXLenVT(); 4724 4725 switch (IntNo) { 4726 default: 4727 break; // Don't custom lower most intrinsics. 4728 case Intrinsic::thread_pointer: { 4729 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4730 return DAG.getRegister(RISCV::X4, PtrVT); 4731 } 4732 case Intrinsic::riscv_orc_b: 4733 case Intrinsic::riscv_brev8: { 4734 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4735 unsigned Opc = 4736 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4737 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4738 DAG.getConstant(7, DL, XLenVT)); 4739 } 4740 case Intrinsic::riscv_grev: 4741 case Intrinsic::riscv_gorc: { 4742 unsigned Opc = 4743 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4744 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4745 } 4746 case Intrinsic::riscv_zip: 4747 case Intrinsic::riscv_unzip: { 4748 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4749 // For i32 the immediate is 15. For i64 the immediate is 31. 4750 unsigned Opc = 4751 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4752 unsigned BitWidth = Op.getValueSizeInBits(); 4753 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4754 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4755 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4756 } 4757 case Intrinsic::riscv_shfl: 4758 case Intrinsic::riscv_unshfl: { 4759 unsigned Opc = 4760 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4761 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4762 } 4763 case Intrinsic::riscv_bcompress: 4764 case Intrinsic::riscv_bdecompress: { 4765 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4766 : RISCVISD::BDECOMPRESS; 4767 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4768 } 4769 case Intrinsic::riscv_bfp: 4770 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4771 Op.getOperand(2)); 4772 case Intrinsic::riscv_fsl: 4773 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4774 Op.getOperand(2), Op.getOperand(3)); 4775 case Intrinsic::riscv_fsr: 4776 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4777 Op.getOperand(2), Op.getOperand(3)); 4778 case Intrinsic::riscv_vmv_x_s: 4779 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4780 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4781 Op.getOperand(1)); 4782 case Intrinsic::riscv_vmv_v_x: 4783 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4784 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4785 Subtarget); 4786 case Intrinsic::riscv_vfmv_v_f: 4787 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4788 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4789 case Intrinsic::riscv_vmv_s_x: { 4790 SDValue Scalar = Op.getOperand(2); 4791 4792 if (Scalar.getValueType().bitsLE(XLenVT)) { 4793 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4794 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4795 Op.getOperand(1), Scalar, Op.getOperand(3)); 4796 } 4797 4798 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4799 4800 // This is an i64 value that lives in two scalar registers. We have to 4801 // insert this in a convoluted way. First we build vXi64 splat containing 4802 // the two values that we assemble using some bit math. Next we'll use 4803 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4804 // to merge element 0 from our splat into the source vector. 4805 // FIXME: This is probably not the best way to do this, but it is 4806 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4807 // point. 4808 // sw lo, (a0) 4809 // sw hi, 4(a0) 4810 // vlse vX, (a0) 4811 // 4812 // vid.v vVid 4813 // vmseq.vx mMask, vVid, 0 4814 // vmerge.vvm vDest, vSrc, vVal, mMask 4815 MVT VT = Op.getSimpleValueType(); 4816 SDValue Vec = Op.getOperand(1); 4817 SDValue VL = getVLOperand(Op); 4818 4819 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4820 if (Op.getOperand(1).isUndef()) 4821 return SplattedVal; 4822 SDValue SplattedIdx = 4823 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4824 DAG.getConstant(0, DL, MVT::i32), VL); 4825 4826 MVT MaskVT = getMaskTypeFor(VT); 4827 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4828 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4829 SDValue SelectCond = 4830 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4831 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4832 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4833 Vec, VL); 4834 } 4835 } 4836 4837 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4838 } 4839 4840 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4841 SelectionDAG &DAG) const { 4842 unsigned IntNo = Op.getConstantOperandVal(1); 4843 switch (IntNo) { 4844 default: 4845 break; 4846 case Intrinsic::riscv_masked_strided_load: { 4847 SDLoc DL(Op); 4848 MVT XLenVT = Subtarget.getXLenVT(); 4849 4850 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4851 // the selection of the masked intrinsics doesn't do this for us. 4852 SDValue Mask = Op.getOperand(5); 4853 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4854 4855 MVT VT = Op->getSimpleValueType(0); 4856 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4857 4858 SDValue PassThru = Op.getOperand(2); 4859 if (!IsUnmasked) { 4860 MVT MaskVT = getMaskTypeFor(ContainerVT); 4861 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4862 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4863 } 4864 4865 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4866 4867 SDValue IntID = DAG.getTargetConstant( 4868 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4869 XLenVT); 4870 4871 auto *Load = cast<MemIntrinsicSDNode>(Op); 4872 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4873 if (IsUnmasked) 4874 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4875 else 4876 Ops.push_back(PassThru); 4877 Ops.push_back(Op.getOperand(3)); // Ptr 4878 Ops.push_back(Op.getOperand(4)); // Stride 4879 if (!IsUnmasked) 4880 Ops.push_back(Mask); 4881 Ops.push_back(VL); 4882 if (!IsUnmasked) { 4883 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4884 Ops.push_back(Policy); 4885 } 4886 4887 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4888 SDValue Result = 4889 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4890 Load->getMemoryVT(), Load->getMemOperand()); 4891 SDValue Chain = Result.getValue(1); 4892 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4893 return DAG.getMergeValues({Result, Chain}, DL); 4894 } 4895 case Intrinsic::riscv_seg2_load: 4896 case Intrinsic::riscv_seg3_load: 4897 case Intrinsic::riscv_seg4_load: 4898 case Intrinsic::riscv_seg5_load: 4899 case Intrinsic::riscv_seg6_load: 4900 case Intrinsic::riscv_seg7_load: 4901 case Intrinsic::riscv_seg8_load: { 4902 SDLoc DL(Op); 4903 static const Intrinsic::ID VlsegInts[7] = { 4904 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4905 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4906 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4907 Intrinsic::riscv_vlseg8}; 4908 unsigned NF = Op->getNumValues() - 1; 4909 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4910 MVT XLenVT = Subtarget.getXLenVT(); 4911 MVT VT = Op->getSimpleValueType(0); 4912 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4913 4914 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4915 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4916 auto *Load = cast<MemIntrinsicSDNode>(Op); 4917 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4918 ContainerVTs.push_back(MVT::Other); 4919 SDVTList VTs = DAG.getVTList(ContainerVTs); 4920 SDValue Result = 4921 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4922 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4923 Load->getMemoryVT(), Load->getMemOperand()); 4924 SmallVector<SDValue, 9> Results; 4925 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4926 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4927 DAG, Subtarget)); 4928 Results.push_back(Result.getValue(NF)); 4929 return DAG.getMergeValues(Results, DL); 4930 } 4931 } 4932 4933 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4934 } 4935 4936 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4937 SelectionDAG &DAG) const { 4938 unsigned IntNo = Op.getConstantOperandVal(1); 4939 switch (IntNo) { 4940 default: 4941 break; 4942 case Intrinsic::riscv_masked_strided_store: { 4943 SDLoc DL(Op); 4944 MVT XLenVT = Subtarget.getXLenVT(); 4945 4946 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4947 // the selection of the masked intrinsics doesn't do this for us. 4948 SDValue Mask = Op.getOperand(5); 4949 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4950 4951 SDValue Val = Op.getOperand(2); 4952 MVT VT = Val.getSimpleValueType(); 4953 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4954 4955 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4956 if (!IsUnmasked) { 4957 MVT MaskVT = getMaskTypeFor(ContainerVT); 4958 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4959 } 4960 4961 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4962 4963 SDValue IntID = DAG.getTargetConstant( 4964 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4965 XLenVT); 4966 4967 auto *Store = cast<MemIntrinsicSDNode>(Op); 4968 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4969 Ops.push_back(Val); 4970 Ops.push_back(Op.getOperand(3)); // Ptr 4971 Ops.push_back(Op.getOperand(4)); // Stride 4972 if (!IsUnmasked) 4973 Ops.push_back(Mask); 4974 Ops.push_back(VL); 4975 4976 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4977 Ops, Store->getMemoryVT(), 4978 Store->getMemOperand()); 4979 } 4980 } 4981 4982 return SDValue(); 4983 } 4984 4985 static MVT getLMUL1VT(MVT VT) { 4986 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4987 "Unexpected vector MVT"); 4988 return MVT::getScalableVectorVT( 4989 VT.getVectorElementType(), 4990 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4991 } 4992 4993 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4994 switch (ISDOpcode) { 4995 default: 4996 llvm_unreachable("Unhandled reduction"); 4997 case ISD::VECREDUCE_ADD: 4998 return RISCVISD::VECREDUCE_ADD_VL; 4999 case ISD::VECREDUCE_UMAX: 5000 return RISCVISD::VECREDUCE_UMAX_VL; 5001 case ISD::VECREDUCE_SMAX: 5002 return RISCVISD::VECREDUCE_SMAX_VL; 5003 case ISD::VECREDUCE_UMIN: 5004 return RISCVISD::VECREDUCE_UMIN_VL; 5005 case ISD::VECREDUCE_SMIN: 5006 return RISCVISD::VECREDUCE_SMIN_VL; 5007 case ISD::VECREDUCE_AND: 5008 return RISCVISD::VECREDUCE_AND_VL; 5009 case ISD::VECREDUCE_OR: 5010 return RISCVISD::VECREDUCE_OR_VL; 5011 case ISD::VECREDUCE_XOR: 5012 return RISCVISD::VECREDUCE_XOR_VL; 5013 } 5014 } 5015 5016 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5017 SelectionDAG &DAG, 5018 bool IsVP) const { 5019 SDLoc DL(Op); 5020 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5021 MVT VecVT = Vec.getSimpleValueType(); 5022 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5023 Op.getOpcode() == ISD::VECREDUCE_OR || 5024 Op.getOpcode() == ISD::VECREDUCE_XOR || 5025 Op.getOpcode() == ISD::VP_REDUCE_AND || 5026 Op.getOpcode() == ISD::VP_REDUCE_OR || 5027 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5028 "Unexpected reduction lowering"); 5029 5030 MVT XLenVT = Subtarget.getXLenVT(); 5031 assert(Op.getValueType() == XLenVT && 5032 "Expected reduction output to be legalized to XLenVT"); 5033 5034 MVT ContainerVT = VecVT; 5035 if (VecVT.isFixedLengthVector()) { 5036 ContainerVT = getContainerForFixedLengthVector(VecVT); 5037 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5038 } 5039 5040 SDValue Mask, VL; 5041 if (IsVP) { 5042 Mask = Op.getOperand(2); 5043 VL = Op.getOperand(3); 5044 } else { 5045 std::tie(Mask, VL) = 5046 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5047 } 5048 5049 unsigned BaseOpc; 5050 ISD::CondCode CC; 5051 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5052 5053 switch (Op.getOpcode()) { 5054 default: 5055 llvm_unreachable("Unhandled reduction"); 5056 case ISD::VECREDUCE_AND: 5057 case ISD::VP_REDUCE_AND: { 5058 // vcpop ~x == 0 5059 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5060 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5061 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5062 CC = ISD::SETEQ; 5063 BaseOpc = ISD::AND; 5064 break; 5065 } 5066 case ISD::VECREDUCE_OR: 5067 case ISD::VP_REDUCE_OR: 5068 // vcpop x != 0 5069 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5070 CC = ISD::SETNE; 5071 BaseOpc = ISD::OR; 5072 break; 5073 case ISD::VECREDUCE_XOR: 5074 case ISD::VP_REDUCE_XOR: { 5075 // ((vcpop x) & 1) != 0 5076 SDValue One = DAG.getConstant(1, DL, XLenVT); 5077 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5078 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5079 CC = ISD::SETNE; 5080 BaseOpc = ISD::XOR; 5081 break; 5082 } 5083 } 5084 5085 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5086 5087 if (!IsVP) 5088 return SetCC; 5089 5090 // Now include the start value in the operation. 5091 // Note that we must return the start value when no elements are operated 5092 // upon. The vcpop instructions we've emitted in each case above will return 5093 // 0 for an inactive vector, and so we've already received the neutral value: 5094 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5095 // can simply include the start value. 5096 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5097 } 5098 5099 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5100 SelectionDAG &DAG) const { 5101 SDLoc DL(Op); 5102 SDValue Vec = Op.getOperand(0); 5103 EVT VecEVT = Vec.getValueType(); 5104 5105 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5106 5107 // Due to ordering in legalize types we may have a vector type that needs to 5108 // be split. Do that manually so we can get down to a legal type. 5109 while (getTypeAction(*DAG.getContext(), VecEVT) == 5110 TargetLowering::TypeSplitVector) { 5111 SDValue Lo, Hi; 5112 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5113 VecEVT = Lo.getValueType(); 5114 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5115 } 5116 5117 // TODO: The type may need to be widened rather than split. Or widened before 5118 // it can be split. 5119 if (!isTypeLegal(VecEVT)) 5120 return SDValue(); 5121 5122 MVT VecVT = VecEVT.getSimpleVT(); 5123 MVT VecEltVT = VecVT.getVectorElementType(); 5124 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5125 5126 MVT ContainerVT = VecVT; 5127 if (VecVT.isFixedLengthVector()) { 5128 ContainerVT = getContainerForFixedLengthVector(VecVT); 5129 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5130 } 5131 5132 MVT M1VT = getLMUL1VT(ContainerVT); 5133 MVT XLenVT = Subtarget.getXLenVT(); 5134 5135 SDValue Mask, VL; 5136 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5137 5138 SDValue NeutralElem = 5139 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5140 SDValue IdentitySplat = 5141 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5142 M1VT, DL, DAG, Subtarget); 5143 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5144 IdentitySplat, Mask, VL); 5145 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5146 DAG.getConstant(0, DL, XLenVT)); 5147 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5148 } 5149 5150 // Given a reduction op, this function returns the matching reduction opcode, 5151 // the vector SDValue and the scalar SDValue required to lower this to a 5152 // RISCVISD node. 5153 static std::tuple<unsigned, SDValue, SDValue> 5154 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5155 SDLoc DL(Op); 5156 auto Flags = Op->getFlags(); 5157 unsigned Opcode = Op.getOpcode(); 5158 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5159 switch (Opcode) { 5160 default: 5161 llvm_unreachable("Unhandled reduction"); 5162 case ISD::VECREDUCE_FADD: { 5163 // Use positive zero if we can. It is cheaper to materialize. 5164 SDValue Zero = 5165 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5166 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5167 } 5168 case ISD::VECREDUCE_SEQ_FADD: 5169 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5170 Op.getOperand(0)); 5171 case ISD::VECREDUCE_FMIN: 5172 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5173 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5174 case ISD::VECREDUCE_FMAX: 5175 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5176 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5177 } 5178 } 5179 5180 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5181 SelectionDAG &DAG) const { 5182 SDLoc DL(Op); 5183 MVT VecEltVT = Op.getSimpleValueType(); 5184 5185 unsigned RVVOpcode; 5186 SDValue VectorVal, ScalarVal; 5187 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5188 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5189 MVT VecVT = VectorVal.getSimpleValueType(); 5190 5191 MVT ContainerVT = VecVT; 5192 if (VecVT.isFixedLengthVector()) { 5193 ContainerVT = getContainerForFixedLengthVector(VecVT); 5194 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5195 } 5196 5197 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5198 MVT XLenVT = Subtarget.getXLenVT(); 5199 5200 SDValue Mask, VL; 5201 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5202 5203 SDValue ScalarSplat = 5204 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5205 M1VT, DL, DAG, Subtarget); 5206 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5207 VectorVal, ScalarSplat, Mask, VL); 5208 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5209 DAG.getConstant(0, DL, XLenVT)); 5210 } 5211 5212 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5213 switch (ISDOpcode) { 5214 default: 5215 llvm_unreachable("Unhandled reduction"); 5216 case ISD::VP_REDUCE_ADD: 5217 return RISCVISD::VECREDUCE_ADD_VL; 5218 case ISD::VP_REDUCE_UMAX: 5219 return RISCVISD::VECREDUCE_UMAX_VL; 5220 case ISD::VP_REDUCE_SMAX: 5221 return RISCVISD::VECREDUCE_SMAX_VL; 5222 case ISD::VP_REDUCE_UMIN: 5223 return RISCVISD::VECREDUCE_UMIN_VL; 5224 case ISD::VP_REDUCE_SMIN: 5225 return RISCVISD::VECREDUCE_SMIN_VL; 5226 case ISD::VP_REDUCE_AND: 5227 return RISCVISD::VECREDUCE_AND_VL; 5228 case ISD::VP_REDUCE_OR: 5229 return RISCVISD::VECREDUCE_OR_VL; 5230 case ISD::VP_REDUCE_XOR: 5231 return RISCVISD::VECREDUCE_XOR_VL; 5232 case ISD::VP_REDUCE_FADD: 5233 return RISCVISD::VECREDUCE_FADD_VL; 5234 case ISD::VP_REDUCE_SEQ_FADD: 5235 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5236 case ISD::VP_REDUCE_FMAX: 5237 return RISCVISD::VECREDUCE_FMAX_VL; 5238 case ISD::VP_REDUCE_FMIN: 5239 return RISCVISD::VECREDUCE_FMIN_VL; 5240 } 5241 } 5242 5243 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5244 SelectionDAG &DAG) const { 5245 SDLoc DL(Op); 5246 SDValue Vec = Op.getOperand(1); 5247 EVT VecEVT = Vec.getValueType(); 5248 5249 // TODO: The type may need to be widened rather than split. Or widened before 5250 // it can be split. 5251 if (!isTypeLegal(VecEVT)) 5252 return SDValue(); 5253 5254 MVT VecVT = VecEVT.getSimpleVT(); 5255 MVT VecEltVT = VecVT.getVectorElementType(); 5256 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5257 5258 MVT ContainerVT = VecVT; 5259 if (VecVT.isFixedLengthVector()) { 5260 ContainerVT = getContainerForFixedLengthVector(VecVT); 5261 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5262 } 5263 5264 SDValue VL = Op.getOperand(3); 5265 SDValue Mask = Op.getOperand(2); 5266 5267 MVT M1VT = getLMUL1VT(ContainerVT); 5268 MVT XLenVT = Subtarget.getXLenVT(); 5269 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5270 5271 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5272 DAG.getConstant(1, DL, XLenVT), M1VT, 5273 DL, DAG, Subtarget); 5274 SDValue Reduction = 5275 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5276 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5277 DAG.getConstant(0, DL, XLenVT)); 5278 if (!VecVT.isInteger()) 5279 return Elt0; 5280 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5281 } 5282 5283 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5284 SelectionDAG &DAG) const { 5285 SDValue Vec = Op.getOperand(0); 5286 SDValue SubVec = Op.getOperand(1); 5287 MVT VecVT = Vec.getSimpleValueType(); 5288 MVT SubVecVT = SubVec.getSimpleValueType(); 5289 5290 SDLoc DL(Op); 5291 MVT XLenVT = Subtarget.getXLenVT(); 5292 unsigned OrigIdx = Op.getConstantOperandVal(2); 5293 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5294 5295 // We don't have the ability to slide mask vectors up indexed by their i1 5296 // elements; the smallest we can do is i8. Often we are able to bitcast to 5297 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5298 // into a scalable one, we might not necessarily have enough scalable 5299 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5300 if (SubVecVT.getVectorElementType() == MVT::i1 && 5301 (OrigIdx != 0 || !Vec.isUndef())) { 5302 if (VecVT.getVectorMinNumElements() >= 8 && 5303 SubVecVT.getVectorMinNumElements() >= 8) { 5304 assert(OrigIdx % 8 == 0 && "Invalid index"); 5305 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5306 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5307 "Unexpected mask vector lowering"); 5308 OrigIdx /= 8; 5309 SubVecVT = 5310 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5311 SubVecVT.isScalableVector()); 5312 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5313 VecVT.isScalableVector()); 5314 Vec = DAG.getBitcast(VecVT, Vec); 5315 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5316 } else { 5317 // We can't slide this mask vector up indexed by its i1 elements. 5318 // This poses a problem when we wish to insert a scalable vector which 5319 // can't be re-expressed as a larger type. Just choose the slow path and 5320 // extend to a larger type, then truncate back down. 5321 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5322 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5323 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5324 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5325 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5326 Op.getOperand(2)); 5327 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5328 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5329 } 5330 } 5331 5332 // If the subvector vector is a fixed-length type, we cannot use subregister 5333 // manipulation to simplify the codegen; we don't know which register of a 5334 // LMUL group contains the specific subvector as we only know the minimum 5335 // register size. Therefore we must slide the vector group up the full 5336 // amount. 5337 if (SubVecVT.isFixedLengthVector()) { 5338 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5339 return Op; 5340 MVT ContainerVT = VecVT; 5341 if (VecVT.isFixedLengthVector()) { 5342 ContainerVT = getContainerForFixedLengthVector(VecVT); 5343 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5344 } 5345 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5346 DAG.getUNDEF(ContainerVT), SubVec, 5347 DAG.getConstant(0, DL, XLenVT)); 5348 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5349 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5350 return DAG.getBitcast(Op.getValueType(), SubVec); 5351 } 5352 SDValue Mask = 5353 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5354 // Set the vector length to only the number of elements we care about. Note 5355 // that for slideup this includes the offset. 5356 SDValue VL = 5357 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5358 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5359 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5360 SubVec, SlideupAmt, Mask, VL); 5361 if (VecVT.isFixedLengthVector()) 5362 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5363 return DAG.getBitcast(Op.getValueType(), Slideup); 5364 } 5365 5366 unsigned SubRegIdx, RemIdx; 5367 std::tie(SubRegIdx, RemIdx) = 5368 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5369 VecVT, SubVecVT, OrigIdx, TRI); 5370 5371 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5372 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5373 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5374 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5375 5376 // 1. If the Idx has been completely eliminated and this subvector's size is 5377 // a vector register or a multiple thereof, or the surrounding elements are 5378 // undef, then this is a subvector insert which naturally aligns to a vector 5379 // register. These can easily be handled using subregister manipulation. 5380 // 2. If the subvector is smaller than a vector register, then the insertion 5381 // must preserve the undisturbed elements of the register. We do this by 5382 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5383 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5384 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5385 // LMUL=1 type back into the larger vector (resolving to another subregister 5386 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5387 // to avoid allocating a large register group to hold our subvector. 5388 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5389 return Op; 5390 5391 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5392 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5393 // (in our case undisturbed). This means we can set up a subvector insertion 5394 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5395 // size of the subvector. 5396 MVT InterSubVT = VecVT; 5397 SDValue AlignedExtract = Vec; 5398 unsigned AlignedIdx = OrigIdx - RemIdx; 5399 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5400 InterSubVT = getLMUL1VT(VecVT); 5401 // Extract a subvector equal to the nearest full vector register type. This 5402 // should resolve to a EXTRACT_SUBREG instruction. 5403 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5404 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5405 } 5406 5407 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5408 // For scalable vectors this must be further multiplied by vscale. 5409 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5410 5411 SDValue Mask, VL; 5412 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5413 5414 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5415 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5416 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5417 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5418 5419 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5420 DAG.getUNDEF(InterSubVT), SubVec, 5421 DAG.getConstant(0, DL, XLenVT)); 5422 5423 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5424 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5425 5426 // If required, insert this subvector back into the correct vector register. 5427 // This should resolve to an INSERT_SUBREG instruction. 5428 if (VecVT.bitsGT(InterSubVT)) 5429 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5430 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5431 5432 // We might have bitcast from a mask type: cast back to the original type if 5433 // required. 5434 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5435 } 5436 5437 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5438 SelectionDAG &DAG) const { 5439 SDValue Vec = Op.getOperand(0); 5440 MVT SubVecVT = Op.getSimpleValueType(); 5441 MVT VecVT = Vec.getSimpleValueType(); 5442 5443 SDLoc DL(Op); 5444 MVT XLenVT = Subtarget.getXLenVT(); 5445 unsigned OrigIdx = Op.getConstantOperandVal(1); 5446 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5447 5448 // We don't have the ability to slide mask vectors down indexed by their i1 5449 // elements; the smallest we can do is i8. Often we are able to bitcast to 5450 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5451 // from a scalable one, we might not necessarily have enough scalable 5452 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5453 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5454 if (VecVT.getVectorMinNumElements() >= 8 && 5455 SubVecVT.getVectorMinNumElements() >= 8) { 5456 assert(OrigIdx % 8 == 0 && "Invalid index"); 5457 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5458 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5459 "Unexpected mask vector lowering"); 5460 OrigIdx /= 8; 5461 SubVecVT = 5462 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5463 SubVecVT.isScalableVector()); 5464 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5465 VecVT.isScalableVector()); 5466 Vec = DAG.getBitcast(VecVT, Vec); 5467 } else { 5468 // We can't slide this mask vector down, indexed by its i1 elements. 5469 // This poses a problem when we wish to extract a scalable vector which 5470 // can't be re-expressed as a larger type. Just choose the slow path and 5471 // extend to a larger type, then truncate back down. 5472 // TODO: We could probably improve this when extracting certain fixed 5473 // from fixed, where we can extract as i8 and shift the correct element 5474 // right to reach the desired subvector? 5475 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5476 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5477 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5478 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5479 Op.getOperand(1)); 5480 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5481 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5482 } 5483 } 5484 5485 // If the subvector vector is a fixed-length type, we cannot use subregister 5486 // manipulation to simplify the codegen; we don't know which register of a 5487 // LMUL group contains the specific subvector as we only know the minimum 5488 // register size. Therefore we must slide the vector group down the full 5489 // amount. 5490 if (SubVecVT.isFixedLengthVector()) { 5491 // With an index of 0 this is a cast-like subvector, which can be performed 5492 // with subregister operations. 5493 if (OrigIdx == 0) 5494 return Op; 5495 MVT ContainerVT = VecVT; 5496 if (VecVT.isFixedLengthVector()) { 5497 ContainerVT = getContainerForFixedLengthVector(VecVT); 5498 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5499 } 5500 SDValue Mask = 5501 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5502 // Set the vector length to only the number of elements we care about. This 5503 // avoids sliding down elements we're going to discard straight away. 5504 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5505 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5506 SDValue Slidedown = 5507 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5508 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5509 // Now we can use a cast-like subvector extract to get the result. 5510 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5511 DAG.getConstant(0, DL, XLenVT)); 5512 return DAG.getBitcast(Op.getValueType(), Slidedown); 5513 } 5514 5515 unsigned SubRegIdx, RemIdx; 5516 std::tie(SubRegIdx, RemIdx) = 5517 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5518 VecVT, SubVecVT, OrigIdx, TRI); 5519 5520 // If the Idx has been completely eliminated then this is a subvector extract 5521 // which naturally aligns to a vector register. These can easily be handled 5522 // using subregister manipulation. 5523 if (RemIdx == 0) 5524 return Op; 5525 5526 // Else we must shift our vector register directly to extract the subvector. 5527 // Do this using VSLIDEDOWN. 5528 5529 // If the vector type is an LMUL-group type, extract a subvector equal to the 5530 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5531 // instruction. 5532 MVT InterSubVT = VecVT; 5533 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5534 InterSubVT = getLMUL1VT(VecVT); 5535 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5536 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5537 } 5538 5539 // Slide this vector register down by the desired number of elements in order 5540 // to place the desired subvector starting at element 0. 5541 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5542 // For scalable vectors this must be further multiplied by vscale. 5543 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5544 5545 SDValue Mask, VL; 5546 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5547 SDValue Slidedown = 5548 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5549 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5550 5551 // Now the vector is in the right position, extract our final subvector. This 5552 // should resolve to a COPY. 5553 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5554 DAG.getConstant(0, DL, XLenVT)); 5555 5556 // We might have bitcast from a mask type: cast back to the original type if 5557 // required. 5558 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5559 } 5560 5561 // Lower step_vector to the vid instruction. Any non-identity step value must 5562 // be accounted for my manual expansion. 5563 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5564 SelectionDAG &DAG) const { 5565 SDLoc DL(Op); 5566 MVT VT = Op.getSimpleValueType(); 5567 MVT XLenVT = Subtarget.getXLenVT(); 5568 SDValue Mask, VL; 5569 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5570 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5571 uint64_t StepValImm = Op.getConstantOperandVal(0); 5572 if (StepValImm != 1) { 5573 if (isPowerOf2_64(StepValImm)) { 5574 SDValue StepVal = 5575 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5576 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5577 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5578 } else { 5579 SDValue StepVal = lowerScalarSplat( 5580 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5581 VL, VT, DL, DAG, Subtarget); 5582 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5583 } 5584 } 5585 return StepVec; 5586 } 5587 5588 // Implement vector_reverse using vrgather.vv with indices determined by 5589 // subtracting the id of each element from (VLMAX-1). This will convert 5590 // the indices like so: 5591 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5592 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5593 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5594 SelectionDAG &DAG) const { 5595 SDLoc DL(Op); 5596 MVT VecVT = Op.getSimpleValueType(); 5597 unsigned EltSize = VecVT.getScalarSizeInBits(); 5598 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5599 5600 unsigned MaxVLMAX = 0; 5601 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5602 if (VectorBitsMax != 0) 5603 MaxVLMAX = 5604 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5605 5606 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5607 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5608 5609 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5610 // to use vrgatherei16.vv. 5611 // TODO: It's also possible to use vrgatherei16.vv for other types to 5612 // decrease register width for the index calculation. 5613 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5614 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5615 // Reverse each half, then reassemble them in reverse order. 5616 // NOTE: It's also possible that after splitting that VLMAX no longer 5617 // requires vrgatherei16.vv. 5618 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5619 SDValue Lo, Hi; 5620 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5621 EVT LoVT, HiVT; 5622 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5623 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5624 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5625 // Reassemble the low and high pieces reversed. 5626 // FIXME: This is a CONCAT_VECTORS. 5627 SDValue Res = 5628 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5629 DAG.getIntPtrConstant(0, DL)); 5630 return DAG.getNode( 5631 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5632 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5633 } 5634 5635 // Just promote the int type to i16 which will double the LMUL. 5636 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5637 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5638 } 5639 5640 MVT XLenVT = Subtarget.getXLenVT(); 5641 SDValue Mask, VL; 5642 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5643 5644 // Calculate VLMAX-1 for the desired SEW. 5645 unsigned MinElts = VecVT.getVectorMinNumElements(); 5646 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5647 DAG.getConstant(MinElts, DL, XLenVT)); 5648 SDValue VLMinus1 = 5649 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5650 5651 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5652 bool IsRV32E64 = 5653 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5654 SDValue SplatVL; 5655 if (!IsRV32E64) 5656 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5657 else 5658 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5659 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5660 5661 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5662 SDValue Indices = 5663 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5664 5665 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5666 } 5667 5668 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5669 SelectionDAG &DAG) const { 5670 SDLoc DL(Op); 5671 SDValue V1 = Op.getOperand(0); 5672 SDValue V2 = Op.getOperand(1); 5673 MVT XLenVT = Subtarget.getXLenVT(); 5674 MVT VecVT = Op.getSimpleValueType(); 5675 5676 unsigned MinElts = VecVT.getVectorMinNumElements(); 5677 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5678 DAG.getConstant(MinElts, DL, XLenVT)); 5679 5680 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5681 SDValue DownOffset, UpOffset; 5682 if (ImmValue >= 0) { 5683 // The operand is a TargetConstant, we need to rebuild it as a regular 5684 // constant. 5685 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5686 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5687 } else { 5688 // The operand is a TargetConstant, we need to rebuild it as a regular 5689 // constant rather than negating the original operand. 5690 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5691 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5692 } 5693 5694 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5695 5696 SDValue SlideDown = 5697 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5698 DownOffset, TrueMask, UpOffset); 5699 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5700 TrueMask, 5701 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5702 } 5703 5704 SDValue 5705 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5706 SelectionDAG &DAG) const { 5707 SDLoc DL(Op); 5708 auto *Load = cast<LoadSDNode>(Op); 5709 5710 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5711 Load->getMemoryVT(), 5712 *Load->getMemOperand()) && 5713 "Expecting a correctly-aligned load"); 5714 5715 MVT VT = Op.getSimpleValueType(); 5716 MVT XLenVT = Subtarget.getXLenVT(); 5717 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5718 5719 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5720 5721 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5722 SDValue IntID = DAG.getTargetConstant( 5723 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5724 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5725 if (!IsMaskOp) 5726 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5727 Ops.push_back(Load->getBasePtr()); 5728 Ops.push_back(VL); 5729 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5730 SDValue NewLoad = 5731 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5732 Load->getMemoryVT(), Load->getMemOperand()); 5733 5734 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5735 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5736 } 5737 5738 SDValue 5739 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5740 SelectionDAG &DAG) const { 5741 SDLoc DL(Op); 5742 auto *Store = cast<StoreSDNode>(Op); 5743 5744 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5745 Store->getMemoryVT(), 5746 *Store->getMemOperand()) && 5747 "Expecting a correctly-aligned store"); 5748 5749 SDValue StoreVal = Store->getValue(); 5750 MVT VT = StoreVal.getSimpleValueType(); 5751 MVT XLenVT = Subtarget.getXLenVT(); 5752 5753 // If the size less than a byte, we need to pad with zeros to make a byte. 5754 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5755 VT = MVT::v8i1; 5756 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5757 DAG.getConstant(0, DL, VT), StoreVal, 5758 DAG.getIntPtrConstant(0, DL)); 5759 } 5760 5761 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5762 5763 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5764 5765 SDValue NewValue = 5766 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5767 5768 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5769 SDValue IntID = DAG.getTargetConstant( 5770 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5771 return DAG.getMemIntrinsicNode( 5772 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5773 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5774 Store->getMemoryVT(), Store->getMemOperand()); 5775 } 5776 5777 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5778 SelectionDAG &DAG) const { 5779 SDLoc DL(Op); 5780 MVT VT = Op.getSimpleValueType(); 5781 5782 const auto *MemSD = cast<MemSDNode>(Op); 5783 EVT MemVT = MemSD->getMemoryVT(); 5784 MachineMemOperand *MMO = MemSD->getMemOperand(); 5785 SDValue Chain = MemSD->getChain(); 5786 SDValue BasePtr = MemSD->getBasePtr(); 5787 5788 SDValue Mask, PassThru, VL; 5789 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5790 Mask = VPLoad->getMask(); 5791 PassThru = DAG.getUNDEF(VT); 5792 VL = VPLoad->getVectorLength(); 5793 } else { 5794 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5795 Mask = MLoad->getMask(); 5796 PassThru = MLoad->getPassThru(); 5797 } 5798 5799 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5800 5801 MVT XLenVT = Subtarget.getXLenVT(); 5802 5803 MVT ContainerVT = VT; 5804 if (VT.isFixedLengthVector()) { 5805 ContainerVT = getContainerForFixedLengthVector(VT); 5806 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5807 if (!IsUnmasked) { 5808 MVT MaskVT = getMaskTypeFor(ContainerVT); 5809 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5810 } 5811 } 5812 5813 if (!VL) 5814 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5815 5816 unsigned IntID = 5817 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5818 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5819 if (IsUnmasked) 5820 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5821 else 5822 Ops.push_back(PassThru); 5823 Ops.push_back(BasePtr); 5824 if (!IsUnmasked) 5825 Ops.push_back(Mask); 5826 Ops.push_back(VL); 5827 if (!IsUnmasked) 5828 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5829 5830 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5831 5832 SDValue Result = 5833 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5834 Chain = Result.getValue(1); 5835 5836 if (VT.isFixedLengthVector()) 5837 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5838 5839 return DAG.getMergeValues({Result, Chain}, DL); 5840 } 5841 5842 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5843 SelectionDAG &DAG) const { 5844 SDLoc DL(Op); 5845 5846 const auto *MemSD = cast<MemSDNode>(Op); 5847 EVT MemVT = MemSD->getMemoryVT(); 5848 MachineMemOperand *MMO = MemSD->getMemOperand(); 5849 SDValue Chain = MemSD->getChain(); 5850 SDValue BasePtr = MemSD->getBasePtr(); 5851 SDValue Val, Mask, VL; 5852 5853 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5854 Val = VPStore->getValue(); 5855 Mask = VPStore->getMask(); 5856 VL = VPStore->getVectorLength(); 5857 } else { 5858 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5859 Val = MStore->getValue(); 5860 Mask = MStore->getMask(); 5861 } 5862 5863 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5864 5865 MVT VT = Val.getSimpleValueType(); 5866 MVT XLenVT = Subtarget.getXLenVT(); 5867 5868 MVT ContainerVT = VT; 5869 if (VT.isFixedLengthVector()) { 5870 ContainerVT = getContainerForFixedLengthVector(VT); 5871 5872 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5873 if (!IsUnmasked) { 5874 MVT MaskVT = getMaskTypeFor(ContainerVT); 5875 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5876 } 5877 } 5878 5879 if (!VL) 5880 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5881 5882 unsigned IntID = 5883 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5884 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5885 Ops.push_back(Val); 5886 Ops.push_back(BasePtr); 5887 if (!IsUnmasked) 5888 Ops.push_back(Mask); 5889 Ops.push_back(VL); 5890 5891 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5892 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5893 } 5894 5895 SDValue 5896 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5897 SelectionDAG &DAG) const { 5898 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5899 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5900 5901 MVT VT = Op.getSimpleValueType(); 5902 5903 SDValue Op1 = 5904 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5905 SDValue Op2 = 5906 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5907 5908 SDLoc DL(Op); 5909 SDValue VL = 5910 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5911 5912 MVT MaskVT = getMaskTypeFor(ContainerVT); 5913 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5914 5915 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5916 Op.getOperand(2), Mask, VL); 5917 5918 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5919 } 5920 5921 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5922 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5923 MVT VT = Op.getSimpleValueType(); 5924 5925 if (VT.getVectorElementType() == MVT::i1) 5926 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5927 5928 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5929 } 5930 5931 SDValue 5932 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5933 SelectionDAG &DAG) const { 5934 unsigned Opc; 5935 switch (Op.getOpcode()) { 5936 default: llvm_unreachable("Unexpected opcode!"); 5937 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5938 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5939 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5940 } 5941 5942 return lowerToScalableOp(Op, DAG, Opc); 5943 } 5944 5945 // Lower vector ABS to smax(X, sub(0, X)). 5946 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5947 SDLoc DL(Op); 5948 MVT VT = Op.getSimpleValueType(); 5949 SDValue X = Op.getOperand(0); 5950 5951 assert(VT.isFixedLengthVector() && "Unexpected type"); 5952 5953 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5954 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5955 5956 SDValue Mask, VL; 5957 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5958 5959 SDValue SplatZero = DAG.getNode( 5960 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5961 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5962 SDValue NegX = 5963 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5964 SDValue Max = 5965 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5966 5967 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5968 } 5969 5970 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5971 SDValue Op, SelectionDAG &DAG) const { 5972 SDLoc DL(Op); 5973 MVT VT = Op.getSimpleValueType(); 5974 SDValue Mag = Op.getOperand(0); 5975 SDValue Sign = Op.getOperand(1); 5976 assert(Mag.getValueType() == Sign.getValueType() && 5977 "Can only handle COPYSIGN with matching types."); 5978 5979 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5980 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5981 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5982 5983 SDValue Mask, VL; 5984 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5985 5986 SDValue CopySign = 5987 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5988 5989 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5990 } 5991 5992 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5993 SDValue Op, SelectionDAG &DAG) const { 5994 MVT VT = Op.getSimpleValueType(); 5995 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5996 5997 MVT I1ContainerVT = 5998 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5999 6000 SDValue CC = 6001 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6002 SDValue Op1 = 6003 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6004 SDValue Op2 = 6005 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6006 6007 SDLoc DL(Op); 6008 SDValue Mask, VL; 6009 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6010 6011 SDValue Select = 6012 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6013 6014 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6015 } 6016 6017 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6018 unsigned NewOpc, 6019 bool HasMask) const { 6020 MVT VT = Op.getSimpleValueType(); 6021 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6022 6023 // Create list of operands by converting existing ones to scalable types. 6024 SmallVector<SDValue, 6> Ops; 6025 for (const SDValue &V : Op->op_values()) { 6026 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6027 6028 // Pass through non-vector operands. 6029 if (!V.getValueType().isVector()) { 6030 Ops.push_back(V); 6031 continue; 6032 } 6033 6034 // "cast" fixed length vector to a scalable vector. 6035 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6036 "Only fixed length vectors are supported!"); 6037 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6038 } 6039 6040 SDLoc DL(Op); 6041 SDValue Mask, VL; 6042 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6043 if (HasMask) 6044 Ops.push_back(Mask); 6045 Ops.push_back(VL); 6046 6047 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6048 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6049 } 6050 6051 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6052 // * Operands of each node are assumed to be in the same order. 6053 // * The EVL operand is promoted from i32 to i64 on RV64. 6054 // * Fixed-length vectors are converted to their scalable-vector container 6055 // types. 6056 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6057 unsigned RISCVISDOpc) const { 6058 SDLoc DL(Op); 6059 MVT VT = Op.getSimpleValueType(); 6060 SmallVector<SDValue, 4> Ops; 6061 6062 for (const auto &OpIdx : enumerate(Op->ops())) { 6063 SDValue V = OpIdx.value(); 6064 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6065 // Pass through operands which aren't fixed-length vectors. 6066 if (!V.getValueType().isFixedLengthVector()) { 6067 Ops.push_back(V); 6068 continue; 6069 } 6070 // "cast" fixed length vector to a scalable vector. 6071 MVT OpVT = V.getSimpleValueType(); 6072 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6073 assert(useRVVForFixedLengthVectorVT(OpVT) && 6074 "Only fixed length vectors are supported!"); 6075 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6076 } 6077 6078 if (!VT.isFixedLengthVector()) 6079 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6080 6081 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6082 6083 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6084 6085 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6086 } 6087 6088 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6089 SelectionDAG &DAG) const { 6090 SDLoc DL(Op); 6091 MVT VT = Op.getSimpleValueType(); 6092 6093 SDValue Src = Op.getOperand(0); 6094 // NOTE: Mask is dropped. 6095 SDValue VL = Op.getOperand(2); 6096 6097 MVT ContainerVT = VT; 6098 if (VT.isFixedLengthVector()) { 6099 ContainerVT = getContainerForFixedLengthVector(VT); 6100 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6101 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6102 } 6103 6104 MVT XLenVT = Subtarget.getXLenVT(); 6105 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6106 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6107 DAG.getUNDEF(ContainerVT), Zero, VL); 6108 6109 SDValue SplatValue = 6110 DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT); 6111 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6112 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6113 6114 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6115 Splat, ZeroSplat, VL); 6116 if (!VT.isFixedLengthVector()) 6117 return Result; 6118 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6119 } 6120 6121 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6122 SelectionDAG &DAG) const { 6123 SDLoc DL(Op); 6124 MVT VT = Op.getSimpleValueType(); 6125 6126 SDValue Op1 = Op.getOperand(0); 6127 SDValue Op2 = Op.getOperand(1); 6128 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6129 // NOTE: Mask is dropped. 6130 SDValue VL = Op.getOperand(4); 6131 6132 MVT ContainerVT = VT; 6133 if (VT.isFixedLengthVector()) { 6134 ContainerVT = getContainerForFixedLengthVector(VT); 6135 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6136 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6137 } 6138 6139 SDValue Result; 6140 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6141 6142 switch (Condition) { 6143 default: 6144 break; 6145 // X != Y --> (X^Y) 6146 case ISD::SETNE: 6147 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6148 break; 6149 // X == Y --> ~(X^Y) 6150 case ISD::SETEQ: { 6151 SDValue Temp = 6152 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6153 Result = 6154 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6155 break; 6156 } 6157 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6158 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6159 case ISD::SETGT: 6160 case ISD::SETULT: { 6161 SDValue Temp = 6162 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6163 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6164 break; 6165 } 6166 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6167 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6168 case ISD::SETLT: 6169 case ISD::SETUGT: { 6170 SDValue Temp = 6171 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6172 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6173 break; 6174 } 6175 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6176 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6177 case ISD::SETGE: 6178 case ISD::SETULE: { 6179 SDValue Temp = 6180 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6181 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6182 break; 6183 } 6184 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6185 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6186 case ISD::SETLE: 6187 case ISD::SETUGE: { 6188 SDValue Temp = 6189 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6190 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6191 break; 6192 } 6193 } 6194 6195 if (!VT.isFixedLengthVector()) 6196 return Result; 6197 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6198 } 6199 6200 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6201 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6202 unsigned RISCVISDOpc) const { 6203 SDLoc DL(Op); 6204 6205 SDValue Src = Op.getOperand(0); 6206 SDValue Mask = Op.getOperand(1); 6207 SDValue VL = Op.getOperand(2); 6208 6209 MVT DstVT = Op.getSimpleValueType(); 6210 MVT SrcVT = Src.getSimpleValueType(); 6211 if (DstVT.isFixedLengthVector()) { 6212 DstVT = getContainerForFixedLengthVector(DstVT); 6213 SrcVT = getContainerForFixedLengthVector(SrcVT); 6214 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6215 MVT MaskVT = getMaskTypeFor(DstVT); 6216 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6217 } 6218 6219 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6220 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6221 ? RISCVISD::VSEXT_VL 6222 : RISCVISD::VZEXT_VL; 6223 6224 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6225 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6226 6227 SDValue Result; 6228 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6229 if (SrcVT.isInteger()) { 6230 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6231 6232 // Do we need to do any pre-widening before converting? 6233 if (SrcEltSize == 1) { 6234 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6235 MVT XLenVT = Subtarget.getXLenVT(); 6236 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6237 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6238 DAG.getUNDEF(IntVT), Zero, VL); 6239 SDValue One = DAG.getConstant( 6240 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6241 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6242 DAG.getUNDEF(IntVT), One, VL); 6243 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6244 ZeroSplat, VL); 6245 } else if (DstEltSize > (2 * SrcEltSize)) { 6246 // Widen before converting. 6247 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6248 DstVT.getVectorElementCount()); 6249 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6250 } 6251 6252 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6253 } else { 6254 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6255 "Wrong input/output vector types"); 6256 6257 // Convert f16 to f32 then convert f32 to i64. 6258 if (DstEltSize > (2 * SrcEltSize)) { 6259 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6260 MVT InterimFVT = 6261 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6262 Src = 6263 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6264 } 6265 6266 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6267 } 6268 } else { // Narrowing + Conversion 6269 if (SrcVT.isInteger()) { 6270 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6271 // First do a narrowing convert to an FP type half the size, then round 6272 // the FP type to a small FP type if needed. 6273 6274 MVT InterimFVT = DstVT; 6275 if (SrcEltSize > (2 * DstEltSize)) { 6276 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6277 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6278 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6279 } 6280 6281 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6282 6283 if (InterimFVT != DstVT) { 6284 Src = Result; 6285 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6286 } 6287 } else { 6288 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6289 "Wrong input/output vector types"); 6290 // First do a narrowing conversion to an integer half the size, then 6291 // truncate if needed. 6292 6293 if (DstEltSize == 1) { 6294 // First convert to the same size integer, then convert to mask using 6295 // setcc. 6296 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6297 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6298 DstVT.getVectorElementCount()); 6299 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6300 6301 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6302 // otherwise the conversion was undefined. 6303 MVT XLenVT = Subtarget.getXLenVT(); 6304 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6305 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6306 DAG.getUNDEF(InterimIVT), SplatZero); 6307 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6308 DAG.getCondCode(ISD::SETNE), Mask, VL); 6309 } else { 6310 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6311 DstVT.getVectorElementCount()); 6312 6313 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6314 6315 while (InterimIVT != DstVT) { 6316 SrcEltSize /= 2; 6317 Src = Result; 6318 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6319 DstVT.getVectorElementCount()); 6320 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6321 Src, Mask, VL); 6322 } 6323 } 6324 } 6325 } 6326 6327 MVT VT = Op.getSimpleValueType(); 6328 if (!VT.isFixedLengthVector()) 6329 return Result; 6330 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6331 } 6332 6333 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6334 unsigned MaskOpc, 6335 unsigned VecOpc) const { 6336 MVT VT = Op.getSimpleValueType(); 6337 if (VT.getVectorElementType() != MVT::i1) 6338 return lowerVPOp(Op, DAG, VecOpc); 6339 6340 // It is safe to drop mask parameter as masked-off elements are undef. 6341 SDValue Op1 = Op->getOperand(0); 6342 SDValue Op2 = Op->getOperand(1); 6343 SDValue VL = Op->getOperand(3); 6344 6345 MVT ContainerVT = VT; 6346 const bool IsFixed = VT.isFixedLengthVector(); 6347 if (IsFixed) { 6348 ContainerVT = getContainerForFixedLengthVector(VT); 6349 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6350 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6351 } 6352 6353 SDLoc DL(Op); 6354 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6355 if (!IsFixed) 6356 return Val; 6357 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6358 } 6359 6360 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6361 // matched to a RVV indexed load. The RVV indexed load instructions only 6362 // support the "unsigned unscaled" addressing mode; indices are implicitly 6363 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6364 // signed or scaled indexing is extended to the XLEN value type and scaled 6365 // accordingly. 6366 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6367 SelectionDAG &DAG) const { 6368 SDLoc DL(Op); 6369 MVT VT = Op.getSimpleValueType(); 6370 6371 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6372 EVT MemVT = MemSD->getMemoryVT(); 6373 MachineMemOperand *MMO = MemSD->getMemOperand(); 6374 SDValue Chain = MemSD->getChain(); 6375 SDValue BasePtr = MemSD->getBasePtr(); 6376 6377 ISD::LoadExtType LoadExtType; 6378 SDValue Index, Mask, PassThru, VL; 6379 6380 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6381 Index = VPGN->getIndex(); 6382 Mask = VPGN->getMask(); 6383 PassThru = DAG.getUNDEF(VT); 6384 VL = VPGN->getVectorLength(); 6385 // VP doesn't support extending loads. 6386 LoadExtType = ISD::NON_EXTLOAD; 6387 } else { 6388 // Else it must be a MGATHER. 6389 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6390 Index = MGN->getIndex(); 6391 Mask = MGN->getMask(); 6392 PassThru = MGN->getPassThru(); 6393 LoadExtType = MGN->getExtensionType(); 6394 } 6395 6396 MVT IndexVT = Index.getSimpleValueType(); 6397 MVT XLenVT = Subtarget.getXLenVT(); 6398 6399 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6400 "Unexpected VTs!"); 6401 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6402 // Targets have to explicitly opt-in for extending vector loads. 6403 assert(LoadExtType == ISD::NON_EXTLOAD && 6404 "Unexpected extending MGATHER/VP_GATHER"); 6405 (void)LoadExtType; 6406 6407 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6408 // the selection of the masked intrinsics doesn't do this for us. 6409 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6410 6411 MVT ContainerVT = VT; 6412 if (VT.isFixedLengthVector()) { 6413 // We need to use the larger of the result and index type to determine the 6414 // scalable type to use so we don't increase LMUL for any operand/result. 6415 if (VT.bitsGE(IndexVT)) { 6416 ContainerVT = getContainerForFixedLengthVector(VT); 6417 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6418 ContainerVT.getVectorElementCount()); 6419 } else { 6420 IndexVT = getContainerForFixedLengthVector(IndexVT); 6421 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6422 IndexVT.getVectorElementCount()); 6423 } 6424 6425 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6426 6427 if (!IsUnmasked) { 6428 MVT MaskVT = getMaskTypeFor(ContainerVT); 6429 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6430 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6431 } 6432 } 6433 6434 if (!VL) 6435 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6436 6437 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6438 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6439 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6440 VL); 6441 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6442 TrueMask, VL); 6443 } 6444 6445 unsigned IntID = 6446 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6447 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6448 if (IsUnmasked) 6449 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6450 else 6451 Ops.push_back(PassThru); 6452 Ops.push_back(BasePtr); 6453 Ops.push_back(Index); 6454 if (!IsUnmasked) 6455 Ops.push_back(Mask); 6456 Ops.push_back(VL); 6457 if (!IsUnmasked) 6458 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6459 6460 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6461 SDValue Result = 6462 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6463 Chain = Result.getValue(1); 6464 6465 if (VT.isFixedLengthVector()) 6466 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6467 6468 return DAG.getMergeValues({Result, Chain}, DL); 6469 } 6470 6471 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6472 // matched to a RVV indexed store. The RVV indexed store instructions only 6473 // support the "unsigned unscaled" addressing mode; indices are implicitly 6474 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6475 // signed or scaled indexing is extended to the XLEN value type and scaled 6476 // accordingly. 6477 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6478 SelectionDAG &DAG) const { 6479 SDLoc DL(Op); 6480 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6481 EVT MemVT = MemSD->getMemoryVT(); 6482 MachineMemOperand *MMO = MemSD->getMemOperand(); 6483 SDValue Chain = MemSD->getChain(); 6484 SDValue BasePtr = MemSD->getBasePtr(); 6485 6486 bool IsTruncatingStore = false; 6487 SDValue Index, Mask, Val, VL; 6488 6489 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6490 Index = VPSN->getIndex(); 6491 Mask = VPSN->getMask(); 6492 Val = VPSN->getValue(); 6493 VL = VPSN->getVectorLength(); 6494 // VP doesn't support truncating stores. 6495 IsTruncatingStore = false; 6496 } else { 6497 // Else it must be a MSCATTER. 6498 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6499 Index = MSN->getIndex(); 6500 Mask = MSN->getMask(); 6501 Val = MSN->getValue(); 6502 IsTruncatingStore = MSN->isTruncatingStore(); 6503 } 6504 6505 MVT VT = Val.getSimpleValueType(); 6506 MVT IndexVT = Index.getSimpleValueType(); 6507 MVT XLenVT = Subtarget.getXLenVT(); 6508 6509 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6510 "Unexpected VTs!"); 6511 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6512 // Targets have to explicitly opt-in for extending vector loads and 6513 // truncating vector stores. 6514 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6515 (void)IsTruncatingStore; 6516 6517 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6518 // the selection of the masked intrinsics doesn't do this for us. 6519 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6520 6521 MVT ContainerVT = VT; 6522 if (VT.isFixedLengthVector()) { 6523 // We need to use the larger of the value and index type to determine the 6524 // scalable type to use so we don't increase LMUL for any operand/result. 6525 if (VT.bitsGE(IndexVT)) { 6526 ContainerVT = getContainerForFixedLengthVector(VT); 6527 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6528 ContainerVT.getVectorElementCount()); 6529 } else { 6530 IndexVT = getContainerForFixedLengthVector(IndexVT); 6531 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6532 IndexVT.getVectorElementCount()); 6533 } 6534 6535 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6536 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6537 6538 if (!IsUnmasked) { 6539 MVT MaskVT = getMaskTypeFor(ContainerVT); 6540 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6541 } 6542 } 6543 6544 if (!VL) 6545 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6546 6547 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6548 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6549 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6550 VL); 6551 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6552 TrueMask, VL); 6553 } 6554 6555 unsigned IntID = 6556 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6557 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6558 Ops.push_back(Val); 6559 Ops.push_back(BasePtr); 6560 Ops.push_back(Index); 6561 if (!IsUnmasked) 6562 Ops.push_back(Mask); 6563 Ops.push_back(VL); 6564 6565 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6566 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6567 } 6568 6569 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6570 SelectionDAG &DAG) const { 6571 const MVT XLenVT = Subtarget.getXLenVT(); 6572 SDLoc DL(Op); 6573 SDValue Chain = Op->getOperand(0); 6574 SDValue SysRegNo = DAG.getTargetConstant( 6575 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6576 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6577 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6578 6579 // Encoding used for rounding mode in RISCV differs from that used in 6580 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6581 // table, which consists of a sequence of 4-bit fields, each representing 6582 // corresponding FLT_ROUNDS mode. 6583 static const int Table = 6584 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6585 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6586 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6587 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6588 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6589 6590 SDValue Shift = 6591 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6592 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6593 DAG.getConstant(Table, DL, XLenVT), Shift); 6594 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6595 DAG.getConstant(7, DL, XLenVT)); 6596 6597 return DAG.getMergeValues({Masked, Chain}, DL); 6598 } 6599 6600 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6601 SelectionDAG &DAG) const { 6602 const MVT XLenVT = Subtarget.getXLenVT(); 6603 SDLoc DL(Op); 6604 SDValue Chain = Op->getOperand(0); 6605 SDValue RMValue = Op->getOperand(1); 6606 SDValue SysRegNo = DAG.getTargetConstant( 6607 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6608 6609 // Encoding used for rounding mode in RISCV differs from that used in 6610 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6611 // a table, which consists of a sequence of 4-bit fields, each representing 6612 // corresponding RISCV mode. 6613 static const unsigned Table = 6614 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6615 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6616 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6617 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6618 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6619 6620 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6621 DAG.getConstant(2, DL, XLenVT)); 6622 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6623 DAG.getConstant(Table, DL, XLenVT), Shift); 6624 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6625 DAG.getConstant(0x7, DL, XLenVT)); 6626 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6627 RMValue); 6628 } 6629 6630 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6631 switch (IntNo) { 6632 default: 6633 llvm_unreachable("Unexpected Intrinsic"); 6634 case Intrinsic::riscv_bcompress: 6635 return RISCVISD::BCOMPRESSW; 6636 case Intrinsic::riscv_bdecompress: 6637 return RISCVISD::BDECOMPRESSW; 6638 case Intrinsic::riscv_bfp: 6639 return RISCVISD::BFPW; 6640 case Intrinsic::riscv_fsl: 6641 return RISCVISD::FSLW; 6642 case Intrinsic::riscv_fsr: 6643 return RISCVISD::FSRW; 6644 } 6645 } 6646 6647 // Converts the given intrinsic to a i64 operation with any extension. 6648 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6649 unsigned IntNo) { 6650 SDLoc DL(N); 6651 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6652 // Deal with the Instruction Operands 6653 SmallVector<SDValue, 3> NewOps; 6654 for (SDValue Op : drop_begin(N->ops())) 6655 // Promote the operand to i64 type 6656 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6657 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6658 // ReplaceNodeResults requires we maintain the same type for the return value. 6659 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6660 } 6661 6662 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6663 // form of the given Opcode. 6664 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6665 switch (Opcode) { 6666 default: 6667 llvm_unreachable("Unexpected opcode"); 6668 case ISD::SHL: 6669 return RISCVISD::SLLW; 6670 case ISD::SRA: 6671 return RISCVISD::SRAW; 6672 case ISD::SRL: 6673 return RISCVISD::SRLW; 6674 case ISD::SDIV: 6675 return RISCVISD::DIVW; 6676 case ISD::UDIV: 6677 return RISCVISD::DIVUW; 6678 case ISD::UREM: 6679 return RISCVISD::REMUW; 6680 case ISD::ROTL: 6681 return RISCVISD::ROLW; 6682 case ISD::ROTR: 6683 return RISCVISD::RORW; 6684 } 6685 } 6686 6687 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6688 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6689 // otherwise be promoted to i64, making it difficult to select the 6690 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6691 // type i8/i16/i32 is lost. 6692 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6693 unsigned ExtOpc = ISD::ANY_EXTEND) { 6694 SDLoc DL(N); 6695 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6696 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6697 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6698 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6699 // ReplaceNodeResults requires we maintain the same type for the return value. 6700 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6701 } 6702 6703 // Converts the given 32-bit operation to a i64 operation with signed extension 6704 // semantic to reduce the signed extension instructions. 6705 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6706 SDLoc DL(N); 6707 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6708 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6709 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6710 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6711 DAG.getValueType(MVT::i32)); 6712 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6713 } 6714 6715 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6716 SmallVectorImpl<SDValue> &Results, 6717 SelectionDAG &DAG) const { 6718 SDLoc DL(N); 6719 switch (N->getOpcode()) { 6720 default: 6721 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6722 case ISD::STRICT_FP_TO_SINT: 6723 case ISD::STRICT_FP_TO_UINT: 6724 case ISD::FP_TO_SINT: 6725 case ISD::FP_TO_UINT: { 6726 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6727 "Unexpected custom legalisation"); 6728 bool IsStrict = N->isStrictFPOpcode(); 6729 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6730 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6731 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6732 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6733 TargetLowering::TypeSoftenFloat) { 6734 if (!isTypeLegal(Op0.getValueType())) 6735 return; 6736 if (IsStrict) { 6737 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6738 : RISCVISD::STRICT_FCVT_WU_RV64; 6739 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6740 SDValue Res = DAG.getNode( 6741 Opc, DL, VTs, N->getOperand(0), Op0, 6742 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6743 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6744 Results.push_back(Res.getValue(1)); 6745 return; 6746 } 6747 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6748 SDValue Res = 6749 DAG.getNode(Opc, DL, MVT::i64, Op0, 6750 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6751 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6752 return; 6753 } 6754 // If the FP type needs to be softened, emit a library call using the 'si' 6755 // version. If we left it to default legalization we'd end up with 'di'. If 6756 // the FP type doesn't need to be softened just let generic type 6757 // legalization promote the result type. 6758 RTLIB::Libcall LC; 6759 if (IsSigned) 6760 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6761 else 6762 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6763 MakeLibCallOptions CallOptions; 6764 EVT OpVT = Op0.getValueType(); 6765 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6766 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6767 SDValue Result; 6768 std::tie(Result, Chain) = 6769 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6770 Results.push_back(Result); 6771 if (IsStrict) 6772 Results.push_back(Chain); 6773 break; 6774 } 6775 case ISD::READCYCLECOUNTER: { 6776 assert(!Subtarget.is64Bit() && 6777 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6778 6779 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6780 SDValue RCW = 6781 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6782 6783 Results.push_back( 6784 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6785 Results.push_back(RCW.getValue(2)); 6786 break; 6787 } 6788 case ISD::MUL: { 6789 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6790 unsigned XLen = Subtarget.getXLen(); 6791 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6792 if (Size > XLen) { 6793 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6794 SDValue LHS = N->getOperand(0); 6795 SDValue RHS = N->getOperand(1); 6796 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6797 6798 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6799 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6800 // We need exactly one side to be unsigned. 6801 if (LHSIsU == RHSIsU) 6802 return; 6803 6804 auto MakeMULPair = [&](SDValue S, SDValue U) { 6805 MVT XLenVT = Subtarget.getXLenVT(); 6806 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6807 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6808 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6809 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6810 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6811 }; 6812 6813 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6814 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6815 6816 // The other operand should be signed, but still prefer MULH when 6817 // possible. 6818 if (RHSIsU && LHSIsS && !RHSIsS) 6819 Results.push_back(MakeMULPair(LHS, RHS)); 6820 else if (LHSIsU && RHSIsS && !LHSIsS) 6821 Results.push_back(MakeMULPair(RHS, LHS)); 6822 6823 return; 6824 } 6825 LLVM_FALLTHROUGH; 6826 } 6827 case ISD::ADD: 6828 case ISD::SUB: 6829 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6830 "Unexpected custom legalisation"); 6831 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6832 break; 6833 case ISD::SHL: 6834 case ISD::SRA: 6835 case ISD::SRL: 6836 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6837 "Unexpected custom legalisation"); 6838 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6839 // If we can use a BSET instruction, allow default promotion to apply. 6840 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6841 isOneConstant(N->getOperand(0))) 6842 break; 6843 Results.push_back(customLegalizeToWOp(N, DAG)); 6844 break; 6845 } 6846 6847 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6848 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6849 // shift amount. 6850 if (N->getOpcode() == ISD::SHL) { 6851 SDLoc DL(N); 6852 SDValue NewOp0 = 6853 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6854 SDValue NewOp1 = 6855 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6856 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6857 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6858 DAG.getValueType(MVT::i32)); 6859 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6860 } 6861 6862 break; 6863 case ISD::ROTL: 6864 case ISD::ROTR: 6865 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6866 "Unexpected custom legalisation"); 6867 Results.push_back(customLegalizeToWOp(N, DAG)); 6868 break; 6869 case ISD::CTTZ: 6870 case ISD::CTTZ_ZERO_UNDEF: 6871 case ISD::CTLZ: 6872 case ISD::CTLZ_ZERO_UNDEF: { 6873 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6874 "Unexpected custom legalisation"); 6875 6876 SDValue NewOp0 = 6877 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6878 bool IsCTZ = 6879 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6880 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6881 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6882 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6883 return; 6884 } 6885 case ISD::SDIV: 6886 case ISD::UDIV: 6887 case ISD::UREM: { 6888 MVT VT = N->getSimpleValueType(0); 6889 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6890 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6891 "Unexpected custom legalisation"); 6892 // Don't promote division/remainder by constant since we should expand those 6893 // to multiply by magic constant. 6894 // FIXME: What if the expansion is disabled for minsize. 6895 if (N->getOperand(1).getOpcode() == ISD::Constant) 6896 return; 6897 6898 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6899 // the upper 32 bits. For other types we need to sign or zero extend 6900 // based on the opcode. 6901 unsigned ExtOpc = ISD::ANY_EXTEND; 6902 if (VT != MVT::i32) 6903 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6904 : ISD::ZERO_EXTEND; 6905 6906 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6907 break; 6908 } 6909 case ISD::UADDO: 6910 case ISD::USUBO: { 6911 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6912 "Unexpected custom legalisation"); 6913 bool IsAdd = N->getOpcode() == ISD::UADDO; 6914 // Create an ADDW or SUBW. 6915 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6916 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6917 SDValue Res = 6918 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6919 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6920 DAG.getValueType(MVT::i32)); 6921 6922 SDValue Overflow; 6923 if (IsAdd && isOneConstant(RHS)) { 6924 // Special case uaddo X, 1 overflowed if the addition result is 0. 6925 // The general case (X + C) < C is not necessarily beneficial. Although we 6926 // reduce the live range of X, we may introduce the materialization of 6927 // constant C, especially when the setcc result is used by branch. We have 6928 // no compare with constant and branch instructions. 6929 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6930 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6931 } else { 6932 // Sign extend the LHS and perform an unsigned compare with the ADDW 6933 // result. Since the inputs are sign extended from i32, this is equivalent 6934 // to comparing the lower 32 bits. 6935 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6936 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6937 IsAdd ? ISD::SETULT : ISD::SETUGT); 6938 } 6939 6940 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6941 Results.push_back(Overflow); 6942 return; 6943 } 6944 case ISD::UADDSAT: 6945 case ISD::USUBSAT: { 6946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6947 "Unexpected custom legalisation"); 6948 if (Subtarget.hasStdExtZbb()) { 6949 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6950 // sign extend allows overflow of the lower 32 bits to be detected on 6951 // the promoted size. 6952 SDValue LHS = 6953 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6954 SDValue RHS = 6955 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6956 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6957 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6958 return; 6959 } 6960 6961 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6962 // promotion for UADDO/USUBO. 6963 Results.push_back(expandAddSubSat(N, DAG)); 6964 return; 6965 } 6966 case ISD::ABS: { 6967 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6968 "Unexpected custom legalisation"); 6969 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6970 6971 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6972 6973 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6974 6975 // Freeze the source so we can increase it's use count. 6976 Src = DAG.getFreeze(Src); 6977 6978 // Copy sign bit to all bits using the sraiw pattern. 6979 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6980 DAG.getValueType(MVT::i32)); 6981 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6982 DAG.getConstant(31, DL, MVT::i64)); 6983 6984 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6985 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6986 6987 // NOTE: The result is only required to be anyextended, but sext is 6988 // consistent with type legalization of sub. 6989 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6990 DAG.getValueType(MVT::i32)); 6991 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6992 return; 6993 } 6994 case ISD::BITCAST: { 6995 EVT VT = N->getValueType(0); 6996 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6997 SDValue Op0 = N->getOperand(0); 6998 EVT Op0VT = Op0.getValueType(); 6999 MVT XLenVT = Subtarget.getXLenVT(); 7000 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7001 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7002 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7003 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7004 Subtarget.hasStdExtF()) { 7005 SDValue FPConv = 7006 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7007 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7008 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7009 isTypeLegal(Op0VT)) { 7010 // Custom-legalize bitcasts from fixed-length vector types to illegal 7011 // scalar types in order to improve codegen. Bitcast the vector to a 7012 // one-element vector type whose element type is the same as the result 7013 // type, and extract the first element. 7014 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7015 if (isTypeLegal(BVT)) { 7016 SDValue BVec = DAG.getBitcast(BVT, Op0); 7017 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7018 DAG.getConstant(0, DL, XLenVT))); 7019 } 7020 } 7021 break; 7022 } 7023 case RISCVISD::GREV: 7024 case RISCVISD::GORC: 7025 case RISCVISD::SHFL: { 7026 MVT VT = N->getSimpleValueType(0); 7027 MVT XLenVT = Subtarget.getXLenVT(); 7028 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7029 "Unexpected custom legalisation"); 7030 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7031 assert((Subtarget.hasStdExtZbp() || 7032 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7033 N->getConstantOperandVal(1) == 7)) && 7034 "Unexpected extension"); 7035 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7036 SDValue NewOp1 = 7037 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7038 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7039 // ReplaceNodeResults requires we maintain the same type for the return 7040 // value. 7041 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7042 break; 7043 } 7044 case ISD::BSWAP: 7045 case ISD::BITREVERSE: { 7046 MVT VT = N->getSimpleValueType(0); 7047 MVT XLenVT = Subtarget.getXLenVT(); 7048 assert((VT == MVT::i8 || VT == MVT::i16 || 7049 (VT == MVT::i32 && Subtarget.is64Bit())) && 7050 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7051 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7052 unsigned Imm = VT.getSizeInBits() - 1; 7053 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7054 if (N->getOpcode() == ISD::BSWAP) 7055 Imm &= ~0x7U; 7056 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7057 DAG.getConstant(Imm, DL, XLenVT)); 7058 // ReplaceNodeResults requires we maintain the same type for the return 7059 // value. 7060 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7061 break; 7062 } 7063 case ISD::FSHL: 7064 case ISD::FSHR: { 7065 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7066 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7067 SDValue NewOp0 = 7068 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7069 SDValue NewOp1 = 7070 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7071 SDValue NewShAmt = 7072 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7073 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7074 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7075 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7076 DAG.getConstant(0x1f, DL, MVT::i64)); 7077 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7078 // instruction use different orders. fshl will return its first operand for 7079 // shift of zero, fshr will return its second operand. fsl and fsr both 7080 // return rs1 so the ISD nodes need to have different operand orders. 7081 // Shift amount is in rs2. 7082 unsigned Opc = RISCVISD::FSLW; 7083 if (N->getOpcode() == ISD::FSHR) { 7084 std::swap(NewOp0, NewOp1); 7085 Opc = RISCVISD::FSRW; 7086 } 7087 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7088 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7089 break; 7090 } 7091 case ISD::EXTRACT_VECTOR_ELT: { 7092 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7093 // type is illegal (currently only vXi64 RV32). 7094 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7095 // transferred to the destination register. We issue two of these from the 7096 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7097 // first element. 7098 SDValue Vec = N->getOperand(0); 7099 SDValue Idx = N->getOperand(1); 7100 7101 // The vector type hasn't been legalized yet so we can't issue target 7102 // specific nodes if it needs legalization. 7103 // FIXME: We would manually legalize if it's important. 7104 if (!isTypeLegal(Vec.getValueType())) 7105 return; 7106 7107 MVT VecVT = Vec.getSimpleValueType(); 7108 7109 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7110 VecVT.getVectorElementType() == MVT::i64 && 7111 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7112 7113 // If this is a fixed vector, we need to convert it to a scalable vector. 7114 MVT ContainerVT = VecVT; 7115 if (VecVT.isFixedLengthVector()) { 7116 ContainerVT = getContainerForFixedLengthVector(VecVT); 7117 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7118 } 7119 7120 MVT XLenVT = Subtarget.getXLenVT(); 7121 7122 // Use a VL of 1 to avoid processing more elements than we need. 7123 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7124 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7125 7126 // Unless the index is known to be 0, we must slide the vector down to get 7127 // the desired element into index 0. 7128 if (!isNullConstant(Idx)) { 7129 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7130 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7131 } 7132 7133 // Extract the lower XLEN bits of the correct vector element. 7134 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7135 7136 // To extract the upper XLEN bits of the vector element, shift the first 7137 // element right by 32 bits and re-extract the lower XLEN bits. 7138 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7139 DAG.getUNDEF(ContainerVT), 7140 DAG.getConstant(32, DL, XLenVT), VL); 7141 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7142 ThirtyTwoV, Mask, VL); 7143 7144 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7145 7146 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7147 break; 7148 } 7149 case ISD::INTRINSIC_WO_CHAIN: { 7150 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7151 switch (IntNo) { 7152 default: 7153 llvm_unreachable( 7154 "Don't know how to custom type legalize this intrinsic!"); 7155 case Intrinsic::riscv_grev: 7156 case Intrinsic::riscv_gorc: { 7157 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7158 "Unexpected custom legalisation"); 7159 SDValue NewOp1 = 7160 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7161 SDValue NewOp2 = 7162 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7163 unsigned Opc = 7164 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7165 // If the control is a constant, promote the node by clearing any extra 7166 // bits bits in the control. isel will form greviw/gorciw if the result is 7167 // sign extended. 7168 if (isa<ConstantSDNode>(NewOp2)) { 7169 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7170 DAG.getConstant(0x1f, DL, MVT::i64)); 7171 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7172 } 7173 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7174 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7175 break; 7176 } 7177 case Intrinsic::riscv_bcompress: 7178 case Intrinsic::riscv_bdecompress: 7179 case Intrinsic::riscv_bfp: 7180 case Intrinsic::riscv_fsl: 7181 case Intrinsic::riscv_fsr: { 7182 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7183 "Unexpected custom legalisation"); 7184 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7185 break; 7186 } 7187 case Intrinsic::riscv_orc_b: { 7188 // Lower to the GORCI encoding for orc.b with the operand extended. 7189 SDValue NewOp = 7190 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7191 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7192 DAG.getConstant(7, DL, MVT::i64)); 7193 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7194 return; 7195 } 7196 case Intrinsic::riscv_shfl: 7197 case Intrinsic::riscv_unshfl: { 7198 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7199 "Unexpected custom legalisation"); 7200 SDValue NewOp1 = 7201 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7202 SDValue NewOp2 = 7203 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7204 unsigned Opc = 7205 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7206 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7207 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7208 // will be shuffled the same way as the lower 32 bit half, but the two 7209 // halves won't cross. 7210 if (isa<ConstantSDNode>(NewOp2)) { 7211 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7212 DAG.getConstant(0xf, DL, MVT::i64)); 7213 Opc = 7214 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7215 } 7216 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7217 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7218 break; 7219 } 7220 case Intrinsic::riscv_vmv_x_s: { 7221 EVT VT = N->getValueType(0); 7222 MVT XLenVT = Subtarget.getXLenVT(); 7223 if (VT.bitsLT(XLenVT)) { 7224 // Simple case just extract using vmv.x.s and truncate. 7225 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7226 Subtarget.getXLenVT(), N->getOperand(1)); 7227 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7228 return; 7229 } 7230 7231 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7232 "Unexpected custom legalization"); 7233 7234 // We need to do the move in two steps. 7235 SDValue Vec = N->getOperand(1); 7236 MVT VecVT = Vec.getSimpleValueType(); 7237 7238 // First extract the lower XLEN bits of the element. 7239 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7240 7241 // To extract the upper XLEN bits of the vector element, shift the first 7242 // element right by 32 bits and re-extract the lower XLEN bits. 7243 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7244 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7245 7246 SDValue ThirtyTwoV = 7247 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7248 DAG.getConstant(32, DL, XLenVT), VL); 7249 SDValue LShr32 = 7250 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7251 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7252 7253 Results.push_back( 7254 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7255 break; 7256 } 7257 } 7258 break; 7259 } 7260 case ISD::VECREDUCE_ADD: 7261 case ISD::VECREDUCE_AND: 7262 case ISD::VECREDUCE_OR: 7263 case ISD::VECREDUCE_XOR: 7264 case ISD::VECREDUCE_SMAX: 7265 case ISD::VECREDUCE_UMAX: 7266 case ISD::VECREDUCE_SMIN: 7267 case ISD::VECREDUCE_UMIN: 7268 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7269 Results.push_back(V); 7270 break; 7271 case ISD::VP_REDUCE_ADD: 7272 case ISD::VP_REDUCE_AND: 7273 case ISD::VP_REDUCE_OR: 7274 case ISD::VP_REDUCE_XOR: 7275 case ISD::VP_REDUCE_SMAX: 7276 case ISD::VP_REDUCE_UMAX: 7277 case ISD::VP_REDUCE_SMIN: 7278 case ISD::VP_REDUCE_UMIN: 7279 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7280 Results.push_back(V); 7281 break; 7282 case ISD::FLT_ROUNDS_: { 7283 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7284 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7285 Results.push_back(Res.getValue(0)); 7286 Results.push_back(Res.getValue(1)); 7287 break; 7288 } 7289 } 7290 } 7291 7292 // A structure to hold one of the bit-manipulation patterns below. Together, a 7293 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7294 // (or (and (shl x, 1), 0xAAAAAAAA), 7295 // (and (srl x, 1), 0x55555555)) 7296 struct RISCVBitmanipPat { 7297 SDValue Op; 7298 unsigned ShAmt; 7299 bool IsSHL; 7300 7301 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7302 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7303 } 7304 }; 7305 7306 // Matches patterns of the form 7307 // (and (shl x, C2), (C1 << C2)) 7308 // (and (srl x, C2), C1) 7309 // (shl (and x, C1), C2) 7310 // (srl (and x, (C1 << C2)), C2) 7311 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7312 // The expected masks for each shift amount are specified in BitmanipMasks where 7313 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7314 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7315 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7316 // XLen is 64. 7317 static Optional<RISCVBitmanipPat> 7318 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7319 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7320 "Unexpected number of masks"); 7321 Optional<uint64_t> Mask; 7322 // Optionally consume a mask around the shift operation. 7323 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7324 Mask = Op.getConstantOperandVal(1); 7325 Op = Op.getOperand(0); 7326 } 7327 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7328 return None; 7329 bool IsSHL = Op.getOpcode() == ISD::SHL; 7330 7331 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7332 return None; 7333 uint64_t ShAmt = Op.getConstantOperandVal(1); 7334 7335 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7336 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7337 return None; 7338 // If we don't have enough masks for 64 bit, then we must be trying to 7339 // match SHFL so we're only allowed to shift 1/4 of the width. 7340 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7341 return None; 7342 7343 SDValue Src = Op.getOperand(0); 7344 7345 // The expected mask is shifted left when the AND is found around SHL 7346 // patterns. 7347 // ((x >> 1) & 0x55555555) 7348 // ((x << 1) & 0xAAAAAAAA) 7349 bool SHLExpMask = IsSHL; 7350 7351 if (!Mask) { 7352 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7353 // the mask is all ones: consume that now. 7354 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7355 Mask = Src.getConstantOperandVal(1); 7356 Src = Src.getOperand(0); 7357 // The expected mask is now in fact shifted left for SRL, so reverse the 7358 // decision. 7359 // ((x & 0xAAAAAAAA) >> 1) 7360 // ((x & 0x55555555) << 1) 7361 SHLExpMask = !SHLExpMask; 7362 } else { 7363 // Use a default shifted mask of all-ones if there's no AND, truncated 7364 // down to the expected width. This simplifies the logic later on. 7365 Mask = maskTrailingOnes<uint64_t>(Width); 7366 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7367 } 7368 } 7369 7370 unsigned MaskIdx = Log2_32(ShAmt); 7371 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7372 7373 if (SHLExpMask) 7374 ExpMask <<= ShAmt; 7375 7376 if (Mask != ExpMask) 7377 return None; 7378 7379 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7380 } 7381 7382 // Matches any of the following bit-manipulation patterns: 7383 // (and (shl x, 1), (0x55555555 << 1)) 7384 // (and (srl x, 1), 0x55555555) 7385 // (shl (and x, 0x55555555), 1) 7386 // (srl (and x, (0x55555555 << 1)), 1) 7387 // where the shift amount and mask may vary thus: 7388 // [1] = 0x55555555 / 0xAAAAAAAA 7389 // [2] = 0x33333333 / 0xCCCCCCCC 7390 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7391 // [8] = 0x00FF00FF / 0xFF00FF00 7392 // [16] = 0x0000FFFF / 0xFFFFFFFF 7393 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7394 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7395 // These are the unshifted masks which we use to match bit-manipulation 7396 // patterns. They may be shifted left in certain circumstances. 7397 static const uint64_t BitmanipMasks[] = { 7398 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7399 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7400 7401 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7402 } 7403 7404 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7405 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7406 auto BinOpToRVVReduce = [](unsigned Opc) { 7407 switch (Opc) { 7408 default: 7409 llvm_unreachable("Unhandled binary to transfrom reduction"); 7410 case ISD::ADD: 7411 return RISCVISD::VECREDUCE_ADD_VL; 7412 case ISD::UMAX: 7413 return RISCVISD::VECREDUCE_UMAX_VL; 7414 case ISD::SMAX: 7415 return RISCVISD::VECREDUCE_SMAX_VL; 7416 case ISD::UMIN: 7417 return RISCVISD::VECREDUCE_UMIN_VL; 7418 case ISD::SMIN: 7419 return RISCVISD::VECREDUCE_SMIN_VL; 7420 case ISD::AND: 7421 return RISCVISD::VECREDUCE_AND_VL; 7422 case ISD::OR: 7423 return RISCVISD::VECREDUCE_OR_VL; 7424 case ISD::XOR: 7425 return RISCVISD::VECREDUCE_XOR_VL; 7426 case ISD::FADD: 7427 return RISCVISD::VECREDUCE_FADD_VL; 7428 case ISD::FMAXNUM: 7429 return RISCVISD::VECREDUCE_FMAX_VL; 7430 case ISD::FMINNUM: 7431 return RISCVISD::VECREDUCE_FMIN_VL; 7432 } 7433 }; 7434 7435 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7436 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7437 isNullConstant(V.getOperand(1)) && 7438 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7439 }; 7440 7441 unsigned Opc = N->getOpcode(); 7442 unsigned ReduceIdx; 7443 if (IsReduction(N->getOperand(0), Opc)) 7444 ReduceIdx = 0; 7445 else if (IsReduction(N->getOperand(1), Opc)) 7446 ReduceIdx = 1; 7447 else 7448 return SDValue(); 7449 7450 // Skip if FADD disallows reassociation but the combiner needs. 7451 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7452 return SDValue(); 7453 7454 SDValue Extract = N->getOperand(ReduceIdx); 7455 SDValue Reduce = Extract.getOperand(0); 7456 if (!Reduce.hasOneUse()) 7457 return SDValue(); 7458 7459 SDValue ScalarV = Reduce.getOperand(2); 7460 7461 // Make sure that ScalarV is a splat with VL=1. 7462 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7463 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7464 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7465 return SDValue(); 7466 7467 if (!isOneConstant(ScalarV.getOperand(2))) 7468 return SDValue(); 7469 7470 // TODO: Deal with value other than neutral element. 7471 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7472 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7473 isNullFPConstant(V)) 7474 return true; 7475 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7476 N->getFlags()) == V; 7477 }; 7478 7479 // Check the scalar of ScalarV is neutral element 7480 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7481 return SDValue(); 7482 7483 if (!ScalarV.hasOneUse()) 7484 return SDValue(); 7485 7486 EVT SplatVT = ScalarV.getValueType(); 7487 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7488 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7489 if (SplatVT.isInteger()) { 7490 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7491 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7492 SplatOpc = RISCVISD::VMV_S_X_VL; 7493 else 7494 SplatOpc = RISCVISD::VMV_V_X_VL; 7495 } 7496 7497 SDValue NewScalarV = 7498 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7499 ScalarV.getOperand(2)); 7500 SDValue NewReduce = 7501 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7502 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7503 Reduce.getOperand(3), Reduce.getOperand(4)); 7504 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7505 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7506 } 7507 7508 // Match the following pattern as a GREVI(W) operation 7509 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7510 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7511 const RISCVSubtarget &Subtarget) { 7512 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7513 EVT VT = Op.getValueType(); 7514 7515 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7516 auto LHS = matchGREVIPat(Op.getOperand(0)); 7517 auto RHS = matchGREVIPat(Op.getOperand(1)); 7518 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7519 SDLoc DL(Op); 7520 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7521 DAG.getConstant(LHS->ShAmt, DL, VT)); 7522 } 7523 } 7524 return SDValue(); 7525 } 7526 7527 // Matches any the following pattern as a GORCI(W) operation 7528 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7529 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7530 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7531 // Note that with the variant of 3., 7532 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7533 // the inner pattern will first be matched as GREVI and then the outer 7534 // pattern will be matched to GORC via the first rule above. 7535 // 4. (or (rotl/rotr x, bitwidth/2), x) 7536 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7537 const RISCVSubtarget &Subtarget) { 7538 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7539 EVT VT = Op.getValueType(); 7540 7541 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7542 SDLoc DL(Op); 7543 SDValue Op0 = Op.getOperand(0); 7544 SDValue Op1 = Op.getOperand(1); 7545 7546 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7547 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7548 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7549 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7550 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7551 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7552 if ((Reverse.getOpcode() == ISD::ROTL || 7553 Reverse.getOpcode() == ISD::ROTR) && 7554 Reverse.getOperand(0) == X && 7555 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7556 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7557 if (RotAmt == (VT.getSizeInBits() / 2)) 7558 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7559 DAG.getConstant(RotAmt, DL, VT)); 7560 } 7561 return SDValue(); 7562 }; 7563 7564 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7565 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7566 return V; 7567 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7568 return V; 7569 7570 // OR is commutable so canonicalize its OR operand to the left 7571 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7572 std::swap(Op0, Op1); 7573 if (Op0.getOpcode() != ISD::OR) 7574 return SDValue(); 7575 SDValue OrOp0 = Op0.getOperand(0); 7576 SDValue OrOp1 = Op0.getOperand(1); 7577 auto LHS = matchGREVIPat(OrOp0); 7578 // OR is commutable so swap the operands and try again: x might have been 7579 // on the left 7580 if (!LHS) { 7581 std::swap(OrOp0, OrOp1); 7582 LHS = matchGREVIPat(OrOp0); 7583 } 7584 auto RHS = matchGREVIPat(Op1); 7585 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7586 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7587 DAG.getConstant(LHS->ShAmt, DL, VT)); 7588 } 7589 } 7590 return SDValue(); 7591 } 7592 7593 // Matches any of the following bit-manipulation patterns: 7594 // (and (shl x, 1), (0x22222222 << 1)) 7595 // (and (srl x, 1), 0x22222222) 7596 // (shl (and x, 0x22222222), 1) 7597 // (srl (and x, (0x22222222 << 1)), 1) 7598 // where the shift amount and mask may vary thus: 7599 // [1] = 0x22222222 / 0x44444444 7600 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7601 // [4] = 0x00F000F0 / 0x0F000F00 7602 // [8] = 0x0000FF00 / 0x00FF0000 7603 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7604 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7605 // These are the unshifted masks which we use to match bit-manipulation 7606 // patterns. They may be shifted left in certain circumstances. 7607 static const uint64_t BitmanipMasks[] = { 7608 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7609 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7610 7611 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7612 } 7613 7614 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7615 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7616 const RISCVSubtarget &Subtarget) { 7617 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7618 EVT VT = Op.getValueType(); 7619 7620 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7621 return SDValue(); 7622 7623 SDValue Op0 = Op.getOperand(0); 7624 SDValue Op1 = Op.getOperand(1); 7625 7626 // Or is commutable so canonicalize the second OR to the LHS. 7627 if (Op0.getOpcode() != ISD::OR) 7628 std::swap(Op0, Op1); 7629 if (Op0.getOpcode() != ISD::OR) 7630 return SDValue(); 7631 7632 // We found an inner OR, so our operands are the operands of the inner OR 7633 // and the other operand of the outer OR. 7634 SDValue A = Op0.getOperand(0); 7635 SDValue B = Op0.getOperand(1); 7636 SDValue C = Op1; 7637 7638 auto Match1 = matchSHFLPat(A); 7639 auto Match2 = matchSHFLPat(B); 7640 7641 // If neither matched, we failed. 7642 if (!Match1 && !Match2) 7643 return SDValue(); 7644 7645 // We had at least one match. if one failed, try the remaining C operand. 7646 if (!Match1) { 7647 std::swap(A, C); 7648 Match1 = matchSHFLPat(A); 7649 if (!Match1) 7650 return SDValue(); 7651 } else if (!Match2) { 7652 std::swap(B, C); 7653 Match2 = matchSHFLPat(B); 7654 if (!Match2) 7655 return SDValue(); 7656 } 7657 assert(Match1 && Match2); 7658 7659 // Make sure our matches pair up. 7660 if (!Match1->formsPairWith(*Match2)) 7661 return SDValue(); 7662 7663 // All the remains is to make sure C is an AND with the same input, that masks 7664 // out the bits that are being shuffled. 7665 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7666 C.getOperand(0) != Match1->Op) 7667 return SDValue(); 7668 7669 uint64_t Mask = C.getConstantOperandVal(1); 7670 7671 static const uint64_t BitmanipMasks[] = { 7672 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7673 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7674 }; 7675 7676 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7677 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7678 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7679 7680 if (Mask != ExpMask) 7681 return SDValue(); 7682 7683 SDLoc DL(Op); 7684 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7685 DAG.getConstant(Match1->ShAmt, DL, VT)); 7686 } 7687 7688 // Optimize (add (shl x, c0), (shl y, c1)) -> 7689 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7690 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7691 const RISCVSubtarget &Subtarget) { 7692 // Perform this optimization only in the zba extension. 7693 if (!Subtarget.hasStdExtZba()) 7694 return SDValue(); 7695 7696 // Skip for vector types and larger types. 7697 EVT VT = N->getValueType(0); 7698 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7699 return SDValue(); 7700 7701 // The two operand nodes must be SHL and have no other use. 7702 SDValue N0 = N->getOperand(0); 7703 SDValue N1 = N->getOperand(1); 7704 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7705 !N0->hasOneUse() || !N1->hasOneUse()) 7706 return SDValue(); 7707 7708 // Check c0 and c1. 7709 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7710 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7711 if (!N0C || !N1C) 7712 return SDValue(); 7713 int64_t C0 = N0C->getSExtValue(); 7714 int64_t C1 = N1C->getSExtValue(); 7715 if (C0 <= 0 || C1 <= 0) 7716 return SDValue(); 7717 7718 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7719 int64_t Bits = std::min(C0, C1); 7720 int64_t Diff = std::abs(C0 - C1); 7721 if (Diff != 1 && Diff != 2 && Diff != 3) 7722 return SDValue(); 7723 7724 // Build nodes. 7725 SDLoc DL(N); 7726 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7727 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7728 SDValue NA0 = 7729 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7730 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7731 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7732 } 7733 7734 // Combine 7735 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7736 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7737 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7738 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7739 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7740 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7741 // The grev patterns represents BSWAP. 7742 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7743 // off the grev. 7744 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7745 const RISCVSubtarget &Subtarget) { 7746 bool IsWInstruction = 7747 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7748 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7749 IsWInstruction) && 7750 "Unexpected opcode!"); 7751 SDValue Src = N->getOperand(0); 7752 EVT VT = N->getValueType(0); 7753 SDLoc DL(N); 7754 7755 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7756 return SDValue(); 7757 7758 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7759 !isa<ConstantSDNode>(Src.getOperand(1))) 7760 return SDValue(); 7761 7762 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7763 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7764 7765 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7766 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7767 unsigned ShAmt1 = N->getConstantOperandVal(1); 7768 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7769 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7770 return SDValue(); 7771 7772 Src = Src.getOperand(0); 7773 7774 // Toggle bit the MSB of the shift. 7775 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7776 if (CombinedShAmt == 0) 7777 return Src; 7778 7779 SDValue Res = DAG.getNode( 7780 RISCVISD::GREV, DL, VT, Src, 7781 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7782 if (!IsWInstruction) 7783 return Res; 7784 7785 // Sign extend the result to match the behavior of the rotate. This will be 7786 // selected to GREVIW in isel. 7787 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7788 DAG.getValueType(MVT::i32)); 7789 } 7790 7791 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7792 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7793 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7794 // not undo itself, but they are redundant. 7795 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7796 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7797 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7798 SDValue Src = N->getOperand(0); 7799 7800 if (Src.getOpcode() != N->getOpcode()) 7801 return SDValue(); 7802 7803 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7804 !isa<ConstantSDNode>(Src.getOperand(1))) 7805 return SDValue(); 7806 7807 unsigned ShAmt1 = N->getConstantOperandVal(1); 7808 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7809 Src = Src.getOperand(0); 7810 7811 unsigned CombinedShAmt; 7812 if (IsGORC) 7813 CombinedShAmt = ShAmt1 | ShAmt2; 7814 else 7815 CombinedShAmt = ShAmt1 ^ ShAmt2; 7816 7817 if (CombinedShAmt == 0) 7818 return Src; 7819 7820 SDLoc DL(N); 7821 return DAG.getNode( 7822 N->getOpcode(), DL, N->getValueType(0), Src, 7823 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7824 } 7825 7826 // Combine a constant select operand into its use: 7827 // 7828 // (and (select cond, -1, c), x) 7829 // -> (select cond, x, (and x, c)) [AllOnes=1] 7830 // (or (select cond, 0, c), x) 7831 // -> (select cond, x, (or x, c)) [AllOnes=0] 7832 // (xor (select cond, 0, c), x) 7833 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7834 // (add (select cond, 0, c), x) 7835 // -> (select cond, x, (add x, c)) [AllOnes=0] 7836 // (sub x, (select cond, 0, c)) 7837 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7838 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7839 SelectionDAG &DAG, bool AllOnes) { 7840 EVT VT = N->getValueType(0); 7841 7842 // Skip vectors. 7843 if (VT.isVector()) 7844 return SDValue(); 7845 7846 if ((Slct.getOpcode() != ISD::SELECT && 7847 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7848 !Slct.hasOneUse()) 7849 return SDValue(); 7850 7851 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7852 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7853 }; 7854 7855 bool SwapSelectOps; 7856 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7857 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7858 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7859 SDValue NonConstantVal; 7860 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7861 SwapSelectOps = false; 7862 NonConstantVal = FalseVal; 7863 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7864 SwapSelectOps = true; 7865 NonConstantVal = TrueVal; 7866 } else 7867 return SDValue(); 7868 7869 // Slct is now know to be the desired identity constant when CC is true. 7870 TrueVal = OtherOp; 7871 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7872 // Unless SwapSelectOps says the condition should be false. 7873 if (SwapSelectOps) 7874 std::swap(TrueVal, FalseVal); 7875 7876 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7877 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7878 {Slct.getOperand(0), Slct.getOperand(1), 7879 Slct.getOperand(2), TrueVal, FalseVal}); 7880 7881 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7882 {Slct.getOperand(0), TrueVal, FalseVal}); 7883 } 7884 7885 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7886 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7887 bool AllOnes) { 7888 SDValue N0 = N->getOperand(0); 7889 SDValue N1 = N->getOperand(1); 7890 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7891 return Result; 7892 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7893 return Result; 7894 return SDValue(); 7895 } 7896 7897 // Transform (add (mul x, c0), c1) -> 7898 // (add (mul (add x, c1/c0), c0), c1%c0). 7899 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7900 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7901 // to an infinite loop in DAGCombine if transformed. 7902 // Or transform (add (mul x, c0), c1) -> 7903 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7904 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7905 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7906 // lead to an infinite loop in DAGCombine if transformed. 7907 // Or transform (add (mul x, c0), c1) -> 7908 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7909 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7910 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7911 // lead to an infinite loop in DAGCombine if transformed. 7912 // Or transform (add (mul x, c0), c1) -> 7913 // (mul (add x, c1/c0), c0). 7914 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7915 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7916 const RISCVSubtarget &Subtarget) { 7917 // Skip for vector types and larger types. 7918 EVT VT = N->getValueType(0); 7919 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7920 return SDValue(); 7921 // The first operand node must be a MUL and has no other use. 7922 SDValue N0 = N->getOperand(0); 7923 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7924 return SDValue(); 7925 // Check if c0 and c1 match above conditions. 7926 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7927 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7928 if (!N0C || !N1C) 7929 return SDValue(); 7930 // If N0C has multiple uses it's possible one of the cases in 7931 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7932 // in an infinite loop. 7933 if (!N0C->hasOneUse()) 7934 return SDValue(); 7935 int64_t C0 = N0C->getSExtValue(); 7936 int64_t C1 = N1C->getSExtValue(); 7937 int64_t CA, CB; 7938 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7939 return SDValue(); 7940 // Search for proper CA (non-zero) and CB that both are simm12. 7941 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7942 !isInt<12>(C0 * (C1 / C0))) { 7943 CA = C1 / C0; 7944 CB = C1 % C0; 7945 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7946 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7947 CA = C1 / C0 + 1; 7948 CB = C1 % C0 - C0; 7949 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7950 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7951 CA = C1 / C0 - 1; 7952 CB = C1 % C0 + C0; 7953 } else 7954 return SDValue(); 7955 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7956 SDLoc DL(N); 7957 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7958 DAG.getConstant(CA, DL, VT)); 7959 SDValue New1 = 7960 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7961 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7962 } 7963 7964 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7965 const RISCVSubtarget &Subtarget) { 7966 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7967 return V; 7968 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7969 return V; 7970 if (SDValue V = combineBinOpToReduce(N, DAG)) 7971 return V; 7972 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7973 // (select lhs, rhs, cc, x, (add x, y)) 7974 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7975 } 7976 7977 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7978 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7979 // (select lhs, rhs, cc, x, (sub x, y)) 7980 SDValue N0 = N->getOperand(0); 7981 SDValue N1 = N->getOperand(1); 7982 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7983 } 7984 7985 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7986 if (SDValue V = combineBinOpToReduce(N, DAG)) 7987 return V; 7988 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7989 // (select lhs, rhs, cc, x, (and x, y)) 7990 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7991 } 7992 7993 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7994 const RISCVSubtarget &Subtarget) { 7995 if (Subtarget.hasStdExtZbp()) { 7996 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7997 return GREV; 7998 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7999 return GORC; 8000 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8001 return SHFL; 8002 } 8003 8004 if (SDValue V = combineBinOpToReduce(N, DAG)) 8005 return V; 8006 // fold (or (select cond, 0, y), x) -> 8007 // (select cond, x, (or x, y)) 8008 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8009 } 8010 8011 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8012 SDValue N0 = N->getOperand(0); 8013 SDValue N1 = N->getOperand(1); 8014 8015 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8016 // NOTE: Assumes ROL being legal means ROLW is legal. 8017 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8018 if (N0.getOpcode() == RISCVISD::SLLW && 8019 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8020 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8021 SDLoc DL(N); 8022 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8023 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8024 } 8025 8026 if (SDValue V = combineBinOpToReduce(N, DAG)) 8027 return V; 8028 // fold (xor (select cond, 0, y), x) -> 8029 // (select cond, x, (xor x, y)) 8030 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8031 } 8032 8033 static SDValue 8034 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8035 const RISCVSubtarget &Subtarget) { 8036 SDValue Src = N->getOperand(0); 8037 EVT VT = N->getValueType(0); 8038 8039 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8040 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8041 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8042 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8043 Src.getOperand(0)); 8044 8045 // Fold (i64 (sext_inreg (abs X), i32)) -> 8046 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8047 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8048 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8049 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8050 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8051 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8052 // may get combined into an earlier operation so we need to use 8053 // ComputeNumSignBits. 8054 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8055 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8056 // we can't assume that X has 33 sign bits. We must check. 8057 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8058 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8059 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8060 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8061 SDLoc DL(N); 8062 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8063 SDValue Neg = 8064 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8065 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8066 DAG.getValueType(MVT::i32)); 8067 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8068 } 8069 8070 return SDValue(); 8071 } 8072 8073 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8074 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8075 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8076 bool Commute = false) { 8077 assert((N->getOpcode() == RISCVISD::ADD_VL || 8078 N->getOpcode() == RISCVISD::SUB_VL) && 8079 "Unexpected opcode"); 8080 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8081 SDValue Op0 = N->getOperand(0); 8082 SDValue Op1 = N->getOperand(1); 8083 if (Commute) 8084 std::swap(Op0, Op1); 8085 8086 MVT VT = N->getSimpleValueType(0); 8087 8088 // Determine the narrow size for a widening add/sub. 8089 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8090 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8091 VT.getVectorElementCount()); 8092 8093 SDValue Mask = N->getOperand(2); 8094 SDValue VL = N->getOperand(3); 8095 8096 SDLoc DL(N); 8097 8098 // If the RHS is a sext or zext, we can form a widening op. 8099 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8100 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8101 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8102 unsigned ExtOpc = Op1.getOpcode(); 8103 Op1 = Op1.getOperand(0); 8104 // Re-introduce narrower extends if needed. 8105 if (Op1.getValueType() != NarrowVT) 8106 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8107 8108 unsigned WOpc; 8109 if (ExtOpc == RISCVISD::VSEXT_VL) 8110 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8111 else 8112 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8113 8114 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8115 } 8116 8117 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8118 // sext/zext? 8119 8120 return SDValue(); 8121 } 8122 8123 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8124 // vwsub(u).vv/vx. 8125 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8126 SDValue Op0 = N->getOperand(0); 8127 SDValue Op1 = N->getOperand(1); 8128 SDValue Mask = N->getOperand(2); 8129 SDValue VL = N->getOperand(3); 8130 8131 MVT VT = N->getSimpleValueType(0); 8132 MVT NarrowVT = Op1.getSimpleValueType(); 8133 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8134 8135 unsigned VOpc; 8136 switch (N->getOpcode()) { 8137 default: llvm_unreachable("Unexpected opcode"); 8138 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8139 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8140 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8141 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8142 } 8143 8144 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8145 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8146 8147 SDLoc DL(N); 8148 8149 // If the LHS is a sext or zext, we can narrow this op to the same size as 8150 // the RHS. 8151 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8152 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8153 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8154 unsigned ExtOpc = Op0.getOpcode(); 8155 Op0 = Op0.getOperand(0); 8156 // Re-introduce narrower extends if needed. 8157 if (Op0.getValueType() != NarrowVT) 8158 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8159 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8160 } 8161 8162 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8163 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8164 8165 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8166 // to commute and use a vwadd(u).vx instead. 8167 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8168 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8169 Op0 = Op0.getOperand(1); 8170 8171 // See if have enough sign bits or zero bits in the scalar to use a 8172 // widening add/sub by splatting to smaller element size. 8173 unsigned EltBits = VT.getScalarSizeInBits(); 8174 unsigned ScalarBits = Op0.getValueSizeInBits(); 8175 // Make sure we're getting all element bits from the scalar register. 8176 // FIXME: Support implicit sign extension of vmv.v.x? 8177 if (ScalarBits < EltBits) 8178 return SDValue(); 8179 8180 if (IsSigned) { 8181 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8182 return SDValue(); 8183 } else { 8184 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8185 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8186 return SDValue(); 8187 } 8188 8189 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8190 DAG.getUNDEF(NarrowVT), Op0, VL); 8191 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8192 } 8193 8194 return SDValue(); 8195 } 8196 8197 // Try to form VWMUL, VWMULU or VWMULSU. 8198 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8199 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8200 bool Commute) { 8201 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8202 SDValue Op0 = N->getOperand(0); 8203 SDValue Op1 = N->getOperand(1); 8204 if (Commute) 8205 std::swap(Op0, Op1); 8206 8207 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8208 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8209 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8210 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8211 return SDValue(); 8212 8213 SDValue Mask = N->getOperand(2); 8214 SDValue VL = N->getOperand(3); 8215 8216 // Make sure the mask and VL match. 8217 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8218 return SDValue(); 8219 8220 MVT VT = N->getSimpleValueType(0); 8221 8222 // Determine the narrow size for a widening multiply. 8223 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8224 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8225 VT.getVectorElementCount()); 8226 8227 SDLoc DL(N); 8228 8229 // See if the other operand is the same opcode. 8230 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8231 if (!Op1.hasOneUse()) 8232 return SDValue(); 8233 8234 // Make sure the mask and VL match. 8235 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8236 return SDValue(); 8237 8238 Op1 = Op1.getOperand(0); 8239 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8240 // The operand is a splat of a scalar. 8241 8242 // The pasthru must be undef for tail agnostic 8243 if (!Op1.getOperand(0).isUndef()) 8244 return SDValue(); 8245 // The VL must be the same. 8246 if (Op1.getOperand(2) != VL) 8247 return SDValue(); 8248 8249 // Get the scalar value. 8250 Op1 = Op1.getOperand(1); 8251 8252 // See if have enough sign bits or zero bits in the scalar to use a 8253 // widening multiply by splatting to smaller element size. 8254 unsigned EltBits = VT.getScalarSizeInBits(); 8255 unsigned ScalarBits = Op1.getValueSizeInBits(); 8256 // Make sure we're getting all element bits from the scalar register. 8257 // FIXME: Support implicit sign extension of vmv.v.x? 8258 if (ScalarBits < EltBits) 8259 return SDValue(); 8260 8261 // If the LHS is a sign extend, try to use vwmul. 8262 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8263 // Can use vwmul. 8264 } else { 8265 // Otherwise try to use vwmulu or vwmulsu. 8266 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8267 if (DAG.MaskedValueIsZero(Op1, Mask)) 8268 IsVWMULSU = IsSignExt; 8269 else 8270 return SDValue(); 8271 } 8272 8273 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8274 DAG.getUNDEF(NarrowVT), Op1, VL); 8275 } else 8276 return SDValue(); 8277 8278 Op0 = Op0.getOperand(0); 8279 8280 // Re-introduce narrower extends if needed. 8281 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8282 if (Op0.getValueType() != NarrowVT) 8283 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8284 // vwmulsu requires second operand to be zero extended. 8285 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8286 if (Op1.getValueType() != NarrowVT) 8287 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8288 8289 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8290 if (!IsVWMULSU) 8291 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8292 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8293 } 8294 8295 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8296 switch (Op.getOpcode()) { 8297 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8298 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8299 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8300 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8301 case ISD::FROUND: return RISCVFPRndMode::RMM; 8302 } 8303 8304 return RISCVFPRndMode::Invalid; 8305 } 8306 8307 // Fold 8308 // (fp_to_int (froundeven X)) -> fcvt X, rne 8309 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8310 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8311 // (fp_to_int (fceil X)) -> fcvt X, rup 8312 // (fp_to_int (fround X)) -> fcvt X, rmm 8313 static SDValue performFP_TO_INTCombine(SDNode *N, 8314 TargetLowering::DAGCombinerInfo &DCI, 8315 const RISCVSubtarget &Subtarget) { 8316 SelectionDAG &DAG = DCI.DAG; 8317 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8318 MVT XLenVT = Subtarget.getXLenVT(); 8319 8320 // Only handle XLen or i32 types. Other types narrower than XLen will 8321 // eventually be legalized to XLenVT. 8322 EVT VT = N->getValueType(0); 8323 if (VT != MVT::i32 && VT != XLenVT) 8324 return SDValue(); 8325 8326 SDValue Src = N->getOperand(0); 8327 8328 // Ensure the FP type is also legal. 8329 if (!TLI.isTypeLegal(Src.getValueType())) 8330 return SDValue(); 8331 8332 // Don't do this for f16 with Zfhmin and not Zfh. 8333 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8334 return SDValue(); 8335 8336 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8337 if (FRM == RISCVFPRndMode::Invalid) 8338 return SDValue(); 8339 8340 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8341 8342 unsigned Opc; 8343 if (VT == XLenVT) 8344 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8345 else 8346 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8347 8348 SDLoc DL(N); 8349 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8350 DAG.getTargetConstant(FRM, DL, XLenVT)); 8351 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8352 } 8353 8354 // Fold 8355 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8356 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8357 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8358 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8359 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8360 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8361 TargetLowering::DAGCombinerInfo &DCI, 8362 const RISCVSubtarget &Subtarget) { 8363 SelectionDAG &DAG = DCI.DAG; 8364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8365 MVT XLenVT = Subtarget.getXLenVT(); 8366 8367 // Only handle XLen types. Other types narrower than XLen will eventually be 8368 // legalized to XLenVT. 8369 EVT DstVT = N->getValueType(0); 8370 if (DstVT != XLenVT) 8371 return SDValue(); 8372 8373 SDValue Src = N->getOperand(0); 8374 8375 // Ensure the FP type is also legal. 8376 if (!TLI.isTypeLegal(Src.getValueType())) 8377 return SDValue(); 8378 8379 // Don't do this for f16 with Zfhmin and not Zfh. 8380 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8381 return SDValue(); 8382 8383 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8384 8385 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8386 if (FRM == RISCVFPRndMode::Invalid) 8387 return SDValue(); 8388 8389 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8390 8391 unsigned Opc; 8392 if (SatVT == DstVT) 8393 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8394 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8395 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8396 else 8397 return SDValue(); 8398 // FIXME: Support other SatVTs by clamping before or after the conversion. 8399 8400 Src = Src.getOperand(0); 8401 8402 SDLoc DL(N); 8403 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8404 DAG.getTargetConstant(FRM, DL, XLenVT)); 8405 8406 // RISCV FP-to-int conversions saturate to the destination register size, but 8407 // don't produce 0 for nan. 8408 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8409 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8410 } 8411 8412 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8413 // smaller than XLenVT. 8414 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8415 const RISCVSubtarget &Subtarget) { 8416 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8417 8418 SDValue Src = N->getOperand(0); 8419 if (Src.getOpcode() != ISD::BSWAP) 8420 return SDValue(); 8421 8422 EVT VT = N->getValueType(0); 8423 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8424 !isPowerOf2_32(VT.getSizeInBits())) 8425 return SDValue(); 8426 8427 SDLoc DL(N); 8428 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8429 DAG.getConstant(7, DL, VT)); 8430 } 8431 8432 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8433 DAGCombinerInfo &DCI) const { 8434 SelectionDAG &DAG = DCI.DAG; 8435 8436 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8437 // bits are demanded. N will be added to the Worklist if it was not deleted. 8438 // Caller should return SDValue(N, 0) if this returns true. 8439 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8440 SDValue Op = N->getOperand(OpNo); 8441 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8442 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8443 return false; 8444 8445 if (N->getOpcode() != ISD::DELETED_NODE) 8446 DCI.AddToWorklist(N); 8447 return true; 8448 }; 8449 8450 switch (N->getOpcode()) { 8451 default: 8452 break; 8453 case RISCVISD::SplitF64: { 8454 SDValue Op0 = N->getOperand(0); 8455 // If the input to SplitF64 is just BuildPairF64 then the operation is 8456 // redundant. Instead, use BuildPairF64's operands directly. 8457 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8458 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8459 8460 if (Op0->isUndef()) { 8461 SDValue Lo = DAG.getUNDEF(MVT::i32); 8462 SDValue Hi = DAG.getUNDEF(MVT::i32); 8463 return DCI.CombineTo(N, Lo, Hi); 8464 } 8465 8466 SDLoc DL(N); 8467 8468 // It's cheaper to materialise two 32-bit integers than to load a double 8469 // from the constant pool and transfer it to integer registers through the 8470 // stack. 8471 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8472 APInt V = C->getValueAPF().bitcastToAPInt(); 8473 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8474 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8475 return DCI.CombineTo(N, Lo, Hi); 8476 } 8477 8478 // This is a target-specific version of a DAGCombine performed in 8479 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8480 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8481 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8482 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8483 !Op0.getNode()->hasOneUse()) 8484 break; 8485 SDValue NewSplitF64 = 8486 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8487 Op0.getOperand(0)); 8488 SDValue Lo = NewSplitF64.getValue(0); 8489 SDValue Hi = NewSplitF64.getValue(1); 8490 APInt SignBit = APInt::getSignMask(32); 8491 if (Op0.getOpcode() == ISD::FNEG) { 8492 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8493 DAG.getConstant(SignBit, DL, MVT::i32)); 8494 return DCI.CombineTo(N, Lo, NewHi); 8495 } 8496 assert(Op0.getOpcode() == ISD::FABS); 8497 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8498 DAG.getConstant(~SignBit, DL, MVT::i32)); 8499 return DCI.CombineTo(N, Lo, NewHi); 8500 } 8501 case RISCVISD::SLLW: 8502 case RISCVISD::SRAW: 8503 case RISCVISD::SRLW: { 8504 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8505 if (SimplifyDemandedLowBitsHelper(0, 32) || 8506 SimplifyDemandedLowBitsHelper(1, 5)) 8507 return SDValue(N, 0); 8508 8509 break; 8510 } 8511 case ISD::ROTR: 8512 case ISD::ROTL: 8513 case RISCVISD::RORW: 8514 case RISCVISD::ROLW: { 8515 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8516 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8517 if (SimplifyDemandedLowBitsHelper(0, 32) || 8518 SimplifyDemandedLowBitsHelper(1, 5)) 8519 return SDValue(N, 0); 8520 } 8521 8522 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8523 } 8524 case RISCVISD::CLZW: 8525 case RISCVISD::CTZW: { 8526 // Only the lower 32 bits of the first operand are read 8527 if (SimplifyDemandedLowBitsHelper(0, 32)) 8528 return SDValue(N, 0); 8529 break; 8530 } 8531 case RISCVISD::GREV: 8532 case RISCVISD::GORC: { 8533 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8534 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8535 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8536 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8537 return SDValue(N, 0); 8538 8539 return combineGREVI_GORCI(N, DAG); 8540 } 8541 case RISCVISD::GREVW: 8542 case RISCVISD::GORCW: { 8543 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8544 if (SimplifyDemandedLowBitsHelper(0, 32) || 8545 SimplifyDemandedLowBitsHelper(1, 5)) 8546 return SDValue(N, 0); 8547 8548 break; 8549 } 8550 case RISCVISD::SHFL: 8551 case RISCVISD::UNSHFL: { 8552 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8553 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8554 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8555 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8556 return SDValue(N, 0); 8557 8558 break; 8559 } 8560 case RISCVISD::SHFLW: 8561 case RISCVISD::UNSHFLW: { 8562 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8563 if (SimplifyDemandedLowBitsHelper(0, 32) || 8564 SimplifyDemandedLowBitsHelper(1, 4)) 8565 return SDValue(N, 0); 8566 8567 break; 8568 } 8569 case RISCVISD::BCOMPRESSW: 8570 case RISCVISD::BDECOMPRESSW: { 8571 // Only the lower 32 bits of LHS and RHS are read. 8572 if (SimplifyDemandedLowBitsHelper(0, 32) || 8573 SimplifyDemandedLowBitsHelper(1, 32)) 8574 return SDValue(N, 0); 8575 8576 break; 8577 } 8578 case RISCVISD::FSR: 8579 case RISCVISD::FSL: 8580 case RISCVISD::FSRW: 8581 case RISCVISD::FSLW: { 8582 bool IsWInstruction = 8583 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8584 unsigned BitWidth = 8585 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8586 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8587 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8588 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8589 return SDValue(N, 0); 8590 8591 break; 8592 } 8593 case RISCVISD::FMV_X_ANYEXTH: 8594 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8595 SDLoc DL(N); 8596 SDValue Op0 = N->getOperand(0); 8597 MVT VT = N->getSimpleValueType(0); 8598 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8599 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8600 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8601 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8602 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8603 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8604 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8605 assert(Op0.getOperand(0).getValueType() == VT && 8606 "Unexpected value type!"); 8607 return Op0.getOperand(0); 8608 } 8609 8610 // This is a target-specific version of a DAGCombine performed in 8611 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8612 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8613 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8614 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8615 !Op0.getNode()->hasOneUse()) 8616 break; 8617 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8618 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8619 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8620 if (Op0.getOpcode() == ISD::FNEG) 8621 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8622 DAG.getConstant(SignBit, DL, VT)); 8623 8624 assert(Op0.getOpcode() == ISD::FABS); 8625 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8626 DAG.getConstant(~SignBit, DL, VT)); 8627 } 8628 case ISD::ADD: 8629 return performADDCombine(N, DAG, Subtarget); 8630 case ISD::SUB: 8631 return performSUBCombine(N, DAG); 8632 case ISD::AND: 8633 return performANDCombine(N, DAG); 8634 case ISD::OR: 8635 return performORCombine(N, DAG, Subtarget); 8636 case ISD::XOR: 8637 return performXORCombine(N, DAG); 8638 case ISD::FADD: 8639 case ISD::UMAX: 8640 case ISD::UMIN: 8641 case ISD::SMAX: 8642 case ISD::SMIN: 8643 case ISD::FMAXNUM: 8644 case ISD::FMINNUM: 8645 return combineBinOpToReduce(N, DAG); 8646 case ISD::SIGN_EXTEND_INREG: 8647 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8648 case ISD::ZERO_EXTEND: 8649 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8650 // type legalization. This is safe because fp_to_uint produces poison if 8651 // it overflows. 8652 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8653 SDValue Src = N->getOperand(0); 8654 if (Src.getOpcode() == ISD::FP_TO_UINT && 8655 isTypeLegal(Src.getOperand(0).getValueType())) 8656 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8657 Src.getOperand(0)); 8658 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8659 isTypeLegal(Src.getOperand(1).getValueType())) { 8660 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8661 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8662 Src.getOperand(0), Src.getOperand(1)); 8663 DCI.CombineTo(N, Res); 8664 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8665 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8666 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8667 } 8668 } 8669 return SDValue(); 8670 case RISCVISD::SELECT_CC: { 8671 // Transform 8672 SDValue LHS = N->getOperand(0); 8673 SDValue RHS = N->getOperand(1); 8674 SDValue TrueV = N->getOperand(3); 8675 SDValue FalseV = N->getOperand(4); 8676 8677 // If the True and False values are the same, we don't need a select_cc. 8678 if (TrueV == FalseV) 8679 return TrueV; 8680 8681 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8682 if (!ISD::isIntEqualitySetCC(CCVal)) 8683 break; 8684 8685 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8686 // (select_cc X, Y, lt, trueV, falseV) 8687 // Sometimes the setcc is introduced after select_cc has been formed. 8688 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8689 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8690 // If we're looking for eq 0 instead of ne 0, we need to invert the 8691 // condition. 8692 bool Invert = CCVal == ISD::SETEQ; 8693 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8694 if (Invert) 8695 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8696 8697 SDLoc DL(N); 8698 RHS = LHS.getOperand(1); 8699 LHS = LHS.getOperand(0); 8700 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8701 8702 SDValue TargetCC = DAG.getCondCode(CCVal); 8703 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8704 {LHS, RHS, TargetCC, TrueV, FalseV}); 8705 } 8706 8707 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8708 // (select_cc X, Y, eq/ne, trueV, falseV) 8709 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8710 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8711 {LHS.getOperand(0), LHS.getOperand(1), 8712 N->getOperand(2), TrueV, FalseV}); 8713 // (select_cc X, 1, setne, trueV, falseV) -> 8714 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8715 // This can occur when legalizing some floating point comparisons. 8716 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8717 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8718 SDLoc DL(N); 8719 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8720 SDValue TargetCC = DAG.getCondCode(CCVal); 8721 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8722 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8723 {LHS, RHS, TargetCC, TrueV, FalseV}); 8724 } 8725 8726 break; 8727 } 8728 case RISCVISD::BR_CC: { 8729 SDValue LHS = N->getOperand(1); 8730 SDValue RHS = N->getOperand(2); 8731 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8732 if (!ISD::isIntEqualitySetCC(CCVal)) 8733 break; 8734 8735 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8736 // (br_cc X, Y, lt, dest) 8737 // Sometimes the setcc is introduced after br_cc has been formed. 8738 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8739 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8740 // If we're looking for eq 0 instead of ne 0, we need to invert the 8741 // condition. 8742 bool Invert = CCVal == ISD::SETEQ; 8743 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8744 if (Invert) 8745 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8746 8747 SDLoc DL(N); 8748 RHS = LHS.getOperand(1); 8749 LHS = LHS.getOperand(0); 8750 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8751 8752 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8753 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8754 N->getOperand(4)); 8755 } 8756 8757 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8758 // (br_cc X, Y, eq/ne, trueV, falseV) 8759 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8760 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8761 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8762 N->getOperand(3), N->getOperand(4)); 8763 8764 // (br_cc X, 1, setne, br_cc) -> 8765 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8766 // This can occur when legalizing some floating point comparisons. 8767 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8768 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8769 SDLoc DL(N); 8770 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8771 SDValue TargetCC = DAG.getCondCode(CCVal); 8772 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8773 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8774 N->getOperand(0), LHS, RHS, TargetCC, 8775 N->getOperand(4)); 8776 } 8777 break; 8778 } 8779 case ISD::BITREVERSE: 8780 return performBITREVERSECombine(N, DAG, Subtarget); 8781 case ISD::FP_TO_SINT: 8782 case ISD::FP_TO_UINT: 8783 return performFP_TO_INTCombine(N, DCI, Subtarget); 8784 case ISD::FP_TO_SINT_SAT: 8785 case ISD::FP_TO_UINT_SAT: 8786 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8787 case ISD::FCOPYSIGN: { 8788 EVT VT = N->getValueType(0); 8789 if (!VT.isVector()) 8790 break; 8791 // There is a form of VFSGNJ which injects the negated sign of its second 8792 // operand. Try and bubble any FNEG up after the extend/round to produce 8793 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8794 // TRUNC=1. 8795 SDValue In2 = N->getOperand(1); 8796 // Avoid cases where the extend/round has multiple uses, as duplicating 8797 // those is typically more expensive than removing a fneg. 8798 if (!In2.hasOneUse()) 8799 break; 8800 if (In2.getOpcode() != ISD::FP_EXTEND && 8801 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8802 break; 8803 In2 = In2.getOperand(0); 8804 if (In2.getOpcode() != ISD::FNEG) 8805 break; 8806 SDLoc DL(N); 8807 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8808 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8809 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8810 } 8811 case ISD::MGATHER: 8812 case ISD::MSCATTER: 8813 case ISD::VP_GATHER: 8814 case ISD::VP_SCATTER: { 8815 if (!DCI.isBeforeLegalize()) 8816 break; 8817 SDValue Index, ScaleOp; 8818 bool IsIndexScaled = false; 8819 bool IsIndexSigned = false; 8820 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8821 Index = VPGSN->getIndex(); 8822 ScaleOp = VPGSN->getScale(); 8823 IsIndexScaled = VPGSN->isIndexScaled(); 8824 IsIndexSigned = VPGSN->isIndexSigned(); 8825 } else { 8826 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8827 Index = MGSN->getIndex(); 8828 ScaleOp = MGSN->getScale(); 8829 IsIndexScaled = MGSN->isIndexScaled(); 8830 IsIndexSigned = MGSN->isIndexSigned(); 8831 } 8832 EVT IndexVT = Index.getValueType(); 8833 MVT XLenVT = Subtarget.getXLenVT(); 8834 // RISCV indexed loads only support the "unsigned unscaled" addressing 8835 // mode, so anything else must be manually legalized. 8836 bool NeedsIdxLegalization = 8837 IsIndexScaled || 8838 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8839 if (!NeedsIdxLegalization) 8840 break; 8841 8842 SDLoc DL(N); 8843 8844 // Any index legalization should first promote to XLenVT, so we don't lose 8845 // bits when scaling. This may create an illegal index type so we let 8846 // LLVM's legalization take care of the splitting. 8847 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8848 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8849 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8850 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8851 DL, IndexVT, Index); 8852 } 8853 8854 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8855 if (IsIndexScaled && Scale != 1) { 8856 // Manually scale the indices by the element size. 8857 // TODO: Sanitize the scale operand here? 8858 // TODO: For VP nodes, should we use VP_SHL here? 8859 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8860 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8861 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8862 } 8863 8864 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8865 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8866 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8867 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8868 VPGN->getScale(), VPGN->getMask(), 8869 VPGN->getVectorLength()}, 8870 VPGN->getMemOperand(), NewIndexTy); 8871 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8872 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8873 {VPSN->getChain(), VPSN->getValue(), 8874 VPSN->getBasePtr(), Index, VPSN->getScale(), 8875 VPSN->getMask(), VPSN->getVectorLength()}, 8876 VPSN->getMemOperand(), NewIndexTy); 8877 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8878 return DAG.getMaskedGather( 8879 N->getVTList(), MGN->getMemoryVT(), DL, 8880 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8881 MGN->getBasePtr(), Index, MGN->getScale()}, 8882 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8883 const auto *MSN = cast<MaskedScatterSDNode>(N); 8884 return DAG.getMaskedScatter( 8885 N->getVTList(), MSN->getMemoryVT(), DL, 8886 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8887 Index, MSN->getScale()}, 8888 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8889 } 8890 case RISCVISD::SRA_VL: 8891 case RISCVISD::SRL_VL: 8892 case RISCVISD::SHL_VL: { 8893 SDValue ShAmt = N->getOperand(1); 8894 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8895 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8896 SDLoc DL(N); 8897 SDValue VL = N->getOperand(3); 8898 EVT VT = N->getValueType(0); 8899 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8900 ShAmt.getOperand(1), VL); 8901 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8902 N->getOperand(2), N->getOperand(3)); 8903 } 8904 break; 8905 } 8906 case ISD::SRA: 8907 case ISD::SRL: 8908 case ISD::SHL: { 8909 SDValue ShAmt = N->getOperand(1); 8910 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8911 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8912 SDLoc DL(N); 8913 EVT VT = N->getValueType(0); 8914 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8915 ShAmt.getOperand(1), 8916 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8917 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8918 } 8919 break; 8920 } 8921 case RISCVISD::ADD_VL: 8922 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8923 return V; 8924 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8925 case RISCVISD::SUB_VL: 8926 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8927 case RISCVISD::VWADD_W_VL: 8928 case RISCVISD::VWADDU_W_VL: 8929 case RISCVISD::VWSUB_W_VL: 8930 case RISCVISD::VWSUBU_W_VL: 8931 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8932 case RISCVISD::MUL_VL: 8933 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8934 return V; 8935 // Mul is commutative. 8936 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8937 case ISD::STORE: { 8938 auto *Store = cast<StoreSDNode>(N); 8939 SDValue Val = Store->getValue(); 8940 // Combine store of vmv.x.s to vse with VL of 1. 8941 // FIXME: Support FP. 8942 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8943 SDValue Src = Val.getOperand(0); 8944 EVT VecVT = Src.getValueType(); 8945 EVT MemVT = Store->getMemoryVT(); 8946 // The memory VT and the element type must match. 8947 if (VecVT.getVectorElementType() == MemVT) { 8948 SDLoc DL(N); 8949 MVT MaskVT = getMaskTypeFor(VecVT); 8950 return DAG.getStoreVP( 8951 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8952 DAG.getConstant(1, DL, MaskVT), 8953 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8954 Store->getMemOperand(), Store->getAddressingMode(), 8955 Store->isTruncatingStore(), /*IsCompress*/ false); 8956 } 8957 } 8958 8959 break; 8960 } 8961 case ISD::SPLAT_VECTOR: { 8962 EVT VT = N->getValueType(0); 8963 // Only perform this combine on legal MVT types. 8964 if (!isTypeLegal(VT)) 8965 break; 8966 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8967 DAG, Subtarget)) 8968 return Gather; 8969 break; 8970 } 8971 case RISCVISD::VMV_V_X_VL: { 8972 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8973 // scalar input. 8974 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8975 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8976 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8977 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8978 return SDValue(N, 0); 8979 8980 break; 8981 } 8982 case ISD::INTRINSIC_WO_CHAIN: { 8983 unsigned IntNo = N->getConstantOperandVal(0); 8984 switch (IntNo) { 8985 // By default we do not combine any intrinsic. 8986 default: 8987 return SDValue(); 8988 case Intrinsic::riscv_vcpop: 8989 case Intrinsic::riscv_vcpop_mask: 8990 case Intrinsic::riscv_vfirst: 8991 case Intrinsic::riscv_vfirst_mask: { 8992 SDValue VL = N->getOperand(2); 8993 if (IntNo == Intrinsic::riscv_vcpop_mask || 8994 IntNo == Intrinsic::riscv_vfirst_mask) 8995 VL = N->getOperand(3); 8996 if (!isNullConstant(VL)) 8997 return SDValue(); 8998 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8999 SDLoc DL(N); 9000 EVT VT = N->getValueType(0); 9001 if (IntNo == Intrinsic::riscv_vfirst || 9002 IntNo == Intrinsic::riscv_vfirst_mask) 9003 return DAG.getConstant(-1, DL, VT); 9004 return DAG.getConstant(0, DL, VT); 9005 } 9006 } 9007 } 9008 } 9009 9010 return SDValue(); 9011 } 9012 9013 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9014 const SDNode *N, CombineLevel Level) const { 9015 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9016 // materialised in fewer instructions than `(OP _, c1)`: 9017 // 9018 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9019 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9020 SDValue N0 = N->getOperand(0); 9021 EVT Ty = N0.getValueType(); 9022 if (Ty.isScalarInteger() && 9023 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9024 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9025 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9026 if (C1 && C2) { 9027 const APInt &C1Int = C1->getAPIntValue(); 9028 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9029 9030 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9031 // and the combine should happen, to potentially allow further combines 9032 // later. 9033 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9034 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9035 return true; 9036 9037 // We can materialise `c1` in an add immediate, so it's "free", and the 9038 // combine should be prevented. 9039 if (C1Int.getMinSignedBits() <= 64 && 9040 isLegalAddImmediate(C1Int.getSExtValue())) 9041 return false; 9042 9043 // Neither constant will fit into an immediate, so find materialisation 9044 // costs. 9045 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9046 Subtarget.getFeatureBits(), 9047 /*CompressionCost*/true); 9048 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9049 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9050 /*CompressionCost*/true); 9051 9052 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9053 // combine should be prevented. 9054 if (C1Cost < ShiftedC1Cost) 9055 return false; 9056 } 9057 } 9058 return true; 9059 } 9060 9061 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9062 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9063 TargetLoweringOpt &TLO) const { 9064 // Delay this optimization as late as possible. 9065 if (!TLO.LegalOps) 9066 return false; 9067 9068 EVT VT = Op.getValueType(); 9069 if (VT.isVector()) 9070 return false; 9071 9072 // Only handle AND for now. 9073 if (Op.getOpcode() != ISD::AND) 9074 return false; 9075 9076 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9077 if (!C) 9078 return false; 9079 9080 const APInt &Mask = C->getAPIntValue(); 9081 9082 // Clear all non-demanded bits initially. 9083 APInt ShrunkMask = Mask & DemandedBits; 9084 9085 // Try to make a smaller immediate by setting undemanded bits. 9086 9087 APInt ExpandedMask = Mask | ~DemandedBits; 9088 9089 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9090 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9091 }; 9092 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9093 if (NewMask == Mask) 9094 return true; 9095 SDLoc DL(Op); 9096 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9097 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9098 return TLO.CombineTo(Op, NewOp); 9099 }; 9100 9101 // If the shrunk mask fits in sign extended 12 bits, let the target 9102 // independent code apply it. 9103 if (ShrunkMask.isSignedIntN(12)) 9104 return false; 9105 9106 // Preserve (and X, 0xffff) when zext.h is supported. 9107 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9108 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9109 if (IsLegalMask(NewMask)) 9110 return UseMask(NewMask); 9111 } 9112 9113 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9114 if (VT == MVT::i64) { 9115 APInt NewMask = APInt(64, 0xffffffff); 9116 if (IsLegalMask(NewMask)) 9117 return UseMask(NewMask); 9118 } 9119 9120 // For the remaining optimizations, we need to be able to make a negative 9121 // number through a combination of mask and undemanded bits. 9122 if (!ExpandedMask.isNegative()) 9123 return false; 9124 9125 // What is the fewest number of bits we need to represent the negative number. 9126 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9127 9128 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9129 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9130 APInt NewMask = ShrunkMask; 9131 if (MinSignedBits <= 12) 9132 NewMask.setBitsFrom(11); 9133 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9134 NewMask.setBitsFrom(31); 9135 else 9136 return false; 9137 9138 // Check that our new mask is a subset of the demanded mask. 9139 assert(IsLegalMask(NewMask)); 9140 return UseMask(NewMask); 9141 } 9142 9143 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9144 static const uint64_t GREVMasks[] = { 9145 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9146 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9147 9148 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9149 unsigned Shift = 1 << Stage; 9150 if (ShAmt & Shift) { 9151 uint64_t Mask = GREVMasks[Stage]; 9152 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9153 if (IsGORC) 9154 Res |= x; 9155 x = Res; 9156 } 9157 } 9158 9159 return x; 9160 } 9161 9162 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9163 KnownBits &Known, 9164 const APInt &DemandedElts, 9165 const SelectionDAG &DAG, 9166 unsigned Depth) const { 9167 unsigned BitWidth = Known.getBitWidth(); 9168 unsigned Opc = Op.getOpcode(); 9169 assert((Opc >= ISD::BUILTIN_OP_END || 9170 Opc == ISD::INTRINSIC_WO_CHAIN || 9171 Opc == ISD::INTRINSIC_W_CHAIN || 9172 Opc == ISD::INTRINSIC_VOID) && 9173 "Should use MaskedValueIsZero if you don't know whether Op" 9174 " is a target node!"); 9175 9176 Known.resetAll(); 9177 switch (Opc) { 9178 default: break; 9179 case RISCVISD::SELECT_CC: { 9180 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9181 // If we don't know any bits, early out. 9182 if (Known.isUnknown()) 9183 break; 9184 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9185 9186 // Only known if known in both the LHS and RHS. 9187 Known = KnownBits::commonBits(Known, Known2); 9188 break; 9189 } 9190 case RISCVISD::REMUW: { 9191 KnownBits Known2; 9192 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9193 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9194 // We only care about the lower 32 bits. 9195 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9196 // Restore the original width by sign extending. 9197 Known = Known.sext(BitWidth); 9198 break; 9199 } 9200 case RISCVISD::DIVUW: { 9201 KnownBits Known2; 9202 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9203 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9204 // We only care about the lower 32 bits. 9205 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9206 // Restore the original width by sign extending. 9207 Known = Known.sext(BitWidth); 9208 break; 9209 } 9210 case RISCVISD::CTZW: { 9211 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9212 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9213 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9214 Known.Zero.setBitsFrom(LowBits); 9215 break; 9216 } 9217 case RISCVISD::CLZW: { 9218 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9219 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9220 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9221 Known.Zero.setBitsFrom(LowBits); 9222 break; 9223 } 9224 case RISCVISD::GREV: 9225 case RISCVISD::GORC: { 9226 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9227 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9228 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9229 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9230 // To compute zeros, we need to invert the value and invert it back after. 9231 Known.Zero = 9232 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9233 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9234 } 9235 break; 9236 } 9237 case RISCVISD::READ_VLENB: { 9238 // If we know the minimum VLen from Zvl extensions, we can use that to 9239 // determine the trailing zeros of VLENB. 9240 // FIXME: Limit to 128 bit vectors until we have more testing. 9241 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9242 if (MinVLenB > 0) 9243 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9244 // We assume VLENB is no more than 65536 / 8 bytes. 9245 Known.Zero.setBitsFrom(14); 9246 break; 9247 } 9248 case ISD::INTRINSIC_W_CHAIN: 9249 case ISD::INTRINSIC_WO_CHAIN: { 9250 unsigned IntNo = 9251 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9252 switch (IntNo) { 9253 default: 9254 // We can't do anything for most intrinsics. 9255 break; 9256 case Intrinsic::riscv_vsetvli: 9257 case Intrinsic::riscv_vsetvlimax: 9258 case Intrinsic::riscv_vsetvli_opt: 9259 case Intrinsic::riscv_vsetvlimax_opt: 9260 // Assume that VL output is positive and would fit in an int32_t. 9261 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9262 if (BitWidth >= 32) 9263 Known.Zero.setBitsFrom(31); 9264 break; 9265 } 9266 break; 9267 } 9268 } 9269 } 9270 9271 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9272 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9273 unsigned Depth) const { 9274 switch (Op.getOpcode()) { 9275 default: 9276 break; 9277 case RISCVISD::SELECT_CC: { 9278 unsigned Tmp = 9279 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9280 if (Tmp == 1) return 1; // Early out. 9281 unsigned Tmp2 = 9282 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9283 return std::min(Tmp, Tmp2); 9284 } 9285 case RISCVISD::SLLW: 9286 case RISCVISD::SRAW: 9287 case RISCVISD::SRLW: 9288 case RISCVISD::DIVW: 9289 case RISCVISD::DIVUW: 9290 case RISCVISD::REMUW: 9291 case RISCVISD::ROLW: 9292 case RISCVISD::RORW: 9293 case RISCVISD::GREVW: 9294 case RISCVISD::GORCW: 9295 case RISCVISD::FSLW: 9296 case RISCVISD::FSRW: 9297 case RISCVISD::SHFLW: 9298 case RISCVISD::UNSHFLW: 9299 case RISCVISD::BCOMPRESSW: 9300 case RISCVISD::BDECOMPRESSW: 9301 case RISCVISD::BFPW: 9302 case RISCVISD::FCVT_W_RV64: 9303 case RISCVISD::FCVT_WU_RV64: 9304 case RISCVISD::STRICT_FCVT_W_RV64: 9305 case RISCVISD::STRICT_FCVT_WU_RV64: 9306 // TODO: As the result is sign-extended, this is conservatively correct. A 9307 // more precise answer could be calculated for SRAW depending on known 9308 // bits in the shift amount. 9309 return 33; 9310 case RISCVISD::SHFL: 9311 case RISCVISD::UNSHFL: { 9312 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9313 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9314 // will stay within the upper 32 bits. If there were more than 32 sign bits 9315 // before there will be at least 33 sign bits after. 9316 if (Op.getValueType() == MVT::i64 && 9317 isa<ConstantSDNode>(Op.getOperand(1)) && 9318 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9319 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9320 if (Tmp > 32) 9321 return 33; 9322 } 9323 break; 9324 } 9325 case RISCVISD::VMV_X_S: { 9326 // The number of sign bits of the scalar result is computed by obtaining the 9327 // element type of the input vector operand, subtracting its width from the 9328 // XLEN, and then adding one (sign bit within the element type). If the 9329 // element type is wider than XLen, the least-significant XLEN bits are 9330 // taken. 9331 unsigned XLen = Subtarget.getXLen(); 9332 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9333 if (EltBits <= XLen) 9334 return XLen - EltBits + 1; 9335 break; 9336 } 9337 } 9338 9339 return 1; 9340 } 9341 9342 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9343 MachineBasicBlock *BB) { 9344 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9345 9346 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9347 // Should the count have wrapped while it was being read, we need to try 9348 // again. 9349 // ... 9350 // read: 9351 // rdcycleh x3 # load high word of cycle 9352 // rdcycle x2 # load low word of cycle 9353 // rdcycleh x4 # load high word of cycle 9354 // bne x3, x4, read # check if high word reads match, otherwise try again 9355 // ... 9356 9357 MachineFunction &MF = *BB->getParent(); 9358 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9359 MachineFunction::iterator It = ++BB->getIterator(); 9360 9361 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9362 MF.insert(It, LoopMBB); 9363 9364 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9365 MF.insert(It, DoneMBB); 9366 9367 // Transfer the remainder of BB and its successor edges to DoneMBB. 9368 DoneMBB->splice(DoneMBB->begin(), BB, 9369 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9370 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9371 9372 BB->addSuccessor(LoopMBB); 9373 9374 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9375 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9376 Register LoReg = MI.getOperand(0).getReg(); 9377 Register HiReg = MI.getOperand(1).getReg(); 9378 DebugLoc DL = MI.getDebugLoc(); 9379 9380 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9381 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9382 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9383 .addReg(RISCV::X0); 9384 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9385 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9386 .addReg(RISCV::X0); 9387 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9388 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9389 .addReg(RISCV::X0); 9390 9391 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9392 .addReg(HiReg) 9393 .addReg(ReadAgainReg) 9394 .addMBB(LoopMBB); 9395 9396 LoopMBB->addSuccessor(LoopMBB); 9397 LoopMBB->addSuccessor(DoneMBB); 9398 9399 MI.eraseFromParent(); 9400 9401 return DoneMBB; 9402 } 9403 9404 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9405 MachineBasicBlock *BB) { 9406 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9407 9408 MachineFunction &MF = *BB->getParent(); 9409 DebugLoc DL = MI.getDebugLoc(); 9410 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9411 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9412 Register LoReg = MI.getOperand(0).getReg(); 9413 Register HiReg = MI.getOperand(1).getReg(); 9414 Register SrcReg = MI.getOperand(2).getReg(); 9415 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9416 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9417 9418 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9419 RI); 9420 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9421 MachineMemOperand *MMOLo = 9422 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9423 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9424 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9425 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9426 .addFrameIndex(FI) 9427 .addImm(0) 9428 .addMemOperand(MMOLo); 9429 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9430 .addFrameIndex(FI) 9431 .addImm(4) 9432 .addMemOperand(MMOHi); 9433 MI.eraseFromParent(); // The pseudo instruction is gone now. 9434 return BB; 9435 } 9436 9437 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9438 MachineBasicBlock *BB) { 9439 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9440 "Unexpected instruction"); 9441 9442 MachineFunction &MF = *BB->getParent(); 9443 DebugLoc DL = MI.getDebugLoc(); 9444 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9445 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9446 Register DstReg = MI.getOperand(0).getReg(); 9447 Register LoReg = MI.getOperand(1).getReg(); 9448 Register HiReg = MI.getOperand(2).getReg(); 9449 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9450 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9451 9452 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9453 MachineMemOperand *MMOLo = 9454 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9455 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9456 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9457 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9458 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9459 .addFrameIndex(FI) 9460 .addImm(0) 9461 .addMemOperand(MMOLo); 9462 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9463 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9464 .addFrameIndex(FI) 9465 .addImm(4) 9466 .addMemOperand(MMOHi); 9467 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9468 MI.eraseFromParent(); // The pseudo instruction is gone now. 9469 return BB; 9470 } 9471 9472 static bool isSelectPseudo(MachineInstr &MI) { 9473 switch (MI.getOpcode()) { 9474 default: 9475 return false; 9476 case RISCV::Select_GPR_Using_CC_GPR: 9477 case RISCV::Select_FPR16_Using_CC_GPR: 9478 case RISCV::Select_FPR32_Using_CC_GPR: 9479 case RISCV::Select_FPR64_Using_CC_GPR: 9480 return true; 9481 } 9482 } 9483 9484 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9485 unsigned RelOpcode, unsigned EqOpcode, 9486 const RISCVSubtarget &Subtarget) { 9487 DebugLoc DL = MI.getDebugLoc(); 9488 Register DstReg = MI.getOperand(0).getReg(); 9489 Register Src1Reg = MI.getOperand(1).getReg(); 9490 Register Src2Reg = MI.getOperand(2).getReg(); 9491 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9492 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9493 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9494 9495 // Save the current FFLAGS. 9496 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9497 9498 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9499 .addReg(Src1Reg) 9500 .addReg(Src2Reg); 9501 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9502 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9503 9504 // Restore the FFLAGS. 9505 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9506 .addReg(SavedFFlags, RegState::Kill); 9507 9508 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9509 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9510 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9511 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9512 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9513 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9514 9515 // Erase the pseudoinstruction. 9516 MI.eraseFromParent(); 9517 return BB; 9518 } 9519 9520 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9521 MachineBasicBlock *BB, 9522 const RISCVSubtarget &Subtarget) { 9523 // To "insert" Select_* instructions, we actually have to insert the triangle 9524 // control-flow pattern. The incoming instructions know the destination vreg 9525 // to set, the condition code register to branch on, the true/false values to 9526 // select between, and the condcode to use to select the appropriate branch. 9527 // 9528 // We produce the following control flow: 9529 // HeadMBB 9530 // | \ 9531 // | IfFalseMBB 9532 // | / 9533 // TailMBB 9534 // 9535 // When we find a sequence of selects we attempt to optimize their emission 9536 // by sharing the control flow. Currently we only handle cases where we have 9537 // multiple selects with the exact same condition (same LHS, RHS and CC). 9538 // The selects may be interleaved with other instructions if the other 9539 // instructions meet some requirements we deem safe: 9540 // - They are debug instructions. Otherwise, 9541 // - They do not have side-effects, do not access memory and their inputs do 9542 // not depend on the results of the select pseudo-instructions. 9543 // The TrueV/FalseV operands of the selects cannot depend on the result of 9544 // previous selects in the sequence. 9545 // These conditions could be further relaxed. See the X86 target for a 9546 // related approach and more information. 9547 Register LHS = MI.getOperand(1).getReg(); 9548 Register RHS = MI.getOperand(2).getReg(); 9549 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9550 9551 SmallVector<MachineInstr *, 4> SelectDebugValues; 9552 SmallSet<Register, 4> SelectDests; 9553 SelectDests.insert(MI.getOperand(0).getReg()); 9554 9555 MachineInstr *LastSelectPseudo = &MI; 9556 9557 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9558 SequenceMBBI != E; ++SequenceMBBI) { 9559 if (SequenceMBBI->isDebugInstr()) 9560 continue; 9561 else if (isSelectPseudo(*SequenceMBBI)) { 9562 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9563 SequenceMBBI->getOperand(2).getReg() != RHS || 9564 SequenceMBBI->getOperand(3).getImm() != CC || 9565 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9566 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9567 break; 9568 LastSelectPseudo = &*SequenceMBBI; 9569 SequenceMBBI->collectDebugValues(SelectDebugValues); 9570 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9571 } else { 9572 if (SequenceMBBI->hasUnmodeledSideEffects() || 9573 SequenceMBBI->mayLoadOrStore()) 9574 break; 9575 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9576 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9577 })) 9578 break; 9579 } 9580 } 9581 9582 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9583 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9584 DebugLoc DL = MI.getDebugLoc(); 9585 MachineFunction::iterator I = ++BB->getIterator(); 9586 9587 MachineBasicBlock *HeadMBB = BB; 9588 MachineFunction *F = BB->getParent(); 9589 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9590 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9591 9592 F->insert(I, IfFalseMBB); 9593 F->insert(I, TailMBB); 9594 9595 // Transfer debug instructions associated with the selects to TailMBB. 9596 for (MachineInstr *DebugInstr : SelectDebugValues) { 9597 TailMBB->push_back(DebugInstr->removeFromParent()); 9598 } 9599 9600 // Move all instructions after the sequence to TailMBB. 9601 TailMBB->splice(TailMBB->end(), HeadMBB, 9602 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9603 // Update machine-CFG edges by transferring all successors of the current 9604 // block to the new block which will contain the Phi nodes for the selects. 9605 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9606 // Set the successors for HeadMBB. 9607 HeadMBB->addSuccessor(IfFalseMBB); 9608 HeadMBB->addSuccessor(TailMBB); 9609 9610 // Insert appropriate branch. 9611 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9612 .addReg(LHS) 9613 .addReg(RHS) 9614 .addMBB(TailMBB); 9615 9616 // IfFalseMBB just falls through to TailMBB. 9617 IfFalseMBB->addSuccessor(TailMBB); 9618 9619 // Create PHIs for all of the select pseudo-instructions. 9620 auto SelectMBBI = MI.getIterator(); 9621 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9622 auto InsertionPoint = TailMBB->begin(); 9623 while (SelectMBBI != SelectEnd) { 9624 auto Next = std::next(SelectMBBI); 9625 if (isSelectPseudo(*SelectMBBI)) { 9626 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9627 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9628 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9629 .addReg(SelectMBBI->getOperand(4).getReg()) 9630 .addMBB(HeadMBB) 9631 .addReg(SelectMBBI->getOperand(5).getReg()) 9632 .addMBB(IfFalseMBB); 9633 SelectMBBI->eraseFromParent(); 9634 } 9635 SelectMBBI = Next; 9636 } 9637 9638 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9639 return TailMBB; 9640 } 9641 9642 MachineBasicBlock * 9643 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9644 MachineBasicBlock *BB) const { 9645 switch (MI.getOpcode()) { 9646 default: 9647 llvm_unreachable("Unexpected instr type to insert"); 9648 case RISCV::ReadCycleWide: 9649 assert(!Subtarget.is64Bit() && 9650 "ReadCycleWrite is only to be used on riscv32"); 9651 return emitReadCycleWidePseudo(MI, BB); 9652 case RISCV::Select_GPR_Using_CC_GPR: 9653 case RISCV::Select_FPR16_Using_CC_GPR: 9654 case RISCV::Select_FPR32_Using_CC_GPR: 9655 case RISCV::Select_FPR64_Using_CC_GPR: 9656 return emitSelectPseudo(MI, BB, Subtarget); 9657 case RISCV::BuildPairF64Pseudo: 9658 return emitBuildPairF64Pseudo(MI, BB); 9659 case RISCV::SplitF64Pseudo: 9660 return emitSplitF64Pseudo(MI, BB); 9661 case RISCV::PseudoQuietFLE_H: 9662 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9663 case RISCV::PseudoQuietFLT_H: 9664 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9665 case RISCV::PseudoQuietFLE_S: 9666 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9667 case RISCV::PseudoQuietFLT_S: 9668 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9669 case RISCV::PseudoQuietFLE_D: 9670 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9671 case RISCV::PseudoQuietFLT_D: 9672 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9673 } 9674 } 9675 9676 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9677 SDNode *Node) const { 9678 // Add FRM dependency to any instructions with dynamic rounding mode. 9679 unsigned Opc = MI.getOpcode(); 9680 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9681 if (Idx < 0) 9682 return; 9683 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9684 return; 9685 // If the instruction already reads FRM, don't add another read. 9686 if (MI.readsRegister(RISCV::FRM)) 9687 return; 9688 MI.addOperand( 9689 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9690 } 9691 9692 // Calling Convention Implementation. 9693 // The expectations for frontend ABI lowering vary from target to target. 9694 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9695 // details, but this is a longer term goal. For now, we simply try to keep the 9696 // role of the frontend as simple and well-defined as possible. The rules can 9697 // be summarised as: 9698 // * Never split up large scalar arguments. We handle them here. 9699 // * If a hardfloat calling convention is being used, and the struct may be 9700 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9701 // available, then pass as two separate arguments. If either the GPRs or FPRs 9702 // are exhausted, then pass according to the rule below. 9703 // * If a struct could never be passed in registers or directly in a stack 9704 // slot (as it is larger than 2*XLEN and the floating point rules don't 9705 // apply), then pass it using a pointer with the byval attribute. 9706 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9707 // word-sized array or a 2*XLEN scalar (depending on alignment). 9708 // * The frontend can determine whether a struct is returned by reference or 9709 // not based on its size and fields. If it will be returned by reference, the 9710 // frontend must modify the prototype so a pointer with the sret annotation is 9711 // passed as the first argument. This is not necessary for large scalar 9712 // returns. 9713 // * Struct return values and varargs should be coerced to structs containing 9714 // register-size fields in the same situations they would be for fixed 9715 // arguments. 9716 9717 static const MCPhysReg ArgGPRs[] = { 9718 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9719 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9720 }; 9721 static const MCPhysReg ArgFPR16s[] = { 9722 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9723 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9724 }; 9725 static const MCPhysReg ArgFPR32s[] = { 9726 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9727 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9728 }; 9729 static const MCPhysReg ArgFPR64s[] = { 9730 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9731 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9732 }; 9733 // This is an interim calling convention and it may be changed in the future. 9734 static const MCPhysReg ArgVRs[] = { 9735 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9736 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9737 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9738 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9739 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9740 RISCV::V20M2, RISCV::V22M2}; 9741 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9742 RISCV::V20M4}; 9743 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9744 9745 // Pass a 2*XLEN argument that has been split into two XLEN values through 9746 // registers or the stack as necessary. 9747 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9748 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9749 MVT ValVT2, MVT LocVT2, 9750 ISD::ArgFlagsTy ArgFlags2) { 9751 unsigned XLenInBytes = XLen / 8; 9752 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9753 // At least one half can be passed via register. 9754 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9755 VA1.getLocVT(), CCValAssign::Full)); 9756 } else { 9757 // Both halves must be passed on the stack, with proper alignment. 9758 Align StackAlign = 9759 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9760 State.addLoc( 9761 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9762 State.AllocateStack(XLenInBytes, StackAlign), 9763 VA1.getLocVT(), CCValAssign::Full)); 9764 State.addLoc(CCValAssign::getMem( 9765 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9766 LocVT2, CCValAssign::Full)); 9767 return false; 9768 } 9769 9770 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9771 // The second half can also be passed via register. 9772 State.addLoc( 9773 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9774 } else { 9775 // The second half is passed via the stack, without additional alignment. 9776 State.addLoc(CCValAssign::getMem( 9777 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9778 LocVT2, CCValAssign::Full)); 9779 } 9780 9781 return false; 9782 } 9783 9784 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9785 Optional<unsigned> FirstMaskArgument, 9786 CCState &State, const RISCVTargetLowering &TLI) { 9787 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9788 if (RC == &RISCV::VRRegClass) { 9789 // Assign the first mask argument to V0. 9790 // This is an interim calling convention and it may be changed in the 9791 // future. 9792 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9793 return State.AllocateReg(RISCV::V0); 9794 return State.AllocateReg(ArgVRs); 9795 } 9796 if (RC == &RISCV::VRM2RegClass) 9797 return State.AllocateReg(ArgVRM2s); 9798 if (RC == &RISCV::VRM4RegClass) 9799 return State.AllocateReg(ArgVRM4s); 9800 if (RC == &RISCV::VRM8RegClass) 9801 return State.AllocateReg(ArgVRM8s); 9802 llvm_unreachable("Unhandled register class for ValueType"); 9803 } 9804 9805 // Implements the RISC-V calling convention. Returns true upon failure. 9806 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9807 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9808 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9809 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9810 Optional<unsigned> FirstMaskArgument) { 9811 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9812 assert(XLen == 32 || XLen == 64); 9813 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9814 9815 // Any return value split in to more than two values can't be returned 9816 // directly. Vectors are returned via the available vector registers. 9817 if (!LocVT.isVector() && IsRet && ValNo > 1) 9818 return true; 9819 9820 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9821 // variadic argument, or if no F16/F32 argument registers are available. 9822 bool UseGPRForF16_F32 = true; 9823 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9824 // variadic argument, or if no F64 argument registers are available. 9825 bool UseGPRForF64 = true; 9826 9827 switch (ABI) { 9828 default: 9829 llvm_unreachable("Unexpected ABI"); 9830 case RISCVABI::ABI_ILP32: 9831 case RISCVABI::ABI_LP64: 9832 break; 9833 case RISCVABI::ABI_ILP32F: 9834 case RISCVABI::ABI_LP64F: 9835 UseGPRForF16_F32 = !IsFixed; 9836 break; 9837 case RISCVABI::ABI_ILP32D: 9838 case RISCVABI::ABI_LP64D: 9839 UseGPRForF16_F32 = !IsFixed; 9840 UseGPRForF64 = !IsFixed; 9841 break; 9842 } 9843 9844 // FPR16, FPR32, and FPR64 alias each other. 9845 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9846 UseGPRForF16_F32 = true; 9847 UseGPRForF64 = true; 9848 } 9849 9850 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9851 // similar local variables rather than directly checking against the target 9852 // ABI. 9853 9854 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9855 LocVT = XLenVT; 9856 LocInfo = CCValAssign::BCvt; 9857 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9858 LocVT = MVT::i64; 9859 LocInfo = CCValAssign::BCvt; 9860 } 9861 9862 // If this is a variadic argument, the RISC-V calling convention requires 9863 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9864 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9865 // be used regardless of whether the original argument was split during 9866 // legalisation or not. The argument will not be passed by registers if the 9867 // original type is larger than 2*XLEN, so the register alignment rule does 9868 // not apply. 9869 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9870 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9871 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9872 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9873 // Skip 'odd' register if necessary. 9874 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9875 State.AllocateReg(ArgGPRs); 9876 } 9877 9878 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9879 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9880 State.getPendingArgFlags(); 9881 9882 assert(PendingLocs.size() == PendingArgFlags.size() && 9883 "PendingLocs and PendingArgFlags out of sync"); 9884 9885 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9886 // registers are exhausted. 9887 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9888 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9889 "Can't lower f64 if it is split"); 9890 // Depending on available argument GPRS, f64 may be passed in a pair of 9891 // GPRs, split between a GPR and the stack, or passed completely on the 9892 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9893 // cases. 9894 Register Reg = State.AllocateReg(ArgGPRs); 9895 LocVT = MVT::i32; 9896 if (!Reg) { 9897 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9898 State.addLoc( 9899 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9900 return false; 9901 } 9902 if (!State.AllocateReg(ArgGPRs)) 9903 State.AllocateStack(4, Align(4)); 9904 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9905 return false; 9906 } 9907 9908 // Fixed-length vectors are located in the corresponding scalable-vector 9909 // container types. 9910 if (ValVT.isFixedLengthVector()) 9911 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9912 9913 // Split arguments might be passed indirectly, so keep track of the pending 9914 // values. Split vectors are passed via a mix of registers and indirectly, so 9915 // treat them as we would any other argument. 9916 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9917 LocVT = XLenVT; 9918 LocInfo = CCValAssign::Indirect; 9919 PendingLocs.push_back( 9920 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9921 PendingArgFlags.push_back(ArgFlags); 9922 if (!ArgFlags.isSplitEnd()) { 9923 return false; 9924 } 9925 } 9926 9927 // If the split argument only had two elements, it should be passed directly 9928 // in registers or on the stack. 9929 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9930 PendingLocs.size() <= 2) { 9931 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9932 // Apply the normal calling convention rules to the first half of the 9933 // split argument. 9934 CCValAssign VA = PendingLocs[0]; 9935 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9936 PendingLocs.clear(); 9937 PendingArgFlags.clear(); 9938 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9939 ArgFlags); 9940 } 9941 9942 // Allocate to a register if possible, or else a stack slot. 9943 Register Reg; 9944 unsigned StoreSizeBytes = XLen / 8; 9945 Align StackAlign = Align(XLen / 8); 9946 9947 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9948 Reg = State.AllocateReg(ArgFPR16s); 9949 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9950 Reg = State.AllocateReg(ArgFPR32s); 9951 else if (ValVT == MVT::f64 && !UseGPRForF64) 9952 Reg = State.AllocateReg(ArgFPR64s); 9953 else if (ValVT.isVector()) { 9954 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9955 if (!Reg) { 9956 // For return values, the vector must be passed fully via registers or 9957 // via the stack. 9958 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9959 // but we're using all of them. 9960 if (IsRet) 9961 return true; 9962 // Try using a GPR to pass the address 9963 if ((Reg = State.AllocateReg(ArgGPRs))) { 9964 LocVT = XLenVT; 9965 LocInfo = CCValAssign::Indirect; 9966 } else if (ValVT.isScalableVector()) { 9967 LocVT = XLenVT; 9968 LocInfo = CCValAssign::Indirect; 9969 } else { 9970 // Pass fixed-length vectors on the stack. 9971 LocVT = ValVT; 9972 StoreSizeBytes = ValVT.getStoreSize(); 9973 // Align vectors to their element sizes, being careful for vXi1 9974 // vectors. 9975 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9976 } 9977 } 9978 } else { 9979 Reg = State.AllocateReg(ArgGPRs); 9980 } 9981 9982 unsigned StackOffset = 9983 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9984 9985 // If we reach this point and PendingLocs is non-empty, we must be at the 9986 // end of a split argument that must be passed indirectly. 9987 if (!PendingLocs.empty()) { 9988 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9989 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9990 9991 for (auto &It : PendingLocs) { 9992 if (Reg) 9993 It.convertToReg(Reg); 9994 else 9995 It.convertToMem(StackOffset); 9996 State.addLoc(It); 9997 } 9998 PendingLocs.clear(); 9999 PendingArgFlags.clear(); 10000 return false; 10001 } 10002 10003 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10004 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10005 "Expected an XLenVT or vector types at this stage"); 10006 10007 if (Reg) { 10008 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10009 return false; 10010 } 10011 10012 // When a floating-point value is passed on the stack, no bit-conversion is 10013 // needed. 10014 if (ValVT.isFloatingPoint()) { 10015 LocVT = ValVT; 10016 LocInfo = CCValAssign::Full; 10017 } 10018 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10019 return false; 10020 } 10021 10022 template <typename ArgTy> 10023 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10024 for (const auto &ArgIdx : enumerate(Args)) { 10025 MVT ArgVT = ArgIdx.value().VT; 10026 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10027 return ArgIdx.index(); 10028 } 10029 return None; 10030 } 10031 10032 void RISCVTargetLowering::analyzeInputArgs( 10033 MachineFunction &MF, CCState &CCInfo, 10034 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10035 RISCVCCAssignFn Fn) const { 10036 unsigned NumArgs = Ins.size(); 10037 FunctionType *FType = MF.getFunction().getFunctionType(); 10038 10039 Optional<unsigned> FirstMaskArgument; 10040 if (Subtarget.hasVInstructions()) 10041 FirstMaskArgument = preAssignMask(Ins); 10042 10043 for (unsigned i = 0; i != NumArgs; ++i) { 10044 MVT ArgVT = Ins[i].VT; 10045 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10046 10047 Type *ArgTy = nullptr; 10048 if (IsRet) 10049 ArgTy = FType->getReturnType(); 10050 else if (Ins[i].isOrigArg()) 10051 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10052 10053 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10054 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10055 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10056 FirstMaskArgument)) { 10057 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10058 << EVT(ArgVT).getEVTString() << '\n'); 10059 llvm_unreachable(nullptr); 10060 } 10061 } 10062 } 10063 10064 void RISCVTargetLowering::analyzeOutputArgs( 10065 MachineFunction &MF, CCState &CCInfo, 10066 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10067 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10068 unsigned NumArgs = Outs.size(); 10069 10070 Optional<unsigned> FirstMaskArgument; 10071 if (Subtarget.hasVInstructions()) 10072 FirstMaskArgument = preAssignMask(Outs); 10073 10074 for (unsigned i = 0; i != NumArgs; i++) { 10075 MVT ArgVT = Outs[i].VT; 10076 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10077 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10078 10079 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10080 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10081 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10082 FirstMaskArgument)) { 10083 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10084 << EVT(ArgVT).getEVTString() << "\n"); 10085 llvm_unreachable(nullptr); 10086 } 10087 } 10088 } 10089 10090 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10091 // values. 10092 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10093 const CCValAssign &VA, const SDLoc &DL, 10094 const RISCVSubtarget &Subtarget) { 10095 switch (VA.getLocInfo()) { 10096 default: 10097 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10098 case CCValAssign::Full: 10099 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10100 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10101 break; 10102 case CCValAssign::BCvt: 10103 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10104 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10105 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10106 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10107 else 10108 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10109 break; 10110 } 10111 return Val; 10112 } 10113 10114 // The caller is responsible for loading the full value if the argument is 10115 // passed with CCValAssign::Indirect. 10116 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10117 const CCValAssign &VA, const SDLoc &DL, 10118 const RISCVTargetLowering &TLI) { 10119 MachineFunction &MF = DAG.getMachineFunction(); 10120 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10121 EVT LocVT = VA.getLocVT(); 10122 SDValue Val; 10123 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10124 Register VReg = RegInfo.createVirtualRegister(RC); 10125 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10126 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10127 10128 if (VA.getLocInfo() == CCValAssign::Indirect) 10129 return Val; 10130 10131 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10132 } 10133 10134 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10135 const CCValAssign &VA, const SDLoc &DL, 10136 const RISCVSubtarget &Subtarget) { 10137 EVT LocVT = VA.getLocVT(); 10138 10139 switch (VA.getLocInfo()) { 10140 default: 10141 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10142 case CCValAssign::Full: 10143 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10144 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10145 break; 10146 case CCValAssign::BCvt: 10147 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10148 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10149 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10150 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10151 else 10152 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10153 break; 10154 } 10155 return Val; 10156 } 10157 10158 // The caller is responsible for loading the full value if the argument is 10159 // passed with CCValAssign::Indirect. 10160 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10161 const CCValAssign &VA, const SDLoc &DL) { 10162 MachineFunction &MF = DAG.getMachineFunction(); 10163 MachineFrameInfo &MFI = MF.getFrameInfo(); 10164 EVT LocVT = VA.getLocVT(); 10165 EVT ValVT = VA.getValVT(); 10166 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10167 if (ValVT.isScalableVector()) { 10168 // When the value is a scalable vector, we save the pointer which points to 10169 // the scalable vector value in the stack. The ValVT will be the pointer 10170 // type, instead of the scalable vector type. 10171 ValVT = LocVT; 10172 } 10173 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10174 /*IsImmutable=*/true); 10175 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10176 SDValue Val; 10177 10178 ISD::LoadExtType ExtType; 10179 switch (VA.getLocInfo()) { 10180 default: 10181 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10182 case CCValAssign::Full: 10183 case CCValAssign::Indirect: 10184 case CCValAssign::BCvt: 10185 ExtType = ISD::NON_EXTLOAD; 10186 break; 10187 } 10188 Val = DAG.getExtLoad( 10189 ExtType, DL, LocVT, Chain, FIN, 10190 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10191 return Val; 10192 } 10193 10194 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10195 const CCValAssign &VA, const SDLoc &DL) { 10196 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10197 "Unexpected VA"); 10198 MachineFunction &MF = DAG.getMachineFunction(); 10199 MachineFrameInfo &MFI = MF.getFrameInfo(); 10200 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10201 10202 if (VA.isMemLoc()) { 10203 // f64 is passed on the stack. 10204 int FI = 10205 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10206 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10207 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10208 MachinePointerInfo::getFixedStack(MF, FI)); 10209 } 10210 10211 assert(VA.isRegLoc() && "Expected register VA assignment"); 10212 10213 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10214 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10215 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10216 SDValue Hi; 10217 if (VA.getLocReg() == RISCV::X17) { 10218 // Second half of f64 is passed on the stack. 10219 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10220 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10221 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10222 MachinePointerInfo::getFixedStack(MF, FI)); 10223 } else { 10224 // Second half of f64 is passed in another GPR. 10225 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10226 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10227 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10228 } 10229 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10230 } 10231 10232 // FastCC has less than 1% performance improvement for some particular 10233 // benchmark. But theoretically, it may has benenfit for some cases. 10234 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10235 unsigned ValNo, MVT ValVT, MVT LocVT, 10236 CCValAssign::LocInfo LocInfo, 10237 ISD::ArgFlagsTy ArgFlags, CCState &State, 10238 bool IsFixed, bool IsRet, Type *OrigTy, 10239 const RISCVTargetLowering &TLI, 10240 Optional<unsigned> FirstMaskArgument) { 10241 10242 // X5 and X6 might be used for save-restore libcall. 10243 static const MCPhysReg GPRList[] = { 10244 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10245 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10246 RISCV::X29, RISCV::X30, RISCV::X31}; 10247 10248 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10249 if (unsigned Reg = State.AllocateReg(GPRList)) { 10250 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10251 return false; 10252 } 10253 } 10254 10255 if (LocVT == MVT::f16) { 10256 static const MCPhysReg FPR16List[] = { 10257 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10258 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10259 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10260 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10261 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10262 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10263 return false; 10264 } 10265 } 10266 10267 if (LocVT == MVT::f32) { 10268 static const MCPhysReg FPR32List[] = { 10269 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10270 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10271 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10272 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10273 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10274 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10275 return false; 10276 } 10277 } 10278 10279 if (LocVT == MVT::f64) { 10280 static const MCPhysReg FPR64List[] = { 10281 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10282 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10283 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10284 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10285 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10286 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10287 return false; 10288 } 10289 } 10290 10291 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10292 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10293 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10294 return false; 10295 } 10296 10297 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10298 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10299 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10300 return false; 10301 } 10302 10303 if (LocVT.isVector()) { 10304 if (unsigned Reg = 10305 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10306 // Fixed-length vectors are located in the corresponding scalable-vector 10307 // container types. 10308 if (ValVT.isFixedLengthVector()) 10309 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10310 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10311 } else { 10312 // Try and pass the address via a "fast" GPR. 10313 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10314 LocInfo = CCValAssign::Indirect; 10315 LocVT = TLI.getSubtarget().getXLenVT(); 10316 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10317 } else if (ValVT.isFixedLengthVector()) { 10318 auto StackAlign = 10319 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10320 unsigned StackOffset = 10321 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10322 State.addLoc( 10323 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10324 } else { 10325 // Can't pass scalable vectors on the stack. 10326 return true; 10327 } 10328 } 10329 10330 return false; 10331 } 10332 10333 return true; // CC didn't match. 10334 } 10335 10336 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10337 CCValAssign::LocInfo LocInfo, 10338 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10339 10340 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10341 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10342 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10343 static const MCPhysReg GPRList[] = { 10344 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10345 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10346 if (unsigned Reg = State.AllocateReg(GPRList)) { 10347 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10348 return false; 10349 } 10350 } 10351 10352 if (LocVT == MVT::f32) { 10353 // Pass in STG registers: F1, ..., F6 10354 // fs0 ... fs5 10355 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10356 RISCV::F18_F, RISCV::F19_F, 10357 RISCV::F20_F, RISCV::F21_F}; 10358 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10359 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10360 return false; 10361 } 10362 } 10363 10364 if (LocVT == MVT::f64) { 10365 // Pass in STG registers: D1, ..., D6 10366 // fs6 ... fs11 10367 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10368 RISCV::F24_D, RISCV::F25_D, 10369 RISCV::F26_D, RISCV::F27_D}; 10370 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10371 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10372 return false; 10373 } 10374 } 10375 10376 report_fatal_error("No registers left in GHC calling convention"); 10377 return true; 10378 } 10379 10380 // Transform physical registers into virtual registers. 10381 SDValue RISCVTargetLowering::LowerFormalArguments( 10382 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10383 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10384 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10385 10386 MachineFunction &MF = DAG.getMachineFunction(); 10387 10388 switch (CallConv) { 10389 default: 10390 report_fatal_error("Unsupported calling convention"); 10391 case CallingConv::C: 10392 case CallingConv::Fast: 10393 break; 10394 case CallingConv::GHC: 10395 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10396 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10397 report_fatal_error( 10398 "GHC calling convention requires the F and D instruction set extensions"); 10399 } 10400 10401 const Function &Func = MF.getFunction(); 10402 if (Func.hasFnAttribute("interrupt")) { 10403 if (!Func.arg_empty()) 10404 report_fatal_error( 10405 "Functions with the interrupt attribute cannot have arguments!"); 10406 10407 StringRef Kind = 10408 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10409 10410 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10411 report_fatal_error( 10412 "Function interrupt attribute argument not supported!"); 10413 } 10414 10415 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10416 MVT XLenVT = Subtarget.getXLenVT(); 10417 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10418 // Used with vargs to acumulate store chains. 10419 std::vector<SDValue> OutChains; 10420 10421 // Assign locations to all of the incoming arguments. 10422 SmallVector<CCValAssign, 16> ArgLocs; 10423 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10424 10425 if (CallConv == CallingConv::GHC) 10426 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10427 else 10428 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10429 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10430 : CC_RISCV); 10431 10432 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10433 CCValAssign &VA = ArgLocs[i]; 10434 SDValue ArgValue; 10435 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10436 // case. 10437 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10438 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10439 else if (VA.isRegLoc()) 10440 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10441 else 10442 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10443 10444 if (VA.getLocInfo() == CCValAssign::Indirect) { 10445 // If the original argument was split and passed by reference (e.g. i128 10446 // on RV32), we need to load all parts of it here (using the same 10447 // address). Vectors may be partly split to registers and partly to the 10448 // stack, in which case the base address is partly offset and subsequent 10449 // stores are relative to that. 10450 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10451 MachinePointerInfo())); 10452 unsigned ArgIndex = Ins[i].OrigArgIndex; 10453 unsigned ArgPartOffset = Ins[i].PartOffset; 10454 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10455 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10456 CCValAssign &PartVA = ArgLocs[i + 1]; 10457 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10458 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10459 if (PartVA.getValVT().isScalableVector()) 10460 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10461 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10462 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10463 MachinePointerInfo())); 10464 ++i; 10465 } 10466 continue; 10467 } 10468 InVals.push_back(ArgValue); 10469 } 10470 10471 if (IsVarArg) { 10472 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10473 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10474 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10475 MachineFrameInfo &MFI = MF.getFrameInfo(); 10476 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10477 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10478 10479 // Offset of the first variable argument from stack pointer, and size of 10480 // the vararg save area. For now, the varargs save area is either zero or 10481 // large enough to hold a0-a7. 10482 int VaArgOffset, VarArgsSaveSize; 10483 10484 // If all registers are allocated, then all varargs must be passed on the 10485 // stack and we don't need to save any argregs. 10486 if (ArgRegs.size() == Idx) { 10487 VaArgOffset = CCInfo.getNextStackOffset(); 10488 VarArgsSaveSize = 0; 10489 } else { 10490 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10491 VaArgOffset = -VarArgsSaveSize; 10492 } 10493 10494 // Record the frame index of the first variable argument 10495 // which is a value necessary to VASTART. 10496 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10497 RVFI->setVarArgsFrameIndex(FI); 10498 10499 // If saving an odd number of registers then create an extra stack slot to 10500 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10501 // offsets to even-numbered registered remain 2*XLEN-aligned. 10502 if (Idx % 2) { 10503 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10504 VarArgsSaveSize += XLenInBytes; 10505 } 10506 10507 // Copy the integer registers that may have been used for passing varargs 10508 // to the vararg save area. 10509 for (unsigned I = Idx; I < ArgRegs.size(); 10510 ++I, VaArgOffset += XLenInBytes) { 10511 const Register Reg = RegInfo.createVirtualRegister(RC); 10512 RegInfo.addLiveIn(ArgRegs[I], Reg); 10513 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10514 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10515 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10516 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10517 MachinePointerInfo::getFixedStack(MF, FI)); 10518 cast<StoreSDNode>(Store.getNode()) 10519 ->getMemOperand() 10520 ->setValue((Value *)nullptr); 10521 OutChains.push_back(Store); 10522 } 10523 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10524 } 10525 10526 // All stores are grouped in one node to allow the matching between 10527 // the size of Ins and InVals. This only happens for vararg functions. 10528 if (!OutChains.empty()) { 10529 OutChains.push_back(Chain); 10530 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10531 } 10532 10533 return Chain; 10534 } 10535 10536 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10537 /// for tail call optimization. 10538 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10539 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10540 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10541 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10542 10543 auto &Callee = CLI.Callee; 10544 auto CalleeCC = CLI.CallConv; 10545 auto &Outs = CLI.Outs; 10546 auto &Caller = MF.getFunction(); 10547 auto CallerCC = Caller.getCallingConv(); 10548 10549 // Exception-handling functions need a special set of instructions to 10550 // indicate a return to the hardware. Tail-calling another function would 10551 // probably break this. 10552 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10553 // should be expanded as new function attributes are introduced. 10554 if (Caller.hasFnAttribute("interrupt")) 10555 return false; 10556 10557 // Do not tail call opt if the stack is used to pass parameters. 10558 if (CCInfo.getNextStackOffset() != 0) 10559 return false; 10560 10561 // Do not tail call opt if any parameters need to be passed indirectly. 10562 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10563 // passed indirectly. So the address of the value will be passed in a 10564 // register, or if not available, then the address is put on the stack. In 10565 // order to pass indirectly, space on the stack often needs to be allocated 10566 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10567 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10568 // are passed CCValAssign::Indirect. 10569 for (auto &VA : ArgLocs) 10570 if (VA.getLocInfo() == CCValAssign::Indirect) 10571 return false; 10572 10573 // Do not tail call opt if either caller or callee uses struct return 10574 // semantics. 10575 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10576 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10577 if (IsCallerStructRet || IsCalleeStructRet) 10578 return false; 10579 10580 // Externally-defined functions with weak linkage should not be 10581 // tail-called. The behaviour of branch instructions in this situation (as 10582 // used for tail calls) is implementation-defined, so we cannot rely on the 10583 // linker replacing the tail call with a return. 10584 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10585 const GlobalValue *GV = G->getGlobal(); 10586 if (GV->hasExternalWeakLinkage()) 10587 return false; 10588 } 10589 10590 // The callee has to preserve all registers the caller needs to preserve. 10591 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10592 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10593 if (CalleeCC != CallerCC) { 10594 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10595 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10596 return false; 10597 } 10598 10599 // Byval parameters hand the function a pointer directly into the stack area 10600 // we want to reuse during a tail call. Working around this *is* possible 10601 // but less efficient and uglier in LowerCall. 10602 for (auto &Arg : Outs) 10603 if (Arg.Flags.isByVal()) 10604 return false; 10605 10606 return true; 10607 } 10608 10609 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10610 return DAG.getDataLayout().getPrefTypeAlign( 10611 VT.getTypeForEVT(*DAG.getContext())); 10612 } 10613 10614 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10615 // and output parameter nodes. 10616 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10617 SmallVectorImpl<SDValue> &InVals) const { 10618 SelectionDAG &DAG = CLI.DAG; 10619 SDLoc &DL = CLI.DL; 10620 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10621 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10622 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10623 SDValue Chain = CLI.Chain; 10624 SDValue Callee = CLI.Callee; 10625 bool &IsTailCall = CLI.IsTailCall; 10626 CallingConv::ID CallConv = CLI.CallConv; 10627 bool IsVarArg = CLI.IsVarArg; 10628 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10629 MVT XLenVT = Subtarget.getXLenVT(); 10630 10631 MachineFunction &MF = DAG.getMachineFunction(); 10632 10633 // Analyze the operands of the call, assigning locations to each operand. 10634 SmallVector<CCValAssign, 16> ArgLocs; 10635 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10636 10637 if (CallConv == CallingConv::GHC) 10638 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10639 else 10640 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10641 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10642 : CC_RISCV); 10643 10644 // Check if it's really possible to do a tail call. 10645 if (IsTailCall) 10646 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10647 10648 if (IsTailCall) 10649 ++NumTailCalls; 10650 else if (CLI.CB && CLI.CB->isMustTailCall()) 10651 report_fatal_error("failed to perform tail call elimination on a call " 10652 "site marked musttail"); 10653 10654 // Get a count of how many bytes are to be pushed on the stack. 10655 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10656 10657 // Create local copies for byval args 10658 SmallVector<SDValue, 8> ByValArgs; 10659 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10660 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10661 if (!Flags.isByVal()) 10662 continue; 10663 10664 SDValue Arg = OutVals[i]; 10665 unsigned Size = Flags.getByValSize(); 10666 Align Alignment = Flags.getNonZeroByValAlign(); 10667 10668 int FI = 10669 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10670 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10671 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10672 10673 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10674 /*IsVolatile=*/false, 10675 /*AlwaysInline=*/false, IsTailCall, 10676 MachinePointerInfo(), MachinePointerInfo()); 10677 ByValArgs.push_back(FIPtr); 10678 } 10679 10680 if (!IsTailCall) 10681 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10682 10683 // Copy argument values to their designated locations. 10684 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10685 SmallVector<SDValue, 8> MemOpChains; 10686 SDValue StackPtr; 10687 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10688 CCValAssign &VA = ArgLocs[i]; 10689 SDValue ArgValue = OutVals[i]; 10690 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10691 10692 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10693 bool IsF64OnRV32DSoftABI = 10694 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10695 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10696 SDValue SplitF64 = DAG.getNode( 10697 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10698 SDValue Lo = SplitF64.getValue(0); 10699 SDValue Hi = SplitF64.getValue(1); 10700 10701 Register RegLo = VA.getLocReg(); 10702 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10703 10704 if (RegLo == RISCV::X17) { 10705 // Second half of f64 is passed on the stack. 10706 // Work out the address of the stack slot. 10707 if (!StackPtr.getNode()) 10708 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10709 // Emit the store. 10710 MemOpChains.push_back( 10711 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10712 } else { 10713 // Second half of f64 is passed in another GPR. 10714 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10715 Register RegHigh = RegLo + 1; 10716 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10717 } 10718 continue; 10719 } 10720 10721 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10722 // as any other MemLoc. 10723 10724 // Promote the value if needed. 10725 // For now, only handle fully promoted and indirect arguments. 10726 if (VA.getLocInfo() == CCValAssign::Indirect) { 10727 // Store the argument in a stack slot and pass its address. 10728 Align StackAlign = 10729 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10730 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10731 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10732 // If the original argument was split (e.g. i128), we need 10733 // to store the required parts of it here (and pass just one address). 10734 // Vectors may be partly split to registers and partly to the stack, in 10735 // which case the base address is partly offset and subsequent stores are 10736 // relative to that. 10737 unsigned ArgIndex = Outs[i].OrigArgIndex; 10738 unsigned ArgPartOffset = Outs[i].PartOffset; 10739 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10740 // Calculate the total size to store. We don't have access to what we're 10741 // actually storing other than performing the loop and collecting the 10742 // info. 10743 SmallVector<std::pair<SDValue, SDValue>> Parts; 10744 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10745 SDValue PartValue = OutVals[i + 1]; 10746 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10747 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10748 EVT PartVT = PartValue.getValueType(); 10749 if (PartVT.isScalableVector()) 10750 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10751 StoredSize += PartVT.getStoreSize(); 10752 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10753 Parts.push_back(std::make_pair(PartValue, Offset)); 10754 ++i; 10755 } 10756 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10757 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10758 MemOpChains.push_back( 10759 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10760 MachinePointerInfo::getFixedStack(MF, FI))); 10761 for (const auto &Part : Parts) { 10762 SDValue PartValue = Part.first; 10763 SDValue PartOffset = Part.second; 10764 SDValue Address = 10765 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10766 MemOpChains.push_back( 10767 DAG.getStore(Chain, DL, PartValue, Address, 10768 MachinePointerInfo::getFixedStack(MF, FI))); 10769 } 10770 ArgValue = SpillSlot; 10771 } else { 10772 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10773 } 10774 10775 // Use local copy if it is a byval arg. 10776 if (Flags.isByVal()) 10777 ArgValue = ByValArgs[j++]; 10778 10779 if (VA.isRegLoc()) { 10780 // Queue up the argument copies and emit them at the end. 10781 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10782 } else { 10783 assert(VA.isMemLoc() && "Argument not register or memory"); 10784 assert(!IsTailCall && "Tail call not allowed if stack is used " 10785 "for passing parameters"); 10786 10787 // Work out the address of the stack slot. 10788 if (!StackPtr.getNode()) 10789 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10790 SDValue Address = 10791 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10792 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10793 10794 // Emit the store. 10795 MemOpChains.push_back( 10796 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10797 } 10798 } 10799 10800 // Join the stores, which are independent of one another. 10801 if (!MemOpChains.empty()) 10802 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10803 10804 SDValue Glue; 10805 10806 // Build a sequence of copy-to-reg nodes, chained and glued together. 10807 for (auto &Reg : RegsToPass) { 10808 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10809 Glue = Chain.getValue(1); 10810 } 10811 10812 // Validate that none of the argument registers have been marked as 10813 // reserved, if so report an error. Do the same for the return address if this 10814 // is not a tailcall. 10815 validateCCReservedRegs(RegsToPass, MF); 10816 if (!IsTailCall && 10817 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10818 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10819 MF.getFunction(), 10820 "Return address register required, but has been reserved."}); 10821 10822 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10823 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10824 // split it and then direct call can be matched by PseudoCALL. 10825 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10826 const GlobalValue *GV = S->getGlobal(); 10827 10828 unsigned OpFlags = RISCVII::MO_CALL; 10829 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10830 OpFlags = RISCVII::MO_PLT; 10831 10832 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10833 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10834 unsigned OpFlags = RISCVII::MO_CALL; 10835 10836 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10837 nullptr)) 10838 OpFlags = RISCVII::MO_PLT; 10839 10840 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10841 } 10842 10843 // The first call operand is the chain and the second is the target address. 10844 SmallVector<SDValue, 8> Ops; 10845 Ops.push_back(Chain); 10846 Ops.push_back(Callee); 10847 10848 // Add argument registers to the end of the list so that they are 10849 // known live into the call. 10850 for (auto &Reg : RegsToPass) 10851 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10852 10853 if (!IsTailCall) { 10854 // Add a register mask operand representing the call-preserved registers. 10855 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10856 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10857 assert(Mask && "Missing call preserved mask for calling convention"); 10858 Ops.push_back(DAG.getRegisterMask(Mask)); 10859 } 10860 10861 // Glue the call to the argument copies, if any. 10862 if (Glue.getNode()) 10863 Ops.push_back(Glue); 10864 10865 // Emit the call. 10866 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10867 10868 if (IsTailCall) { 10869 MF.getFrameInfo().setHasTailCall(); 10870 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10871 } 10872 10873 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10874 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10875 Glue = Chain.getValue(1); 10876 10877 // Mark the end of the call, which is glued to the call itself. 10878 Chain = DAG.getCALLSEQ_END(Chain, 10879 DAG.getConstant(NumBytes, DL, PtrVT, true), 10880 DAG.getConstant(0, DL, PtrVT, true), 10881 Glue, DL); 10882 Glue = Chain.getValue(1); 10883 10884 // Assign locations to each value returned by this call. 10885 SmallVector<CCValAssign, 16> RVLocs; 10886 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10887 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10888 10889 // Copy all of the result registers out of their specified physreg. 10890 for (auto &VA : RVLocs) { 10891 // Copy the value out 10892 SDValue RetValue = 10893 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10894 // Glue the RetValue to the end of the call sequence 10895 Chain = RetValue.getValue(1); 10896 Glue = RetValue.getValue(2); 10897 10898 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10899 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10900 SDValue RetValue2 = 10901 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10902 Chain = RetValue2.getValue(1); 10903 Glue = RetValue2.getValue(2); 10904 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10905 RetValue2); 10906 } 10907 10908 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10909 10910 InVals.push_back(RetValue); 10911 } 10912 10913 return Chain; 10914 } 10915 10916 bool RISCVTargetLowering::CanLowerReturn( 10917 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10918 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10919 SmallVector<CCValAssign, 16> RVLocs; 10920 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10921 10922 Optional<unsigned> FirstMaskArgument; 10923 if (Subtarget.hasVInstructions()) 10924 FirstMaskArgument = preAssignMask(Outs); 10925 10926 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10927 MVT VT = Outs[i].VT; 10928 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10929 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10930 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10931 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10932 *this, FirstMaskArgument)) 10933 return false; 10934 } 10935 return true; 10936 } 10937 10938 SDValue 10939 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10940 bool IsVarArg, 10941 const SmallVectorImpl<ISD::OutputArg> &Outs, 10942 const SmallVectorImpl<SDValue> &OutVals, 10943 const SDLoc &DL, SelectionDAG &DAG) const { 10944 const MachineFunction &MF = DAG.getMachineFunction(); 10945 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10946 10947 // Stores the assignment of the return value to a location. 10948 SmallVector<CCValAssign, 16> RVLocs; 10949 10950 // Info about the registers and stack slot. 10951 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10952 *DAG.getContext()); 10953 10954 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10955 nullptr, CC_RISCV); 10956 10957 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10958 report_fatal_error("GHC functions return void only"); 10959 10960 SDValue Glue; 10961 SmallVector<SDValue, 4> RetOps(1, Chain); 10962 10963 // Copy the result values into the output registers. 10964 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10965 SDValue Val = OutVals[i]; 10966 CCValAssign &VA = RVLocs[i]; 10967 assert(VA.isRegLoc() && "Can only return in registers!"); 10968 10969 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10970 // Handle returning f64 on RV32D with a soft float ABI. 10971 assert(VA.isRegLoc() && "Expected return via registers"); 10972 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10973 DAG.getVTList(MVT::i32, MVT::i32), Val); 10974 SDValue Lo = SplitF64.getValue(0); 10975 SDValue Hi = SplitF64.getValue(1); 10976 Register RegLo = VA.getLocReg(); 10977 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10978 Register RegHi = RegLo + 1; 10979 10980 if (STI.isRegisterReservedByUser(RegLo) || 10981 STI.isRegisterReservedByUser(RegHi)) 10982 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10983 MF.getFunction(), 10984 "Return value register required, but has been reserved."}); 10985 10986 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10987 Glue = Chain.getValue(1); 10988 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10989 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10990 Glue = Chain.getValue(1); 10991 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10992 } else { 10993 // Handle a 'normal' return. 10994 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10995 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10996 10997 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10998 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10999 MF.getFunction(), 11000 "Return value register required, but has been reserved."}); 11001 11002 // Guarantee that all emitted copies are stuck together. 11003 Glue = Chain.getValue(1); 11004 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11005 } 11006 } 11007 11008 RetOps[0] = Chain; // Update chain. 11009 11010 // Add the glue node if we have it. 11011 if (Glue.getNode()) { 11012 RetOps.push_back(Glue); 11013 } 11014 11015 unsigned RetOpc = RISCVISD::RET_FLAG; 11016 // Interrupt service routines use different return instructions. 11017 const Function &Func = DAG.getMachineFunction().getFunction(); 11018 if (Func.hasFnAttribute("interrupt")) { 11019 if (!Func.getReturnType()->isVoidTy()) 11020 report_fatal_error( 11021 "Functions with the interrupt attribute must have void return type!"); 11022 11023 MachineFunction &MF = DAG.getMachineFunction(); 11024 StringRef Kind = 11025 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11026 11027 if (Kind == "user") 11028 RetOpc = RISCVISD::URET_FLAG; 11029 else if (Kind == "supervisor") 11030 RetOpc = RISCVISD::SRET_FLAG; 11031 else 11032 RetOpc = RISCVISD::MRET_FLAG; 11033 } 11034 11035 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11036 } 11037 11038 void RISCVTargetLowering::validateCCReservedRegs( 11039 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11040 MachineFunction &MF) const { 11041 const Function &F = MF.getFunction(); 11042 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11043 11044 if (llvm::any_of(Regs, [&STI](auto Reg) { 11045 return STI.isRegisterReservedByUser(Reg.first); 11046 })) 11047 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11048 F, "Argument register required, but has been reserved."}); 11049 } 11050 11051 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11052 return CI->isTailCall(); 11053 } 11054 11055 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11056 #define NODE_NAME_CASE(NODE) \ 11057 case RISCVISD::NODE: \ 11058 return "RISCVISD::" #NODE; 11059 // clang-format off 11060 switch ((RISCVISD::NodeType)Opcode) { 11061 case RISCVISD::FIRST_NUMBER: 11062 break; 11063 NODE_NAME_CASE(RET_FLAG) 11064 NODE_NAME_CASE(URET_FLAG) 11065 NODE_NAME_CASE(SRET_FLAG) 11066 NODE_NAME_CASE(MRET_FLAG) 11067 NODE_NAME_CASE(CALL) 11068 NODE_NAME_CASE(SELECT_CC) 11069 NODE_NAME_CASE(BR_CC) 11070 NODE_NAME_CASE(BuildPairF64) 11071 NODE_NAME_CASE(SplitF64) 11072 NODE_NAME_CASE(TAIL) 11073 NODE_NAME_CASE(MULHSU) 11074 NODE_NAME_CASE(SLLW) 11075 NODE_NAME_CASE(SRAW) 11076 NODE_NAME_CASE(SRLW) 11077 NODE_NAME_CASE(DIVW) 11078 NODE_NAME_CASE(DIVUW) 11079 NODE_NAME_CASE(REMUW) 11080 NODE_NAME_CASE(ROLW) 11081 NODE_NAME_CASE(RORW) 11082 NODE_NAME_CASE(CLZW) 11083 NODE_NAME_CASE(CTZW) 11084 NODE_NAME_CASE(FSLW) 11085 NODE_NAME_CASE(FSRW) 11086 NODE_NAME_CASE(FSL) 11087 NODE_NAME_CASE(FSR) 11088 NODE_NAME_CASE(FMV_H_X) 11089 NODE_NAME_CASE(FMV_X_ANYEXTH) 11090 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11091 NODE_NAME_CASE(FMV_W_X_RV64) 11092 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11093 NODE_NAME_CASE(FCVT_X) 11094 NODE_NAME_CASE(FCVT_XU) 11095 NODE_NAME_CASE(FCVT_W_RV64) 11096 NODE_NAME_CASE(FCVT_WU_RV64) 11097 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11098 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11099 NODE_NAME_CASE(READ_CYCLE_WIDE) 11100 NODE_NAME_CASE(GREV) 11101 NODE_NAME_CASE(GREVW) 11102 NODE_NAME_CASE(GORC) 11103 NODE_NAME_CASE(GORCW) 11104 NODE_NAME_CASE(SHFL) 11105 NODE_NAME_CASE(SHFLW) 11106 NODE_NAME_CASE(UNSHFL) 11107 NODE_NAME_CASE(UNSHFLW) 11108 NODE_NAME_CASE(BFP) 11109 NODE_NAME_CASE(BFPW) 11110 NODE_NAME_CASE(BCOMPRESS) 11111 NODE_NAME_CASE(BCOMPRESSW) 11112 NODE_NAME_CASE(BDECOMPRESS) 11113 NODE_NAME_CASE(BDECOMPRESSW) 11114 NODE_NAME_CASE(VMV_V_X_VL) 11115 NODE_NAME_CASE(VFMV_V_F_VL) 11116 NODE_NAME_CASE(VMV_X_S) 11117 NODE_NAME_CASE(VMV_S_X_VL) 11118 NODE_NAME_CASE(VFMV_S_F_VL) 11119 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11120 NODE_NAME_CASE(READ_VLENB) 11121 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11122 NODE_NAME_CASE(VSLIDEUP_VL) 11123 NODE_NAME_CASE(VSLIDE1UP_VL) 11124 NODE_NAME_CASE(VSLIDEDOWN_VL) 11125 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11126 NODE_NAME_CASE(VID_VL) 11127 NODE_NAME_CASE(VFNCVT_ROD_VL) 11128 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11129 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11130 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11131 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11132 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11133 NODE_NAME_CASE(VECREDUCE_AND_VL) 11134 NODE_NAME_CASE(VECREDUCE_OR_VL) 11135 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11136 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11137 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11138 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11139 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11140 NODE_NAME_CASE(ADD_VL) 11141 NODE_NAME_CASE(AND_VL) 11142 NODE_NAME_CASE(MUL_VL) 11143 NODE_NAME_CASE(OR_VL) 11144 NODE_NAME_CASE(SDIV_VL) 11145 NODE_NAME_CASE(SHL_VL) 11146 NODE_NAME_CASE(SREM_VL) 11147 NODE_NAME_CASE(SRA_VL) 11148 NODE_NAME_CASE(SRL_VL) 11149 NODE_NAME_CASE(SUB_VL) 11150 NODE_NAME_CASE(UDIV_VL) 11151 NODE_NAME_CASE(UREM_VL) 11152 NODE_NAME_CASE(XOR_VL) 11153 NODE_NAME_CASE(SADDSAT_VL) 11154 NODE_NAME_CASE(UADDSAT_VL) 11155 NODE_NAME_CASE(SSUBSAT_VL) 11156 NODE_NAME_CASE(USUBSAT_VL) 11157 NODE_NAME_CASE(FADD_VL) 11158 NODE_NAME_CASE(FSUB_VL) 11159 NODE_NAME_CASE(FMUL_VL) 11160 NODE_NAME_CASE(FDIV_VL) 11161 NODE_NAME_CASE(FNEG_VL) 11162 NODE_NAME_CASE(FABS_VL) 11163 NODE_NAME_CASE(FSQRT_VL) 11164 NODE_NAME_CASE(FMA_VL) 11165 NODE_NAME_CASE(FCOPYSIGN_VL) 11166 NODE_NAME_CASE(SMIN_VL) 11167 NODE_NAME_CASE(SMAX_VL) 11168 NODE_NAME_CASE(UMIN_VL) 11169 NODE_NAME_CASE(UMAX_VL) 11170 NODE_NAME_CASE(FMINNUM_VL) 11171 NODE_NAME_CASE(FMAXNUM_VL) 11172 NODE_NAME_CASE(MULHS_VL) 11173 NODE_NAME_CASE(MULHU_VL) 11174 NODE_NAME_CASE(FP_TO_SINT_VL) 11175 NODE_NAME_CASE(FP_TO_UINT_VL) 11176 NODE_NAME_CASE(SINT_TO_FP_VL) 11177 NODE_NAME_CASE(UINT_TO_FP_VL) 11178 NODE_NAME_CASE(FP_EXTEND_VL) 11179 NODE_NAME_CASE(FP_ROUND_VL) 11180 NODE_NAME_CASE(VWMUL_VL) 11181 NODE_NAME_CASE(VWMULU_VL) 11182 NODE_NAME_CASE(VWMULSU_VL) 11183 NODE_NAME_CASE(VWADD_VL) 11184 NODE_NAME_CASE(VWADDU_VL) 11185 NODE_NAME_CASE(VWSUB_VL) 11186 NODE_NAME_CASE(VWSUBU_VL) 11187 NODE_NAME_CASE(VWADD_W_VL) 11188 NODE_NAME_CASE(VWADDU_W_VL) 11189 NODE_NAME_CASE(VWSUB_W_VL) 11190 NODE_NAME_CASE(VWSUBU_W_VL) 11191 NODE_NAME_CASE(SETCC_VL) 11192 NODE_NAME_CASE(VSELECT_VL) 11193 NODE_NAME_CASE(VP_MERGE_VL) 11194 NODE_NAME_CASE(VMAND_VL) 11195 NODE_NAME_CASE(VMOR_VL) 11196 NODE_NAME_CASE(VMXOR_VL) 11197 NODE_NAME_CASE(VMCLR_VL) 11198 NODE_NAME_CASE(VMSET_VL) 11199 NODE_NAME_CASE(VRGATHER_VX_VL) 11200 NODE_NAME_CASE(VRGATHER_VV_VL) 11201 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11202 NODE_NAME_CASE(VSEXT_VL) 11203 NODE_NAME_CASE(VZEXT_VL) 11204 NODE_NAME_CASE(VCPOP_VL) 11205 NODE_NAME_CASE(READ_CSR) 11206 NODE_NAME_CASE(WRITE_CSR) 11207 NODE_NAME_CASE(SWAP_CSR) 11208 } 11209 // clang-format on 11210 return nullptr; 11211 #undef NODE_NAME_CASE 11212 } 11213 11214 /// getConstraintType - Given a constraint letter, return the type of 11215 /// constraint it is for this target. 11216 RISCVTargetLowering::ConstraintType 11217 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11218 if (Constraint.size() == 1) { 11219 switch (Constraint[0]) { 11220 default: 11221 break; 11222 case 'f': 11223 return C_RegisterClass; 11224 case 'I': 11225 case 'J': 11226 case 'K': 11227 return C_Immediate; 11228 case 'A': 11229 return C_Memory; 11230 case 'S': // A symbolic address 11231 return C_Other; 11232 } 11233 } else { 11234 if (Constraint == "vr" || Constraint == "vm") 11235 return C_RegisterClass; 11236 } 11237 return TargetLowering::getConstraintType(Constraint); 11238 } 11239 11240 std::pair<unsigned, const TargetRegisterClass *> 11241 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11242 StringRef Constraint, 11243 MVT VT) const { 11244 // First, see if this is a constraint that directly corresponds to a 11245 // RISCV register class. 11246 if (Constraint.size() == 1) { 11247 switch (Constraint[0]) { 11248 case 'r': 11249 // TODO: Support fixed vectors up to XLen for P extension? 11250 if (VT.isVector()) 11251 break; 11252 return std::make_pair(0U, &RISCV::GPRRegClass); 11253 case 'f': 11254 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11255 return std::make_pair(0U, &RISCV::FPR16RegClass); 11256 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11257 return std::make_pair(0U, &RISCV::FPR32RegClass); 11258 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11259 return std::make_pair(0U, &RISCV::FPR64RegClass); 11260 break; 11261 default: 11262 break; 11263 } 11264 } else if (Constraint == "vr") { 11265 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11266 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11267 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11268 return std::make_pair(0U, RC); 11269 } 11270 } else if (Constraint == "vm") { 11271 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11272 return std::make_pair(0U, &RISCV::VMV0RegClass); 11273 } 11274 11275 // Clang will correctly decode the usage of register name aliases into their 11276 // official names. However, other frontends like `rustc` do not. This allows 11277 // users of these frontends to use the ABI names for registers in LLVM-style 11278 // register constraints. 11279 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11280 .Case("{zero}", RISCV::X0) 11281 .Case("{ra}", RISCV::X1) 11282 .Case("{sp}", RISCV::X2) 11283 .Case("{gp}", RISCV::X3) 11284 .Case("{tp}", RISCV::X4) 11285 .Case("{t0}", RISCV::X5) 11286 .Case("{t1}", RISCV::X6) 11287 .Case("{t2}", RISCV::X7) 11288 .Cases("{s0}", "{fp}", RISCV::X8) 11289 .Case("{s1}", RISCV::X9) 11290 .Case("{a0}", RISCV::X10) 11291 .Case("{a1}", RISCV::X11) 11292 .Case("{a2}", RISCV::X12) 11293 .Case("{a3}", RISCV::X13) 11294 .Case("{a4}", RISCV::X14) 11295 .Case("{a5}", RISCV::X15) 11296 .Case("{a6}", RISCV::X16) 11297 .Case("{a7}", RISCV::X17) 11298 .Case("{s2}", RISCV::X18) 11299 .Case("{s3}", RISCV::X19) 11300 .Case("{s4}", RISCV::X20) 11301 .Case("{s5}", RISCV::X21) 11302 .Case("{s6}", RISCV::X22) 11303 .Case("{s7}", RISCV::X23) 11304 .Case("{s8}", RISCV::X24) 11305 .Case("{s9}", RISCV::X25) 11306 .Case("{s10}", RISCV::X26) 11307 .Case("{s11}", RISCV::X27) 11308 .Case("{t3}", RISCV::X28) 11309 .Case("{t4}", RISCV::X29) 11310 .Case("{t5}", RISCV::X30) 11311 .Case("{t6}", RISCV::X31) 11312 .Default(RISCV::NoRegister); 11313 if (XRegFromAlias != RISCV::NoRegister) 11314 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11315 11316 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11317 // TableGen record rather than the AsmName to choose registers for InlineAsm 11318 // constraints, plus we want to match those names to the widest floating point 11319 // register type available, manually select floating point registers here. 11320 // 11321 // The second case is the ABI name of the register, so that frontends can also 11322 // use the ABI names in register constraint lists. 11323 if (Subtarget.hasStdExtF()) { 11324 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11325 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11326 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11327 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11328 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11329 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11330 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11331 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11332 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11333 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11334 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11335 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11336 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11337 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11338 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11339 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11340 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11341 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11342 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11343 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11344 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11345 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11346 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11347 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11348 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11349 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11350 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11351 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11352 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11353 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11354 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11355 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11356 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11357 .Default(RISCV::NoRegister); 11358 if (FReg != RISCV::NoRegister) { 11359 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11360 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11361 unsigned RegNo = FReg - RISCV::F0_F; 11362 unsigned DReg = RISCV::F0_D + RegNo; 11363 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11364 } 11365 if (VT == MVT::f32 || VT == MVT::Other) 11366 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11367 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11368 unsigned RegNo = FReg - RISCV::F0_F; 11369 unsigned HReg = RISCV::F0_H + RegNo; 11370 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11371 } 11372 } 11373 } 11374 11375 if (Subtarget.hasVInstructions()) { 11376 Register VReg = StringSwitch<Register>(Constraint.lower()) 11377 .Case("{v0}", RISCV::V0) 11378 .Case("{v1}", RISCV::V1) 11379 .Case("{v2}", RISCV::V2) 11380 .Case("{v3}", RISCV::V3) 11381 .Case("{v4}", RISCV::V4) 11382 .Case("{v5}", RISCV::V5) 11383 .Case("{v6}", RISCV::V6) 11384 .Case("{v7}", RISCV::V7) 11385 .Case("{v8}", RISCV::V8) 11386 .Case("{v9}", RISCV::V9) 11387 .Case("{v10}", RISCV::V10) 11388 .Case("{v11}", RISCV::V11) 11389 .Case("{v12}", RISCV::V12) 11390 .Case("{v13}", RISCV::V13) 11391 .Case("{v14}", RISCV::V14) 11392 .Case("{v15}", RISCV::V15) 11393 .Case("{v16}", RISCV::V16) 11394 .Case("{v17}", RISCV::V17) 11395 .Case("{v18}", RISCV::V18) 11396 .Case("{v19}", RISCV::V19) 11397 .Case("{v20}", RISCV::V20) 11398 .Case("{v21}", RISCV::V21) 11399 .Case("{v22}", RISCV::V22) 11400 .Case("{v23}", RISCV::V23) 11401 .Case("{v24}", RISCV::V24) 11402 .Case("{v25}", RISCV::V25) 11403 .Case("{v26}", RISCV::V26) 11404 .Case("{v27}", RISCV::V27) 11405 .Case("{v28}", RISCV::V28) 11406 .Case("{v29}", RISCV::V29) 11407 .Case("{v30}", RISCV::V30) 11408 .Case("{v31}", RISCV::V31) 11409 .Default(RISCV::NoRegister); 11410 if (VReg != RISCV::NoRegister) { 11411 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11412 return std::make_pair(VReg, &RISCV::VMRegClass); 11413 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11414 return std::make_pair(VReg, &RISCV::VRRegClass); 11415 for (const auto *RC : 11416 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11417 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11418 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11419 return std::make_pair(VReg, RC); 11420 } 11421 } 11422 } 11423 } 11424 11425 std::pair<Register, const TargetRegisterClass *> Res = 11426 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11427 11428 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11429 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11430 // Subtarget into account. 11431 if (Res.second == &RISCV::GPRF16RegClass || 11432 Res.second == &RISCV::GPRF32RegClass || 11433 Res.second == &RISCV::GPRF64RegClass) 11434 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11435 11436 return Res; 11437 } 11438 11439 unsigned 11440 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11441 // Currently only support length 1 constraints. 11442 if (ConstraintCode.size() == 1) { 11443 switch (ConstraintCode[0]) { 11444 case 'A': 11445 return InlineAsm::Constraint_A; 11446 default: 11447 break; 11448 } 11449 } 11450 11451 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11452 } 11453 11454 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11455 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11456 SelectionDAG &DAG) const { 11457 // Currently only support length 1 constraints. 11458 if (Constraint.length() == 1) { 11459 switch (Constraint[0]) { 11460 case 'I': 11461 // Validate & create a 12-bit signed immediate operand. 11462 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11463 uint64_t CVal = C->getSExtValue(); 11464 if (isInt<12>(CVal)) 11465 Ops.push_back( 11466 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11467 } 11468 return; 11469 case 'J': 11470 // Validate & create an integer zero operand. 11471 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11472 if (C->getZExtValue() == 0) 11473 Ops.push_back( 11474 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11475 return; 11476 case 'K': 11477 // Validate & create a 5-bit unsigned immediate operand. 11478 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11479 uint64_t CVal = C->getZExtValue(); 11480 if (isUInt<5>(CVal)) 11481 Ops.push_back( 11482 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11483 } 11484 return; 11485 case 'S': 11486 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11487 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11488 GA->getValueType(0))); 11489 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11490 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11491 BA->getValueType(0))); 11492 } 11493 return; 11494 default: 11495 break; 11496 } 11497 } 11498 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11499 } 11500 11501 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11502 Instruction *Inst, 11503 AtomicOrdering Ord) const { 11504 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11505 return Builder.CreateFence(Ord); 11506 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11507 return Builder.CreateFence(AtomicOrdering::Release); 11508 return nullptr; 11509 } 11510 11511 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11512 Instruction *Inst, 11513 AtomicOrdering Ord) const { 11514 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11515 return Builder.CreateFence(AtomicOrdering::Acquire); 11516 return nullptr; 11517 } 11518 11519 TargetLowering::AtomicExpansionKind 11520 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11521 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11522 // point operations can't be used in an lr/sc sequence without breaking the 11523 // forward-progress guarantee. 11524 if (AI->isFloatingPointOperation()) 11525 return AtomicExpansionKind::CmpXChg; 11526 11527 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11528 if (Size == 8 || Size == 16) 11529 return AtomicExpansionKind::MaskedIntrinsic; 11530 return AtomicExpansionKind::None; 11531 } 11532 11533 static Intrinsic::ID 11534 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11535 if (XLen == 32) { 11536 switch (BinOp) { 11537 default: 11538 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11539 case AtomicRMWInst::Xchg: 11540 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11541 case AtomicRMWInst::Add: 11542 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11543 case AtomicRMWInst::Sub: 11544 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11545 case AtomicRMWInst::Nand: 11546 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11547 case AtomicRMWInst::Max: 11548 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11549 case AtomicRMWInst::Min: 11550 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11551 case AtomicRMWInst::UMax: 11552 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11553 case AtomicRMWInst::UMin: 11554 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11555 } 11556 } 11557 11558 if (XLen == 64) { 11559 switch (BinOp) { 11560 default: 11561 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11562 case AtomicRMWInst::Xchg: 11563 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11564 case AtomicRMWInst::Add: 11565 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11566 case AtomicRMWInst::Sub: 11567 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11568 case AtomicRMWInst::Nand: 11569 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11570 case AtomicRMWInst::Max: 11571 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11572 case AtomicRMWInst::Min: 11573 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11574 case AtomicRMWInst::UMax: 11575 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11576 case AtomicRMWInst::UMin: 11577 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11578 } 11579 } 11580 11581 llvm_unreachable("Unexpected XLen\n"); 11582 } 11583 11584 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11585 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11586 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11587 unsigned XLen = Subtarget.getXLen(); 11588 Value *Ordering = 11589 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11590 Type *Tys[] = {AlignedAddr->getType()}; 11591 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11592 AI->getModule(), 11593 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11594 11595 if (XLen == 64) { 11596 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11597 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11598 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11599 } 11600 11601 Value *Result; 11602 11603 // Must pass the shift amount needed to sign extend the loaded value prior 11604 // to performing a signed comparison for min/max. ShiftAmt is the number of 11605 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11606 // is the number of bits to left+right shift the value in order to 11607 // sign-extend. 11608 if (AI->getOperation() == AtomicRMWInst::Min || 11609 AI->getOperation() == AtomicRMWInst::Max) { 11610 const DataLayout &DL = AI->getModule()->getDataLayout(); 11611 unsigned ValWidth = 11612 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11613 Value *SextShamt = 11614 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11615 Result = Builder.CreateCall(LrwOpScwLoop, 11616 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11617 } else { 11618 Result = 11619 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11620 } 11621 11622 if (XLen == 64) 11623 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11624 return Result; 11625 } 11626 11627 TargetLowering::AtomicExpansionKind 11628 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11629 AtomicCmpXchgInst *CI) const { 11630 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11631 if (Size == 8 || Size == 16) 11632 return AtomicExpansionKind::MaskedIntrinsic; 11633 return AtomicExpansionKind::None; 11634 } 11635 11636 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11637 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11638 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11639 unsigned XLen = Subtarget.getXLen(); 11640 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11641 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11642 if (XLen == 64) { 11643 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11644 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11645 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11646 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11647 } 11648 Type *Tys[] = {AlignedAddr->getType()}; 11649 Function *MaskedCmpXchg = 11650 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11651 Value *Result = Builder.CreateCall( 11652 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11653 if (XLen == 64) 11654 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11655 return Result; 11656 } 11657 11658 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11659 return false; 11660 } 11661 11662 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11663 EVT VT) const { 11664 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11665 return false; 11666 11667 switch (FPVT.getSimpleVT().SimpleTy) { 11668 case MVT::f16: 11669 return Subtarget.hasStdExtZfh(); 11670 case MVT::f32: 11671 return Subtarget.hasStdExtF(); 11672 case MVT::f64: 11673 return Subtarget.hasStdExtD(); 11674 default: 11675 return false; 11676 } 11677 } 11678 11679 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11680 // If we are using the small code model, we can reduce size of jump table 11681 // entry to 4 bytes. 11682 if (Subtarget.is64Bit() && !isPositionIndependent() && 11683 getTargetMachine().getCodeModel() == CodeModel::Small) { 11684 return MachineJumpTableInfo::EK_Custom32; 11685 } 11686 return TargetLowering::getJumpTableEncoding(); 11687 } 11688 11689 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11690 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11691 unsigned uid, MCContext &Ctx) const { 11692 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11693 getTargetMachine().getCodeModel() == CodeModel::Small); 11694 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11695 } 11696 11697 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11698 EVT VT) const { 11699 VT = VT.getScalarType(); 11700 11701 if (!VT.isSimple()) 11702 return false; 11703 11704 switch (VT.getSimpleVT().SimpleTy) { 11705 case MVT::f16: 11706 return Subtarget.hasStdExtZfh(); 11707 case MVT::f32: 11708 return Subtarget.hasStdExtF(); 11709 case MVT::f64: 11710 return Subtarget.hasStdExtD(); 11711 default: 11712 break; 11713 } 11714 11715 return false; 11716 } 11717 11718 Register RISCVTargetLowering::getExceptionPointerRegister( 11719 const Constant *PersonalityFn) const { 11720 return RISCV::X10; 11721 } 11722 11723 Register RISCVTargetLowering::getExceptionSelectorRegister( 11724 const Constant *PersonalityFn) const { 11725 return RISCV::X11; 11726 } 11727 11728 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11729 // Return false to suppress the unnecessary extensions if the LibCall 11730 // arguments or return value is f32 type for LP64 ABI. 11731 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11732 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11733 return false; 11734 11735 return true; 11736 } 11737 11738 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11739 if (Subtarget.is64Bit() && Type == MVT::i32) 11740 return true; 11741 11742 return IsSigned; 11743 } 11744 11745 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11746 SDValue C) const { 11747 // Check integral scalar types. 11748 if (VT.isScalarInteger()) { 11749 // Omit the optimization if the sub target has the M extension and the data 11750 // size exceeds XLen. 11751 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11752 return false; 11753 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11754 // Break the MUL to a SLLI and an ADD/SUB. 11755 const APInt &Imm = ConstNode->getAPIntValue(); 11756 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11757 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11758 return true; 11759 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11760 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11761 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11762 (Imm - 8).isPowerOf2())) 11763 return true; 11764 // Omit the following optimization if the sub target has the M extension 11765 // and the data size >= XLen. 11766 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11767 return false; 11768 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11769 // a pair of LUI/ADDI. 11770 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11771 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11772 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11773 (1 - ImmS).isPowerOf2()) 11774 return true; 11775 } 11776 } 11777 } 11778 11779 return false; 11780 } 11781 11782 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11783 SDValue ConstNode) const { 11784 // Let the DAGCombiner decide for vectors. 11785 EVT VT = AddNode.getValueType(); 11786 if (VT.isVector()) 11787 return true; 11788 11789 // Let the DAGCombiner decide for larger types. 11790 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11791 return true; 11792 11793 // It is worse if c1 is simm12 while c1*c2 is not. 11794 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11795 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11796 const APInt &C1 = C1Node->getAPIntValue(); 11797 const APInt &C2 = C2Node->getAPIntValue(); 11798 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11799 return false; 11800 11801 // Default to true and let the DAGCombiner decide. 11802 return true; 11803 } 11804 11805 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11806 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11807 bool *Fast) const { 11808 if (!VT.isVector()) 11809 return false; 11810 11811 EVT ElemVT = VT.getVectorElementType(); 11812 if (Alignment >= ElemVT.getStoreSize()) { 11813 if (Fast) 11814 *Fast = true; 11815 return true; 11816 } 11817 11818 return false; 11819 } 11820 11821 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11822 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11823 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11824 bool IsABIRegCopy = CC.hasValue(); 11825 EVT ValueVT = Val.getValueType(); 11826 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11827 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11828 // and cast to f32. 11829 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11830 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11831 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11832 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11833 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11834 Parts[0] = Val; 11835 return true; 11836 } 11837 11838 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11839 LLVMContext &Context = *DAG.getContext(); 11840 EVT ValueEltVT = ValueVT.getVectorElementType(); 11841 EVT PartEltVT = PartVT.getVectorElementType(); 11842 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11843 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11844 if (PartVTBitSize % ValueVTBitSize == 0) { 11845 assert(PartVTBitSize >= ValueVTBitSize); 11846 // If the element types are different, bitcast to the same element type of 11847 // PartVT first. 11848 // Give an example here, we want copy a <vscale x 1 x i8> value to 11849 // <vscale x 4 x i16>. 11850 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11851 // subvector, then we can bitcast to <vscale x 4 x i16>. 11852 if (ValueEltVT != PartEltVT) { 11853 if (PartVTBitSize > ValueVTBitSize) { 11854 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11855 assert(Count != 0 && "The number of element should not be zero."); 11856 EVT SameEltTypeVT = 11857 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11858 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11859 DAG.getUNDEF(SameEltTypeVT), Val, 11860 DAG.getVectorIdxConstant(0, DL)); 11861 } 11862 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11863 } else { 11864 Val = 11865 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11866 Val, DAG.getVectorIdxConstant(0, DL)); 11867 } 11868 Parts[0] = Val; 11869 return true; 11870 } 11871 } 11872 return false; 11873 } 11874 11875 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11876 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11877 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11878 bool IsABIRegCopy = CC.hasValue(); 11879 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11880 SDValue Val = Parts[0]; 11881 11882 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11883 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11884 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11885 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11886 return Val; 11887 } 11888 11889 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11890 LLVMContext &Context = *DAG.getContext(); 11891 SDValue Val = Parts[0]; 11892 EVT ValueEltVT = ValueVT.getVectorElementType(); 11893 EVT PartEltVT = PartVT.getVectorElementType(); 11894 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11895 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11896 if (PartVTBitSize % ValueVTBitSize == 0) { 11897 assert(PartVTBitSize >= ValueVTBitSize); 11898 EVT SameEltTypeVT = ValueVT; 11899 // If the element types are different, convert it to the same element type 11900 // of PartVT. 11901 // Give an example here, we want copy a <vscale x 1 x i8> value from 11902 // <vscale x 4 x i16>. 11903 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11904 // then we can extract <vscale x 1 x i8>. 11905 if (ValueEltVT != PartEltVT) { 11906 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11907 assert(Count != 0 && "The number of element should not be zero."); 11908 SameEltTypeVT = 11909 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11910 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11911 } 11912 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11913 DAG.getVectorIdxConstant(0, DL)); 11914 return Val; 11915 } 11916 } 11917 return SDValue(); 11918 } 11919 11920 SDValue 11921 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11922 SelectionDAG &DAG, 11923 SmallVectorImpl<SDNode *> &Created) const { 11924 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11925 if (isIntDivCheap(N->getValueType(0), Attr)) 11926 return SDValue(N, 0); // Lower SDIV as SDIV 11927 11928 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11929 "Unexpected divisor!"); 11930 11931 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11932 if (!Subtarget.hasStdExtZbt()) 11933 return SDValue(); 11934 11935 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11936 // Besides, more critical path instructions will be generated when dividing 11937 // by 2. So we keep using the original DAGs for these cases. 11938 unsigned Lg2 = Divisor.countTrailingZeros(); 11939 if (Lg2 == 1 || Lg2 >= 12) 11940 return SDValue(); 11941 11942 // fold (sdiv X, pow2) 11943 EVT VT = N->getValueType(0); 11944 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11945 return SDValue(); 11946 11947 SDLoc DL(N); 11948 SDValue N0 = N->getOperand(0); 11949 SDValue Zero = DAG.getConstant(0, DL, VT); 11950 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11951 11952 // Add (N0 < 0) ? Pow2 - 1 : 0; 11953 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11954 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11955 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11956 11957 Created.push_back(Cmp.getNode()); 11958 Created.push_back(Add.getNode()); 11959 Created.push_back(Sel.getNode()); 11960 11961 // Divide by pow2. 11962 SDValue SRA = 11963 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11964 11965 // If we're dividing by a positive value, we're done. Otherwise, we must 11966 // negate the result. 11967 if (Divisor.isNonNegative()) 11968 return SRA; 11969 11970 Created.push_back(SRA.getNode()); 11971 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11972 } 11973 11974 #define GET_REGISTER_MATCHER 11975 #include "RISCVGenAsmMatcher.inc" 11976 11977 Register 11978 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11979 const MachineFunction &MF) const { 11980 Register Reg = MatchRegisterAltName(RegName); 11981 if (Reg == RISCV::NoRegister) 11982 Reg = MatchRegisterName(RegName); 11983 if (Reg == RISCV::NoRegister) 11984 report_fatal_error( 11985 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11986 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11987 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11988 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11989 StringRef(RegName) + "\".")); 11990 return Reg; 11991 } 11992 11993 namespace llvm { 11994 namespace RISCVVIntrinsicsTable { 11995 11996 #define GET_RISCVVIntrinsicsTable_IMPL 11997 #include "RISCVGenSearchableTables.inc" 11998 11999 } // namespace RISCVVIntrinsicsTable 12000 12001 } // namespace llvm 12002