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 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 311 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 312 setOperationAction(ISD::SELECT, MVT::f16, Custom); 313 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 314 315 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 316 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 317 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 318 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 319 ISD::FLOG2, ISD::FLOG10}, 320 MVT::f16, Promote); 321 322 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 323 // complete support for all operations in LegalizeDAG. 324 325 // We need to custom promote this. 326 if (Subtarget.is64Bit()) 327 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 328 } 329 330 if (Subtarget.hasStdExtF()) { 331 for (auto NT : FPLegalNodeTypes) 332 setOperationAction(NT, MVT::f32, Legal); 333 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 334 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 335 setOperationAction(ISD::SELECT, MVT::f32, Custom); 336 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 337 for (auto Op : FPOpToExpand) 338 setOperationAction(Op, MVT::f32, Expand); 339 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 340 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 341 } 342 343 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 344 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 345 346 if (Subtarget.hasStdExtD()) { 347 for (auto NT : FPLegalNodeTypes) 348 setOperationAction(NT, MVT::f64, Legal); 349 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 350 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 351 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 352 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 353 setOperationAction(ISD::SELECT, MVT::f64, Custom); 354 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 355 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 356 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 357 for (auto Op : FPOpToExpand) 358 setOperationAction(Op, MVT::f64, Expand); 359 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 360 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 361 } 362 363 if (Subtarget.is64Bit()) 364 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 365 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 366 MVT::i32, Custom); 367 368 if (Subtarget.hasStdExtF()) { 369 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 370 Custom); 371 372 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 373 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 374 XLenVT, Legal); 375 376 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 377 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 378 } 379 380 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 381 ISD::JumpTable}, 382 XLenVT, Custom); 383 384 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 385 386 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 387 // Unfortunately this can't be determined just from the ISA naming string. 388 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 389 Subtarget.is64Bit() ? Legal : Custom); 390 391 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 392 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 393 if (Subtarget.is64Bit()) 394 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 395 396 if (Subtarget.hasStdExtA()) { 397 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 398 setMinCmpXchgSizeInBits(32); 399 } else { 400 setMaxAtomicSizeInBitsSupported(0); 401 } 402 403 setBooleanContents(ZeroOrOneBooleanContent); 404 405 if (Subtarget.hasVInstructions()) { 406 setBooleanVectorContents(ZeroOrOneBooleanContent); 407 408 setOperationAction(ISD::VSCALE, XLenVT, Custom); 409 410 // RVV intrinsics may have illegal operands. 411 // We also need to custom legalize vmv.x.s. 412 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 413 {MVT::i8, MVT::i16}, Custom); 414 if (Subtarget.is64Bit()) 415 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 416 else 417 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 418 MVT::i64, Custom); 419 420 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 421 MVT::Other, Custom); 422 423 static const unsigned IntegerVPOps[] = { 424 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 425 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 426 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 427 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 428 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 429 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 430 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 431 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 432 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 433 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 434 435 static const unsigned FloatingPointVPOps[] = { 436 ISD::VP_FADD, ISD::VP_FSUB, 437 ISD::VP_FMUL, ISD::VP_FDIV, 438 ISD::VP_FNEG, ISD::VP_FMA, 439 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 440 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 441 ISD::VP_MERGE, ISD::VP_SELECT, 442 ISD::VP_SITOFP, ISD::VP_UITOFP, 443 ISD::VP_SETCC, ISD::VP_FP_ROUND, 444 ISD::VP_FP_EXTEND}; 445 446 if (!Subtarget.is64Bit()) { 447 // We must custom-lower certain vXi64 operations on RV32 due to the vector 448 // element type being illegal. 449 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 450 MVT::i64, Custom); 451 452 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 453 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 454 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 455 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 456 MVT::i64, Custom); 457 458 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 459 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 460 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 461 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 462 MVT::i64, Custom); 463 } 464 465 for (MVT VT : BoolVecVTs) { 466 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 467 468 // Mask VTs are custom-expanded into a series of standard nodes 469 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 470 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 471 VT, Custom); 472 473 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 474 Custom); 475 476 setOperationAction(ISD::SELECT, VT, Custom); 477 setOperationAction( 478 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 479 Expand); 480 481 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 482 483 setOperationAction( 484 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 485 Custom); 486 487 setOperationAction( 488 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 489 Custom); 490 491 // RVV has native int->float & float->int conversions where the 492 // element type sizes are within one power-of-two of each other. Any 493 // wider distances between type sizes have to be lowered as sequences 494 // which progressively narrow the gap in stages. 495 setOperationAction( 496 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 497 VT, Custom); 498 499 // Expand all extending loads to types larger than this, and truncating 500 // stores from types larger than this. 501 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 502 setTruncStoreAction(OtherVT, VT, Expand); 503 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 504 VT, Expand); 505 } 506 507 setOperationAction( 508 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 509 Custom); 510 } 511 512 for (MVT VT : IntVecVTs) { 513 if (VT.getVectorElementType() == MVT::i64 && 514 !Subtarget.hasVInstructionsI64()) 515 continue; 516 517 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 518 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 519 520 // Vectors implement MULHS/MULHU. 521 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 522 523 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 524 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 525 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 526 527 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 528 Legal); 529 530 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 531 532 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 533 Expand); 534 535 setOperationAction(ISD::BSWAP, VT, Expand); 536 537 // Custom-lower extensions and truncations from/to mask types. 538 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 539 VT, Custom); 540 541 // RVV has native int->float & float->int conversions where the 542 // element type sizes are within one power-of-two of each other. Any 543 // wider distances between type sizes have to be lowered as sequences 544 // which progressively narrow the gap in stages. 545 setOperationAction( 546 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 547 VT, Custom); 548 549 setOperationAction( 550 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 551 552 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 553 // nodes which truncate by one power of two at a time. 554 setOperationAction(ISD::TRUNCATE, VT, Custom); 555 556 // Custom-lower insert/extract operations to simplify patterns. 557 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 558 Custom); 559 560 // Custom-lower reduction operations to set up the corresponding custom 561 // nodes' operands. 562 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 563 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 564 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 565 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 566 VT, Custom); 567 568 setOperationAction(IntegerVPOps, VT, Custom); 569 570 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 571 572 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 573 VT, Custom); 574 575 setOperationAction( 576 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 577 Custom); 578 579 setOperationAction( 580 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 581 VT, Custom); 582 583 setOperationAction(ISD::SELECT, VT, Custom); 584 setOperationAction(ISD::SELECT_CC, VT, Expand); 585 586 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 587 588 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 589 setTruncStoreAction(VT, OtherVT, Expand); 590 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 591 VT, Expand); 592 } 593 594 // Splice 595 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 596 597 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 598 // type that can represent the value exactly. 599 if (VT.getVectorElementType() != MVT::i64) { 600 MVT FloatEltVT = 601 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 602 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 603 if (isTypeLegal(FloatVT)) { 604 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 605 Custom); 606 } 607 } 608 } 609 610 // Expand various CCs to best match the RVV ISA, which natively supports UNE 611 // but no other unordered comparisons, and supports all ordered comparisons 612 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 613 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 614 // and we pattern-match those back to the "original", swapping operands once 615 // more. This way we catch both operations and both "vf" and "fv" forms with 616 // fewer patterns. 617 static const ISD::CondCode VFPCCToExpand[] = { 618 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 619 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 620 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 621 }; 622 623 // Sets common operation actions on RVV floating-point vector types. 624 const auto SetCommonVFPActions = [&](MVT VT) { 625 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 626 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 627 // sizes are within one power-of-two of each other. Therefore conversions 628 // between vXf16 and vXf64 must be lowered as sequences which convert via 629 // vXf32. 630 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 631 // Custom-lower insert/extract operations to simplify patterns. 632 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 633 Custom); 634 // Expand various condition codes (explained above). 635 setCondCodeAction(VFPCCToExpand, VT, Expand); 636 637 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 638 639 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 640 VT, Custom); 641 642 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 643 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 644 VT, Custom); 645 646 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 647 648 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 649 650 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 651 VT, Custom); 652 653 setOperationAction( 654 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 655 Custom); 656 657 setOperationAction(ISD::SELECT, VT, Custom); 658 setOperationAction(ISD::SELECT_CC, VT, Expand); 659 660 setOperationAction( 661 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 662 VT, Custom); 663 664 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 665 666 setOperationAction(FloatingPointVPOps, VT, Custom); 667 }; 668 669 // Sets common extload/truncstore actions on RVV floating-point vector 670 // types. 671 const auto SetCommonVFPExtLoadTruncStoreActions = 672 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 673 for (auto SmallVT : SmallerVTs) { 674 setTruncStoreAction(VT, SmallVT, Expand); 675 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 676 } 677 }; 678 679 if (Subtarget.hasVInstructionsF16()) 680 for (MVT VT : F16VecVTs) 681 SetCommonVFPActions(VT); 682 683 for (MVT VT : F32VecVTs) { 684 if (Subtarget.hasVInstructionsF32()) 685 SetCommonVFPActions(VT); 686 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 687 } 688 689 for (MVT VT : F64VecVTs) { 690 if (Subtarget.hasVInstructionsF64()) 691 SetCommonVFPActions(VT); 692 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 693 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 694 } 695 696 if (Subtarget.useRVVForFixedLengthVectors()) { 697 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 698 if (!useRVVForFixedLengthVectorVT(VT)) 699 continue; 700 701 // By default everything must be expanded. 702 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 703 setOperationAction(Op, VT, Expand); 704 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 705 setTruncStoreAction(VT, OtherVT, Expand); 706 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 707 OtherVT, VT, Expand); 708 } 709 710 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 711 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 712 Custom); 713 714 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 715 Custom); 716 717 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 718 VT, Custom); 719 720 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 721 722 setOperationAction(ISD::SETCC, VT, Custom); 723 724 setOperationAction(ISD::SELECT, VT, Custom); 725 726 setOperationAction(ISD::TRUNCATE, VT, Custom); 727 728 setOperationAction(ISD::BITCAST, VT, Custom); 729 730 setOperationAction( 731 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 732 Custom); 733 734 setOperationAction( 735 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 736 Custom); 737 738 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 739 ISD::FP_TO_UINT}, 740 VT, Custom); 741 742 // Operations below are different for between masks and other vectors. 743 if (VT.getVectorElementType() == MVT::i1) { 744 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 745 ISD::OR, ISD::XOR}, 746 VT, Custom); 747 748 setOperationAction( 749 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 750 VT, Custom); 751 continue; 752 } 753 754 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 755 // it before type legalization for i64 vectors on RV32. It will then be 756 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 757 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 758 // improvements first. 759 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 760 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 761 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 762 } 763 764 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 765 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 766 767 setOperationAction( 768 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 769 770 setOperationAction( 771 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 772 Custom); 773 774 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 775 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 776 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 777 VT, Custom); 778 779 setOperationAction( 780 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 781 782 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 783 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 784 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 785 786 setOperationAction( 787 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 788 Custom); 789 790 setOperationAction(ISD::VSELECT, VT, Custom); 791 setOperationAction(ISD::SELECT_CC, VT, Expand); 792 793 setOperationAction( 794 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 795 796 // Custom-lower reduction operations to set up the corresponding custom 797 // nodes' operands. 798 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 799 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 800 ISD::VECREDUCE_UMIN}, 801 VT, Custom); 802 803 setOperationAction(IntegerVPOps, VT, Custom); 804 805 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 806 // type that can represent the value exactly. 807 if (VT.getVectorElementType() != MVT::i64) { 808 MVT FloatEltVT = 809 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 810 EVT FloatVT = 811 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 812 if (isTypeLegal(FloatVT)) 813 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 814 Custom); 815 } 816 } 817 818 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 819 if (!useRVVForFixedLengthVectorVT(VT)) 820 continue; 821 822 // By default everything must be expanded. 823 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 824 setOperationAction(Op, VT, Expand); 825 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 826 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 827 setTruncStoreAction(VT, OtherVT, Expand); 828 } 829 830 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 831 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 832 Custom); 833 834 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 835 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 836 ISD::EXTRACT_VECTOR_ELT}, 837 VT, Custom); 838 839 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 840 ISD::MGATHER, ISD::MSCATTER}, 841 VT, Custom); 842 843 setOperationAction( 844 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 845 Custom); 846 847 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 848 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 849 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 850 VT, Custom); 851 852 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 853 854 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 855 VT, Custom); 856 857 for (auto CC : VFPCCToExpand) 858 setCondCodeAction(CC, VT, Expand); 859 860 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 861 setOperationAction(ISD::SELECT_CC, VT, Expand); 862 863 setOperationAction(ISD::BITCAST, VT, Custom); 864 865 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 866 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 867 VT, Custom); 868 869 setOperationAction(FloatingPointVPOps, VT, Custom); 870 } 871 872 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 873 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 874 Custom); 875 if (Subtarget.hasStdExtZfh()) 876 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 877 if (Subtarget.hasStdExtF()) 878 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 879 if (Subtarget.hasStdExtD()) 880 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 881 } 882 } 883 884 // Function alignments. 885 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 886 setMinFunctionAlignment(FunctionAlignment); 887 setPrefFunctionAlignment(FunctionAlignment); 888 889 setMinimumJumpTableEntries(5); 890 891 // Jumps are expensive, compared to logic 892 setJumpIsExpensive(); 893 894 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 895 ISD::OR, ISD::XOR}); 896 897 if (Subtarget.hasStdExtF()) 898 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 899 900 if (Subtarget.hasStdExtZbp()) 901 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 902 903 if (Subtarget.hasStdExtZbb()) 904 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 905 906 if (Subtarget.hasStdExtZbkb()) 907 setTargetDAGCombine(ISD::BITREVERSE); 908 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 909 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 910 if (Subtarget.hasStdExtF()) 911 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 912 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 913 if (Subtarget.hasVInstructions()) 914 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 915 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 916 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 917 918 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 919 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 920 } 921 922 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 923 LLVMContext &Context, 924 EVT VT) const { 925 if (!VT.isVector()) 926 return getPointerTy(DL); 927 if (Subtarget.hasVInstructions() && 928 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 929 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 930 return VT.changeVectorElementTypeToInteger(); 931 } 932 933 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 934 return Subtarget.getXLenVT(); 935 } 936 937 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 938 const CallInst &I, 939 MachineFunction &MF, 940 unsigned Intrinsic) const { 941 auto &DL = I.getModule()->getDataLayout(); 942 switch (Intrinsic) { 943 default: 944 return false; 945 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 946 case Intrinsic::riscv_masked_atomicrmw_add_i32: 947 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 948 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 949 case Intrinsic::riscv_masked_atomicrmw_max_i32: 950 case Intrinsic::riscv_masked_atomicrmw_min_i32: 951 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 952 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 953 case Intrinsic::riscv_masked_cmpxchg_i32: 954 Info.opc = ISD::INTRINSIC_W_CHAIN; 955 Info.memVT = MVT::i32; 956 Info.ptrVal = I.getArgOperand(0); 957 Info.offset = 0; 958 Info.align = Align(4); 959 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 960 MachineMemOperand::MOVolatile; 961 return true; 962 case Intrinsic::riscv_masked_strided_load: 963 Info.opc = ISD::INTRINSIC_W_CHAIN; 964 Info.ptrVal = I.getArgOperand(1); 965 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 966 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 967 Info.size = MemoryLocation::UnknownSize; 968 Info.flags |= MachineMemOperand::MOLoad; 969 return true; 970 case Intrinsic::riscv_masked_strided_store: 971 Info.opc = ISD::INTRINSIC_VOID; 972 Info.ptrVal = I.getArgOperand(1); 973 Info.memVT = 974 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 975 Info.align = Align( 976 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 977 8); 978 Info.size = MemoryLocation::UnknownSize; 979 Info.flags |= MachineMemOperand::MOStore; 980 return true; 981 case Intrinsic::riscv_seg2_load: 982 case Intrinsic::riscv_seg3_load: 983 case Intrinsic::riscv_seg4_load: 984 case Intrinsic::riscv_seg5_load: 985 case Intrinsic::riscv_seg6_load: 986 case Intrinsic::riscv_seg7_load: 987 case Intrinsic::riscv_seg8_load: 988 Info.opc = ISD::INTRINSIC_W_CHAIN; 989 Info.ptrVal = I.getArgOperand(0); 990 Info.memVT = 991 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 992 Info.align = 993 Align(DL.getTypeSizeInBits( 994 I.getType()->getStructElementType(0)->getScalarType()) / 995 8); 996 Info.size = MemoryLocation::UnknownSize; 997 Info.flags |= MachineMemOperand::MOLoad; 998 return true; 999 } 1000 } 1001 1002 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1003 const AddrMode &AM, Type *Ty, 1004 unsigned AS, 1005 Instruction *I) const { 1006 // No global is ever allowed as a base. 1007 if (AM.BaseGV) 1008 return false; 1009 1010 // RVV instructions only support register addressing. 1011 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1012 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1013 1014 // Require a 12-bit signed offset. 1015 if (!isInt<12>(AM.BaseOffs)) 1016 return false; 1017 1018 switch (AM.Scale) { 1019 case 0: // "r+i" or just "i", depending on HasBaseReg. 1020 break; 1021 case 1: 1022 if (!AM.HasBaseReg) // allow "r+i". 1023 break; 1024 return false; // disallow "r+r" or "r+r+i". 1025 default: 1026 return false; 1027 } 1028 1029 return true; 1030 } 1031 1032 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1033 return isInt<12>(Imm); 1034 } 1035 1036 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1037 return isInt<12>(Imm); 1038 } 1039 1040 // On RV32, 64-bit integers are split into their high and low parts and held 1041 // in two different registers, so the trunc is free since the low register can 1042 // just be used. 1043 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1044 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1045 return false; 1046 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1047 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1048 return (SrcBits == 64 && DestBits == 32); 1049 } 1050 1051 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1052 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1053 !SrcVT.isInteger() || !DstVT.isInteger()) 1054 return false; 1055 unsigned SrcBits = SrcVT.getSizeInBits(); 1056 unsigned DestBits = DstVT.getSizeInBits(); 1057 return (SrcBits == 64 && DestBits == 32); 1058 } 1059 1060 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1061 // Zexts are free if they can be combined with a load. 1062 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1063 // poorly with type legalization of compares preferring sext. 1064 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1065 EVT MemVT = LD->getMemoryVT(); 1066 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1067 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1068 LD->getExtensionType() == ISD::ZEXTLOAD)) 1069 return true; 1070 } 1071 1072 return TargetLowering::isZExtFree(Val, VT2); 1073 } 1074 1075 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1076 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1077 } 1078 1079 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1080 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1081 } 1082 1083 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1084 return Subtarget.hasStdExtZbb(); 1085 } 1086 1087 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1088 return Subtarget.hasStdExtZbb(); 1089 } 1090 1091 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1092 EVT VT = Y.getValueType(); 1093 1094 // FIXME: Support vectors once we have tests. 1095 if (VT.isVector()) 1096 return false; 1097 1098 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1099 Subtarget.hasStdExtZbkb()) && 1100 !isa<ConstantSDNode>(Y); 1101 } 1102 1103 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1104 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1105 auto *C = dyn_cast<ConstantSDNode>(Y); 1106 return C && C->getAPIntValue().ule(10); 1107 } 1108 1109 bool RISCVTargetLowering:: 1110 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1111 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1112 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1113 SelectionDAG &DAG) const { 1114 // One interesting pattern that we'd want to form is 'bit extract': 1115 // ((1 >> Y) & 1) ==/!= 0 1116 // But we also need to be careful not to try to reverse that fold. 1117 1118 // Is this '((1 >> Y) & 1)'? 1119 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1120 return false; // Keep the 'bit extract' pattern. 1121 1122 // Will this be '((1 >> Y) & 1)' after the transform? 1123 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1124 return true; // Do form the 'bit extract' pattern. 1125 1126 // If 'X' is a constant, and we transform, then we will immediately 1127 // try to undo the fold, thus causing endless combine loop. 1128 // So only do the transform if X is not a constant. This matches the default 1129 // implementation of this function. 1130 return !XC; 1131 } 1132 1133 /// Check if sinking \p I's operands to I's basic block is profitable, because 1134 /// the operands can be folded into a target instruction, e.g. 1135 /// splats of scalars can fold into vector instructions. 1136 bool RISCVTargetLowering::shouldSinkOperands( 1137 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1138 using namespace llvm::PatternMatch; 1139 1140 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1141 return false; 1142 1143 auto IsSinker = [&](Instruction *I, int Operand) { 1144 switch (I->getOpcode()) { 1145 case Instruction::Add: 1146 case Instruction::Sub: 1147 case Instruction::Mul: 1148 case Instruction::And: 1149 case Instruction::Or: 1150 case Instruction::Xor: 1151 case Instruction::FAdd: 1152 case Instruction::FSub: 1153 case Instruction::FMul: 1154 case Instruction::FDiv: 1155 case Instruction::ICmp: 1156 case Instruction::FCmp: 1157 return true; 1158 case Instruction::Shl: 1159 case Instruction::LShr: 1160 case Instruction::AShr: 1161 case Instruction::UDiv: 1162 case Instruction::SDiv: 1163 case Instruction::URem: 1164 case Instruction::SRem: 1165 return Operand == 1; 1166 case Instruction::Call: 1167 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1168 switch (II->getIntrinsicID()) { 1169 case Intrinsic::fma: 1170 case Intrinsic::vp_fma: 1171 return Operand == 0 || Operand == 1; 1172 // FIXME: Our patterns can only match vx/vf instructions when the splat 1173 // it on the RHS, because TableGen doesn't recognize our VP operations 1174 // as commutative. 1175 case Intrinsic::vp_add: 1176 case Intrinsic::vp_mul: 1177 case Intrinsic::vp_and: 1178 case Intrinsic::vp_or: 1179 case Intrinsic::vp_xor: 1180 case Intrinsic::vp_fadd: 1181 case Intrinsic::vp_fmul: 1182 case Intrinsic::vp_shl: 1183 case Intrinsic::vp_lshr: 1184 case Intrinsic::vp_ashr: 1185 case Intrinsic::vp_udiv: 1186 case Intrinsic::vp_sdiv: 1187 case Intrinsic::vp_urem: 1188 case Intrinsic::vp_srem: 1189 return Operand == 1; 1190 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1191 // explicit patterns for both LHS and RHS (as 'vr' versions). 1192 case Intrinsic::vp_sub: 1193 case Intrinsic::vp_fsub: 1194 case Intrinsic::vp_fdiv: 1195 return Operand == 0 || Operand == 1; 1196 default: 1197 return false; 1198 } 1199 } 1200 return false; 1201 default: 1202 return false; 1203 } 1204 }; 1205 1206 for (auto OpIdx : enumerate(I->operands())) { 1207 if (!IsSinker(I, OpIdx.index())) 1208 continue; 1209 1210 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1211 // Make sure we are not already sinking this operand 1212 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1213 continue; 1214 1215 // We are looking for a splat that can be sunk. 1216 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1217 m_Undef(), m_ZeroMask()))) 1218 continue; 1219 1220 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1221 // and vector registers 1222 for (Use &U : Op->uses()) { 1223 Instruction *Insn = cast<Instruction>(U.getUser()); 1224 if (!IsSinker(Insn, U.getOperandNo())) 1225 return false; 1226 } 1227 1228 Ops.push_back(&Op->getOperandUse(0)); 1229 Ops.push_back(&OpIdx.value()); 1230 } 1231 return true; 1232 } 1233 1234 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1235 bool ForCodeSize) const { 1236 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1237 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1238 return false; 1239 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1240 return false; 1241 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1242 return false; 1243 return Imm.isZero(); 1244 } 1245 1246 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1247 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1248 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1249 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1250 } 1251 1252 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1253 CallingConv::ID CC, 1254 EVT VT) const { 1255 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1256 // We might still end up using a GPR but that will be decided based on ABI. 1257 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1258 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1259 return MVT::f32; 1260 1261 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1262 } 1263 1264 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1265 CallingConv::ID CC, 1266 EVT VT) const { 1267 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1268 // We might still end up using a GPR but that will be decided based on ABI. 1269 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1270 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1271 return 1; 1272 1273 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1274 } 1275 1276 // Changes the condition code and swaps operands if necessary, so the SetCC 1277 // operation matches one of the comparisons supported directly by branches 1278 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1279 // with 1/-1. 1280 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1281 ISD::CondCode &CC, SelectionDAG &DAG) { 1282 // Convert X > -1 to X >= 0. 1283 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1284 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1285 CC = ISD::SETGE; 1286 return; 1287 } 1288 // Convert X < 1 to 0 >= X. 1289 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1290 RHS = LHS; 1291 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1292 CC = ISD::SETGE; 1293 return; 1294 } 1295 1296 switch (CC) { 1297 default: 1298 break; 1299 case ISD::SETGT: 1300 case ISD::SETLE: 1301 case ISD::SETUGT: 1302 case ISD::SETULE: 1303 CC = ISD::getSetCCSwappedOperands(CC); 1304 std::swap(LHS, RHS); 1305 break; 1306 } 1307 } 1308 1309 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1310 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1311 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1312 if (VT.getVectorElementType() == MVT::i1) 1313 KnownSize *= 8; 1314 1315 switch (KnownSize) { 1316 default: 1317 llvm_unreachable("Invalid LMUL."); 1318 case 8: 1319 return RISCVII::VLMUL::LMUL_F8; 1320 case 16: 1321 return RISCVII::VLMUL::LMUL_F4; 1322 case 32: 1323 return RISCVII::VLMUL::LMUL_F2; 1324 case 64: 1325 return RISCVII::VLMUL::LMUL_1; 1326 case 128: 1327 return RISCVII::VLMUL::LMUL_2; 1328 case 256: 1329 return RISCVII::VLMUL::LMUL_4; 1330 case 512: 1331 return RISCVII::VLMUL::LMUL_8; 1332 } 1333 } 1334 1335 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1336 switch (LMul) { 1337 default: 1338 llvm_unreachable("Invalid LMUL."); 1339 case RISCVII::VLMUL::LMUL_F8: 1340 case RISCVII::VLMUL::LMUL_F4: 1341 case RISCVII::VLMUL::LMUL_F2: 1342 case RISCVII::VLMUL::LMUL_1: 1343 return RISCV::VRRegClassID; 1344 case RISCVII::VLMUL::LMUL_2: 1345 return RISCV::VRM2RegClassID; 1346 case RISCVII::VLMUL::LMUL_4: 1347 return RISCV::VRM4RegClassID; 1348 case RISCVII::VLMUL::LMUL_8: 1349 return RISCV::VRM8RegClassID; 1350 } 1351 } 1352 1353 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1354 RISCVII::VLMUL LMUL = getLMUL(VT); 1355 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1356 LMUL == RISCVII::VLMUL::LMUL_F4 || 1357 LMUL == RISCVII::VLMUL::LMUL_F2 || 1358 LMUL == RISCVII::VLMUL::LMUL_1) { 1359 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1360 "Unexpected subreg numbering"); 1361 return RISCV::sub_vrm1_0 + Index; 1362 } 1363 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1364 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1365 "Unexpected subreg numbering"); 1366 return RISCV::sub_vrm2_0 + Index; 1367 } 1368 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1369 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1370 "Unexpected subreg numbering"); 1371 return RISCV::sub_vrm4_0 + Index; 1372 } 1373 llvm_unreachable("Invalid vector type."); 1374 } 1375 1376 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1377 if (VT.getVectorElementType() == MVT::i1) 1378 return RISCV::VRRegClassID; 1379 return getRegClassIDForLMUL(getLMUL(VT)); 1380 } 1381 1382 // Attempt to decompose a subvector insert/extract between VecVT and 1383 // SubVecVT via subregister indices. Returns the subregister index that 1384 // can perform the subvector insert/extract with the given element index, as 1385 // well as the index corresponding to any leftover subvectors that must be 1386 // further inserted/extracted within the register class for SubVecVT. 1387 std::pair<unsigned, unsigned> 1388 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1389 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1390 const RISCVRegisterInfo *TRI) { 1391 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1392 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1393 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1394 "Register classes not ordered"); 1395 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1396 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1397 // Try to compose a subregister index that takes us from the incoming 1398 // LMUL>1 register class down to the outgoing one. At each step we half 1399 // the LMUL: 1400 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1401 // Note that this is not guaranteed to find a subregister index, such as 1402 // when we are extracting from one VR type to another. 1403 unsigned SubRegIdx = RISCV::NoSubRegister; 1404 for (const unsigned RCID : 1405 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1406 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1407 VecVT = VecVT.getHalfNumVectorElementsVT(); 1408 bool IsHi = 1409 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1410 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1411 getSubregIndexByMVT(VecVT, IsHi)); 1412 if (IsHi) 1413 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1414 } 1415 return {SubRegIdx, InsertExtractIdx}; 1416 } 1417 1418 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1419 // stores for those types. 1420 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1421 return !Subtarget.useRVVForFixedLengthVectors() || 1422 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1423 } 1424 1425 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1426 if (ScalarTy->isPointerTy()) 1427 return true; 1428 1429 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1430 ScalarTy->isIntegerTy(32)) 1431 return true; 1432 1433 if (ScalarTy->isIntegerTy(64)) 1434 return Subtarget.hasVInstructionsI64(); 1435 1436 if (ScalarTy->isHalfTy()) 1437 return Subtarget.hasVInstructionsF16(); 1438 if (ScalarTy->isFloatTy()) 1439 return Subtarget.hasVInstructionsF32(); 1440 if (ScalarTy->isDoubleTy()) 1441 return Subtarget.hasVInstructionsF64(); 1442 1443 return false; 1444 } 1445 1446 static SDValue getVLOperand(SDValue Op) { 1447 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1448 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1449 "Unexpected opcode"); 1450 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1451 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1452 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1453 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1454 if (!II) 1455 return SDValue(); 1456 return Op.getOperand(II->VLOperand + 1 + HasChain); 1457 } 1458 1459 static bool useRVVForFixedLengthVectorVT(MVT VT, 1460 const RISCVSubtarget &Subtarget) { 1461 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1462 if (!Subtarget.useRVVForFixedLengthVectors()) 1463 return false; 1464 1465 // We only support a set of vector types with a consistent maximum fixed size 1466 // across all supported vector element types to avoid legalization issues. 1467 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1468 // fixed-length vector type we support is 1024 bytes. 1469 if (VT.getFixedSizeInBits() > 1024 * 8) 1470 return false; 1471 1472 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1473 1474 MVT EltVT = VT.getVectorElementType(); 1475 1476 // Don't use RVV for vectors we cannot scalarize if required. 1477 switch (EltVT.SimpleTy) { 1478 // i1 is supported but has different rules. 1479 default: 1480 return false; 1481 case MVT::i1: 1482 // Masks can only use a single register. 1483 if (VT.getVectorNumElements() > MinVLen) 1484 return false; 1485 MinVLen /= 8; 1486 break; 1487 case MVT::i8: 1488 case MVT::i16: 1489 case MVT::i32: 1490 break; 1491 case MVT::i64: 1492 if (!Subtarget.hasVInstructionsI64()) 1493 return false; 1494 break; 1495 case MVT::f16: 1496 if (!Subtarget.hasVInstructionsF16()) 1497 return false; 1498 break; 1499 case MVT::f32: 1500 if (!Subtarget.hasVInstructionsF32()) 1501 return false; 1502 break; 1503 case MVT::f64: 1504 if (!Subtarget.hasVInstructionsF64()) 1505 return false; 1506 break; 1507 } 1508 1509 // Reject elements larger than ELEN. 1510 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1511 return false; 1512 1513 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1514 // Don't use RVV for types that don't fit. 1515 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1516 return false; 1517 1518 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1519 // the base fixed length RVV support in place. 1520 if (!VT.isPow2VectorType()) 1521 return false; 1522 1523 return true; 1524 } 1525 1526 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1527 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1528 } 1529 1530 // Return the largest legal scalable vector type that matches VT's element type. 1531 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1532 const RISCVSubtarget &Subtarget) { 1533 // This may be called before legal types are setup. 1534 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1535 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1536 "Expected legal fixed length vector!"); 1537 1538 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1539 unsigned MaxELen = Subtarget.getELEN(); 1540 1541 MVT EltVT = VT.getVectorElementType(); 1542 switch (EltVT.SimpleTy) { 1543 default: 1544 llvm_unreachable("unexpected element type for RVV container"); 1545 case MVT::i1: 1546 case MVT::i8: 1547 case MVT::i16: 1548 case MVT::i32: 1549 case MVT::i64: 1550 case MVT::f16: 1551 case MVT::f32: 1552 case MVT::f64: { 1553 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1554 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1555 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1556 unsigned NumElts = 1557 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1558 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1559 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1560 return MVT::getScalableVectorVT(EltVT, NumElts); 1561 } 1562 } 1563 } 1564 1565 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1566 const RISCVSubtarget &Subtarget) { 1567 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1568 Subtarget); 1569 } 1570 1571 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1572 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1573 } 1574 1575 // Grow V to consume an entire RVV register. 1576 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1577 const RISCVSubtarget &Subtarget) { 1578 assert(VT.isScalableVector() && 1579 "Expected to convert into a scalable vector!"); 1580 assert(V.getValueType().isFixedLengthVector() && 1581 "Expected a fixed length vector operand!"); 1582 SDLoc DL(V); 1583 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1584 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1585 } 1586 1587 // Shrink V so it's just big enough to maintain a VT's worth of data. 1588 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1589 const RISCVSubtarget &Subtarget) { 1590 assert(VT.isFixedLengthVector() && 1591 "Expected to convert into a fixed length vector!"); 1592 assert(V.getValueType().isScalableVector() && 1593 "Expected a scalable vector operand!"); 1594 SDLoc DL(V); 1595 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1596 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1597 } 1598 1599 /// Return the type of the mask type suitable for masking the provided 1600 /// vector type. This is simply an i1 element type vector of the same 1601 /// (possibly scalable) length. 1602 static MVT getMaskTypeFor(EVT VecVT) { 1603 assert(VecVT.isVector()); 1604 ElementCount EC = VecVT.getVectorElementCount(); 1605 return MVT::getVectorVT(MVT::i1, EC); 1606 } 1607 1608 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1609 /// vector length VL. . 1610 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1611 SelectionDAG &DAG) { 1612 MVT MaskVT = getMaskTypeFor(VecVT); 1613 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1614 } 1615 1616 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1617 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1618 // the vector type that it is contained in. 1619 static std::pair<SDValue, SDValue> 1620 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1621 const RISCVSubtarget &Subtarget) { 1622 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1623 MVT XLenVT = Subtarget.getXLenVT(); 1624 SDValue VL = VecVT.isFixedLengthVector() 1625 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1626 : DAG.getRegister(RISCV::X0, XLenVT); 1627 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1628 return {Mask, VL}; 1629 } 1630 1631 // As above but assuming the given type is a scalable vector type. 1632 static std::pair<SDValue, SDValue> 1633 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1634 const RISCVSubtarget &Subtarget) { 1635 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1636 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1637 } 1638 1639 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1640 // of either is (currently) supported. This can get us into an infinite loop 1641 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1642 // as a ..., etc. 1643 // Until either (or both) of these can reliably lower any node, reporting that 1644 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1645 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1646 // which is not desirable. 1647 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1648 EVT VT, unsigned DefinedValues) const { 1649 return false; 1650 } 1651 1652 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1653 const RISCVSubtarget &Subtarget) { 1654 // RISCV FP-to-int conversions saturate to the destination register size, but 1655 // don't produce 0 for nan. We can use a conversion instruction and fix the 1656 // nan case with a compare and a select. 1657 SDValue Src = Op.getOperand(0); 1658 1659 EVT DstVT = Op.getValueType(); 1660 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1661 1662 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1663 unsigned Opc; 1664 if (SatVT == DstVT) 1665 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1666 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1667 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1668 else 1669 return SDValue(); 1670 // FIXME: Support other SatVTs by clamping before or after the conversion. 1671 1672 SDLoc DL(Op); 1673 SDValue FpToInt = DAG.getNode( 1674 Opc, DL, DstVT, Src, 1675 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1676 1677 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1678 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1679 } 1680 1681 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1682 // and back. Taking care to avoid converting values that are nan or already 1683 // correct. 1684 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1685 // have FRM dependencies modeled yet. 1686 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1687 MVT VT = Op.getSimpleValueType(); 1688 assert(VT.isVector() && "Unexpected type"); 1689 1690 SDLoc DL(Op); 1691 1692 // Freeze the source since we are increasing the number of uses. 1693 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1694 1695 // Truncate to integer and convert back to FP. 1696 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1697 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1698 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1699 1700 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1701 1702 if (Op.getOpcode() == ISD::FCEIL) { 1703 // If the truncated value is the greater than or equal to the original 1704 // value, we've computed the ceil. Otherwise, we went the wrong way and 1705 // need to increase by 1. 1706 // FIXME: This should use a masked operation. Handle here or in isel? 1707 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1708 DAG.getConstantFP(1.0, DL, VT)); 1709 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1710 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1711 } else if (Op.getOpcode() == ISD::FFLOOR) { 1712 // If the truncated value is the less than or equal to the original value, 1713 // we've computed the floor. Otherwise, we went the wrong way and need to 1714 // decrease by 1. 1715 // FIXME: This should use a masked operation. Handle here or in isel? 1716 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1717 DAG.getConstantFP(1.0, DL, VT)); 1718 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1719 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1720 } 1721 1722 // Restore the original sign so that -0.0 is preserved. 1723 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1724 1725 // Determine the largest integer that can be represented exactly. This and 1726 // values larger than it don't have any fractional bits so don't need to 1727 // be converted. 1728 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1729 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1730 APFloat MaxVal = APFloat(FltSem); 1731 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1732 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1733 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1734 1735 // If abs(Src) was larger than MaxVal or nan, keep it. 1736 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1737 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1738 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1739 } 1740 1741 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1742 // This mode isn't supported in vector hardware on RISCV. But as long as we 1743 // aren't compiling with trapping math, we can emulate this with 1744 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1745 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1746 // dependencies modeled yet. 1747 // FIXME: Use masked operations to avoid final merge. 1748 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1749 MVT VT = Op.getSimpleValueType(); 1750 assert(VT.isVector() && "Unexpected type"); 1751 1752 SDLoc DL(Op); 1753 1754 // Freeze the source since we are increasing the number of uses. 1755 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1756 1757 // We do the conversion on the absolute value and fix the sign at the end. 1758 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1759 1760 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1761 bool Ignored; 1762 APFloat Point5Pred = APFloat(0.5f); 1763 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1764 Point5Pred.next(/*nextDown*/ true); 1765 1766 // Add the adjustment. 1767 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1768 DAG.getConstantFP(Point5Pred, DL, VT)); 1769 1770 // Truncate to integer and convert back to fp. 1771 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1772 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1773 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1774 1775 // Restore the original sign. 1776 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1777 1778 // Determine the largest integer that can be represented exactly. This and 1779 // values larger than it don't have any fractional bits so don't need to 1780 // be converted. 1781 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1782 APFloat MaxVal = APFloat(FltSem); 1783 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1784 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1785 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1786 1787 // If abs(Src) was larger than MaxVal or nan, keep it. 1788 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1789 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1790 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1791 } 1792 1793 struct VIDSequence { 1794 int64_t StepNumerator; 1795 unsigned StepDenominator; 1796 int64_t Addend; 1797 }; 1798 1799 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1800 // to the (non-zero) step S and start value X. This can be then lowered as the 1801 // RVV sequence (VID * S) + X, for example. 1802 // The step S is represented as an integer numerator divided by a positive 1803 // denominator. Note that the implementation currently only identifies 1804 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1805 // cannot detect 2/3, for example. 1806 // Note that this method will also match potentially unappealing index 1807 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1808 // determine whether this is worth generating code for. 1809 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1810 unsigned NumElts = Op.getNumOperands(); 1811 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1812 if (!Op.getValueType().isInteger()) 1813 return None; 1814 1815 Optional<unsigned> SeqStepDenom; 1816 Optional<int64_t> SeqStepNum, SeqAddend; 1817 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1818 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1819 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1820 // Assume undef elements match the sequence; we just have to be careful 1821 // when interpolating across them. 1822 if (Op.getOperand(Idx).isUndef()) 1823 continue; 1824 // The BUILD_VECTOR must be all constants. 1825 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1826 return None; 1827 1828 uint64_t Val = Op.getConstantOperandVal(Idx) & 1829 maskTrailingOnes<uint64_t>(EltSizeInBits); 1830 1831 if (PrevElt) { 1832 // Calculate the step since the last non-undef element, and ensure 1833 // it's consistent across the entire sequence. 1834 unsigned IdxDiff = Idx - PrevElt->second; 1835 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1836 1837 // A zero-value value difference means that we're somewhere in the middle 1838 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1839 // step change before evaluating the sequence. 1840 if (ValDiff == 0) 1841 continue; 1842 1843 int64_t Remainder = ValDiff % IdxDiff; 1844 // Normalize the step if it's greater than 1. 1845 if (Remainder != ValDiff) { 1846 // The difference must cleanly divide the element span. 1847 if (Remainder != 0) 1848 return None; 1849 ValDiff /= IdxDiff; 1850 IdxDiff = 1; 1851 } 1852 1853 if (!SeqStepNum) 1854 SeqStepNum = ValDiff; 1855 else if (ValDiff != SeqStepNum) 1856 return None; 1857 1858 if (!SeqStepDenom) 1859 SeqStepDenom = IdxDiff; 1860 else if (IdxDiff != *SeqStepDenom) 1861 return None; 1862 } 1863 1864 // Record this non-undef element for later. 1865 if (!PrevElt || PrevElt->first != Val) 1866 PrevElt = std::make_pair(Val, Idx); 1867 } 1868 1869 // We need to have logged a step for this to count as a legal index sequence. 1870 if (!SeqStepNum || !SeqStepDenom) 1871 return None; 1872 1873 // Loop back through the sequence and validate elements we might have skipped 1874 // while waiting for a valid step. While doing this, log any sequence addend. 1875 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1876 if (Op.getOperand(Idx).isUndef()) 1877 continue; 1878 uint64_t Val = Op.getConstantOperandVal(Idx) & 1879 maskTrailingOnes<uint64_t>(EltSizeInBits); 1880 uint64_t ExpectedVal = 1881 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1882 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1883 if (!SeqAddend) 1884 SeqAddend = Addend; 1885 else if (Addend != SeqAddend) 1886 return None; 1887 } 1888 1889 assert(SeqAddend && "Must have an addend if we have a step"); 1890 1891 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1892 } 1893 1894 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1895 // and lower it as a VRGATHER_VX_VL from the source vector. 1896 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1897 SelectionDAG &DAG, 1898 const RISCVSubtarget &Subtarget) { 1899 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1900 return SDValue(); 1901 SDValue Vec = SplatVal.getOperand(0); 1902 // Only perform this optimization on vectors of the same size for simplicity. 1903 if (Vec.getValueType() != VT) 1904 return SDValue(); 1905 SDValue Idx = SplatVal.getOperand(1); 1906 // The index must be a legal type. 1907 if (Idx.getValueType() != Subtarget.getXLenVT()) 1908 return SDValue(); 1909 1910 MVT ContainerVT = VT; 1911 if (VT.isFixedLengthVector()) { 1912 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1913 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1914 } 1915 1916 SDValue Mask, VL; 1917 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1918 1919 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1920 Idx, Mask, VL); 1921 1922 if (!VT.isFixedLengthVector()) 1923 return Gather; 1924 1925 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1926 } 1927 1928 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1929 const RISCVSubtarget &Subtarget) { 1930 MVT VT = Op.getSimpleValueType(); 1931 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1932 1933 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1934 1935 SDLoc DL(Op); 1936 SDValue Mask, VL; 1937 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1938 1939 MVT XLenVT = Subtarget.getXLenVT(); 1940 unsigned NumElts = Op.getNumOperands(); 1941 1942 if (VT.getVectorElementType() == MVT::i1) { 1943 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1944 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1945 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1946 } 1947 1948 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1949 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1950 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1951 } 1952 1953 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1954 // scalar integer chunks whose bit-width depends on the number of mask 1955 // bits and XLEN. 1956 // First, determine the most appropriate scalar integer type to use. This 1957 // is at most XLenVT, but may be shrunk to a smaller vector element type 1958 // according to the size of the final vector - use i8 chunks rather than 1959 // XLenVT if we're producing a v8i1. This results in more consistent 1960 // codegen across RV32 and RV64. 1961 unsigned NumViaIntegerBits = 1962 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1963 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1964 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1965 // If we have to use more than one INSERT_VECTOR_ELT then this 1966 // optimization is likely to increase code size; avoid peforming it in 1967 // such a case. We can use a load from a constant pool in this case. 1968 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1969 return SDValue(); 1970 // Now we can create our integer vector type. Note that it may be larger 1971 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1972 MVT IntegerViaVecVT = 1973 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1974 divideCeil(NumElts, NumViaIntegerBits)); 1975 1976 uint64_t Bits = 0; 1977 unsigned BitPos = 0, IntegerEltIdx = 0; 1978 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1979 1980 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1981 // Once we accumulate enough bits to fill our scalar type, insert into 1982 // our vector and clear our accumulated data. 1983 if (I != 0 && I % NumViaIntegerBits == 0) { 1984 if (NumViaIntegerBits <= 32) 1985 Bits = SignExtend64(Bits, 32); 1986 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1987 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1988 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1989 Bits = 0; 1990 BitPos = 0; 1991 IntegerEltIdx++; 1992 } 1993 SDValue V = Op.getOperand(I); 1994 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1995 Bits |= ((uint64_t)BitValue << BitPos); 1996 } 1997 1998 // Insert the (remaining) scalar value into position in our integer 1999 // vector type. 2000 if (NumViaIntegerBits <= 32) 2001 Bits = SignExtend64(Bits, 32); 2002 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2003 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2004 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2005 2006 if (NumElts < NumViaIntegerBits) { 2007 // If we're producing a smaller vector than our minimum legal integer 2008 // type, bitcast to the equivalent (known-legal) mask type, and extract 2009 // our final mask. 2010 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2011 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2012 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2013 DAG.getConstant(0, DL, XLenVT)); 2014 } else { 2015 // Else we must have produced an integer type with the same size as the 2016 // mask type; bitcast for the final result. 2017 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2018 Vec = DAG.getBitcast(VT, Vec); 2019 } 2020 2021 return Vec; 2022 } 2023 2024 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2025 // vector type, we have a legal equivalently-sized i8 type, so we can use 2026 // that. 2027 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2028 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2029 2030 SDValue WideVec; 2031 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2032 // For a splat, perform a scalar truncate before creating the wider 2033 // vector. 2034 assert(Splat.getValueType() == XLenVT && 2035 "Unexpected type for i1 splat value"); 2036 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2037 DAG.getConstant(1, DL, XLenVT)); 2038 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2039 } else { 2040 SmallVector<SDValue, 8> Ops(Op->op_values()); 2041 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2042 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2043 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2044 } 2045 2046 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2047 } 2048 2049 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2050 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2051 return Gather; 2052 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2053 : RISCVISD::VMV_V_X_VL; 2054 Splat = 2055 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2056 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2057 } 2058 2059 // Try and match index sequences, which we can lower to the vid instruction 2060 // with optional modifications. An all-undef vector is matched by 2061 // getSplatValue, above. 2062 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2063 int64_t StepNumerator = SimpleVID->StepNumerator; 2064 unsigned StepDenominator = SimpleVID->StepDenominator; 2065 int64_t Addend = SimpleVID->Addend; 2066 2067 assert(StepNumerator != 0 && "Invalid step"); 2068 bool Negate = false; 2069 int64_t SplatStepVal = StepNumerator; 2070 unsigned StepOpcode = ISD::MUL; 2071 if (StepNumerator != 1) { 2072 if (isPowerOf2_64(std::abs(StepNumerator))) { 2073 Negate = StepNumerator < 0; 2074 StepOpcode = ISD::SHL; 2075 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2076 } 2077 } 2078 2079 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2080 // threshold since it's the immediate value many RVV instructions accept. 2081 // There is no vmul.vi instruction so ensure multiply constant can fit in 2082 // a single addi instruction. 2083 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2084 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2085 isPowerOf2_32(StepDenominator) && 2086 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2087 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2088 // Convert right out of the scalable type so we can use standard ISD 2089 // nodes for the rest of the computation. If we used scalable types with 2090 // these, we'd lose the fixed-length vector info and generate worse 2091 // vsetvli code. 2092 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2093 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2094 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2095 SDValue SplatStep = DAG.getSplatBuildVector( 2096 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2097 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2098 } 2099 if (StepDenominator != 1) { 2100 SDValue SplatStep = DAG.getSplatBuildVector( 2101 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2102 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2103 } 2104 if (Addend != 0 || Negate) { 2105 SDValue SplatAddend = DAG.getSplatBuildVector( 2106 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2107 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2108 } 2109 return VID; 2110 } 2111 } 2112 2113 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2114 // when re-interpreted as a vector with a larger element type. For example, 2115 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2116 // could be instead splat as 2117 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2118 // TODO: This optimization could also work on non-constant splats, but it 2119 // would require bit-manipulation instructions to construct the splat value. 2120 SmallVector<SDValue> Sequence; 2121 unsigned EltBitSize = VT.getScalarSizeInBits(); 2122 const auto *BV = cast<BuildVectorSDNode>(Op); 2123 if (VT.isInteger() && EltBitSize < 64 && 2124 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2125 BV->getRepeatedSequence(Sequence) && 2126 (Sequence.size() * EltBitSize) <= 64) { 2127 unsigned SeqLen = Sequence.size(); 2128 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2129 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2130 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2131 ViaIntVT == MVT::i64) && 2132 "Unexpected sequence type"); 2133 2134 unsigned EltIdx = 0; 2135 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2136 uint64_t SplatValue = 0; 2137 // Construct the amalgamated value which can be splatted as this larger 2138 // vector type. 2139 for (const auto &SeqV : Sequence) { 2140 if (!SeqV.isUndef()) 2141 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2142 << (EltIdx * EltBitSize)); 2143 EltIdx++; 2144 } 2145 2146 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2147 // achieve better constant materializion. 2148 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2149 SplatValue = SignExtend64(SplatValue, 32); 2150 2151 // Since we can't introduce illegal i64 types at this stage, we can only 2152 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2153 // way we can use RVV instructions to splat. 2154 assert((ViaIntVT.bitsLE(XLenVT) || 2155 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2156 "Unexpected bitcast sequence"); 2157 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2158 SDValue ViaVL = 2159 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2160 MVT ViaContainerVT = 2161 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2162 SDValue Splat = 2163 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2164 DAG.getUNDEF(ViaContainerVT), 2165 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2166 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2167 return DAG.getBitcast(VT, Splat); 2168 } 2169 } 2170 2171 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2172 // which constitute a large proportion of the elements. In such cases we can 2173 // splat a vector with the dominant element and make up the shortfall with 2174 // INSERT_VECTOR_ELTs. 2175 // Note that this includes vectors of 2 elements by association. The 2176 // upper-most element is the "dominant" one, allowing us to use a splat to 2177 // "insert" the upper element, and an insert of the lower element at position 2178 // 0, which improves codegen. 2179 SDValue DominantValue; 2180 unsigned MostCommonCount = 0; 2181 DenseMap<SDValue, unsigned> ValueCounts; 2182 unsigned NumUndefElts = 2183 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2184 2185 // Track the number of scalar loads we know we'd be inserting, estimated as 2186 // any non-zero floating-point constant. Other kinds of element are either 2187 // already in registers or are materialized on demand. The threshold at which 2188 // a vector load is more desirable than several scalar materializion and 2189 // vector-insertion instructions is not known. 2190 unsigned NumScalarLoads = 0; 2191 2192 for (SDValue V : Op->op_values()) { 2193 if (V.isUndef()) 2194 continue; 2195 2196 ValueCounts.insert(std::make_pair(V, 0)); 2197 unsigned &Count = ValueCounts[V]; 2198 2199 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2200 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2201 2202 // Is this value dominant? In case of a tie, prefer the highest element as 2203 // it's cheaper to insert near the beginning of a vector than it is at the 2204 // end. 2205 if (++Count >= MostCommonCount) { 2206 DominantValue = V; 2207 MostCommonCount = Count; 2208 } 2209 } 2210 2211 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2212 unsigned NumDefElts = NumElts - NumUndefElts; 2213 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2214 2215 // Don't perform this optimization when optimizing for size, since 2216 // materializing elements and inserting them tends to cause code bloat. 2217 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2218 ((MostCommonCount > DominantValueCountThreshold) || 2219 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2220 // Start by splatting the most common element. 2221 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2222 2223 DenseSet<SDValue> Processed{DominantValue}; 2224 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2225 for (const auto &OpIdx : enumerate(Op->ops())) { 2226 const SDValue &V = OpIdx.value(); 2227 if (V.isUndef() || !Processed.insert(V).second) 2228 continue; 2229 if (ValueCounts[V] == 1) { 2230 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2231 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2232 } else { 2233 // Blend in all instances of this value using a VSELECT, using a 2234 // mask where each bit signals whether that element is the one 2235 // we're after. 2236 SmallVector<SDValue> Ops; 2237 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2238 return DAG.getConstant(V == V1, DL, XLenVT); 2239 }); 2240 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2241 DAG.getBuildVector(SelMaskTy, DL, Ops), 2242 DAG.getSplatBuildVector(VT, DL, V), Vec); 2243 } 2244 } 2245 2246 return Vec; 2247 } 2248 2249 return SDValue(); 2250 } 2251 2252 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2253 SDValue Lo, SDValue Hi, SDValue VL, 2254 SelectionDAG &DAG) { 2255 if (!Passthru) 2256 Passthru = DAG.getUNDEF(VT); 2257 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2258 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2259 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2260 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2261 // node in order to try and match RVV vector/scalar instructions. 2262 if ((LoC >> 31) == HiC) 2263 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2264 2265 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2266 // vmv.v.x whose EEW = 32 to lower it. 2267 auto *Const = dyn_cast<ConstantSDNode>(VL); 2268 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2269 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2270 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2271 // access the subtarget here now. 2272 auto InterVec = DAG.getNode( 2273 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2274 DAG.getRegister(RISCV::X0, MVT::i32)); 2275 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2276 } 2277 } 2278 2279 // Fall back to a stack store and stride x0 vector load. 2280 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2281 Hi, VL); 2282 } 2283 2284 // Called by type legalization to handle splat of i64 on RV32. 2285 // FIXME: We can optimize this when the type has sign or zero bits in one 2286 // of the halves. 2287 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2288 SDValue Scalar, SDValue VL, 2289 SelectionDAG &DAG) { 2290 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2291 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2292 DAG.getConstant(0, DL, MVT::i32)); 2293 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2294 DAG.getConstant(1, DL, MVT::i32)); 2295 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2296 } 2297 2298 // This function lowers a splat of a scalar operand Splat with the vector 2299 // length VL. It ensures the final sequence is type legal, which is useful when 2300 // lowering a splat after type legalization. 2301 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2302 MVT VT, SDLoc DL, SelectionDAG &DAG, 2303 const RISCVSubtarget &Subtarget) { 2304 bool HasPassthru = Passthru && !Passthru.isUndef(); 2305 if (!HasPassthru && !Passthru) 2306 Passthru = DAG.getUNDEF(VT); 2307 if (VT.isFloatingPoint()) { 2308 // If VL is 1, we could use vfmv.s.f. 2309 if (isOneConstant(VL)) 2310 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2311 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2312 } 2313 2314 MVT XLenVT = Subtarget.getXLenVT(); 2315 2316 // Simplest case is that the operand needs to be promoted to XLenVT. 2317 if (Scalar.getValueType().bitsLE(XLenVT)) { 2318 // If the operand is a constant, sign extend to increase our chances 2319 // of being able to use a .vi instruction. ANY_EXTEND would become a 2320 // a zero extend and the simm5 check in isel would fail. 2321 // FIXME: Should we ignore the upper bits in isel instead? 2322 unsigned ExtOpc = 2323 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2324 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2325 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2326 // If VL is 1 and the scalar value won't benefit from immediate, we could 2327 // use vmv.s.x. 2328 if (isOneConstant(VL) && 2329 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2330 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2331 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2332 } 2333 2334 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2335 "Unexpected scalar for splat lowering!"); 2336 2337 if (isOneConstant(VL) && isNullConstant(Scalar)) 2338 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2339 DAG.getConstant(0, DL, XLenVT), VL); 2340 2341 // Otherwise use the more complicated splatting algorithm. 2342 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2343 } 2344 2345 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2346 const RISCVSubtarget &Subtarget) { 2347 // We need to be able to widen elements to the next larger integer type. 2348 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2349 return false; 2350 2351 int Size = Mask.size(); 2352 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2353 2354 int Srcs[] = {-1, -1}; 2355 for (int i = 0; i != Size; ++i) { 2356 // Ignore undef elements. 2357 if (Mask[i] < 0) 2358 continue; 2359 2360 // Is this an even or odd element. 2361 int Pol = i % 2; 2362 2363 // Ensure we consistently use the same source for this element polarity. 2364 int Src = Mask[i] / Size; 2365 if (Srcs[Pol] < 0) 2366 Srcs[Pol] = Src; 2367 if (Srcs[Pol] != Src) 2368 return false; 2369 2370 // Make sure the element within the source is appropriate for this element 2371 // in the destination. 2372 int Elt = Mask[i] % Size; 2373 if (Elt != i / 2) 2374 return false; 2375 } 2376 2377 // We need to find a source for each polarity and they can't be the same. 2378 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2379 return false; 2380 2381 // Swap the sources if the second source was in the even polarity. 2382 SwapSources = Srcs[0] > Srcs[1]; 2383 2384 return true; 2385 } 2386 2387 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2388 /// and then extract the original number of elements from the rotated result. 2389 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2390 /// returned rotation amount is for a rotate right, where elements move from 2391 /// higher elements to lower elements. \p LoSrc indicates the first source 2392 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2393 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2394 /// 0 or 1 if a rotation is found. 2395 /// 2396 /// NOTE: We talk about rotate to the right which matches how bit shift and 2397 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2398 /// and the table below write vectors with the lowest elements on the left. 2399 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2400 int Size = Mask.size(); 2401 2402 // We need to detect various ways of spelling a rotation: 2403 // [11, 12, 13, 14, 15, 0, 1, 2] 2404 // [-1, 12, 13, 14, -1, -1, 1, -1] 2405 // [-1, -1, -1, -1, -1, -1, 1, 2] 2406 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2407 // [-1, 4, 5, 6, -1, -1, 9, -1] 2408 // [-1, 4, 5, 6, -1, -1, -1, -1] 2409 int Rotation = 0; 2410 LoSrc = -1; 2411 HiSrc = -1; 2412 for (int i = 0; i != Size; ++i) { 2413 int M = Mask[i]; 2414 if (M < 0) 2415 continue; 2416 2417 // Determine where a rotate vector would have started. 2418 int StartIdx = i - (M % Size); 2419 // The identity rotation isn't interesting, stop. 2420 if (StartIdx == 0) 2421 return -1; 2422 2423 // If we found the tail of a vector the rotation must be the missing 2424 // front. If we found the head of a vector, it must be how much of the 2425 // head. 2426 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2427 2428 if (Rotation == 0) 2429 Rotation = CandidateRotation; 2430 else if (Rotation != CandidateRotation) 2431 // The rotations don't match, so we can't match this mask. 2432 return -1; 2433 2434 // Compute which value this mask is pointing at. 2435 int MaskSrc = M < Size ? 0 : 1; 2436 2437 // Compute which of the two target values this index should be assigned to. 2438 // This reflects whether the high elements are remaining or the low elemnts 2439 // are remaining. 2440 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2441 2442 // Either set up this value if we've not encountered it before, or check 2443 // that it remains consistent. 2444 if (TargetSrc < 0) 2445 TargetSrc = MaskSrc; 2446 else if (TargetSrc != MaskSrc) 2447 // This may be a rotation, but it pulls from the inputs in some 2448 // unsupported interleaving. 2449 return -1; 2450 } 2451 2452 // Check that we successfully analyzed the mask, and normalize the results. 2453 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2454 assert((LoSrc >= 0 || HiSrc >= 0) && 2455 "Failed to find a rotated input vector!"); 2456 2457 return Rotation; 2458 } 2459 2460 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2461 const RISCVSubtarget &Subtarget) { 2462 SDValue V1 = Op.getOperand(0); 2463 SDValue V2 = Op.getOperand(1); 2464 SDLoc DL(Op); 2465 MVT XLenVT = Subtarget.getXLenVT(); 2466 MVT VT = Op.getSimpleValueType(); 2467 unsigned NumElts = VT.getVectorNumElements(); 2468 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2469 2470 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2471 2472 SDValue TrueMask, VL; 2473 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2474 2475 if (SVN->isSplat()) { 2476 const int Lane = SVN->getSplatIndex(); 2477 if (Lane >= 0) { 2478 MVT SVT = VT.getVectorElementType(); 2479 2480 // Turn splatted vector load into a strided load with an X0 stride. 2481 SDValue V = V1; 2482 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2483 // with undef. 2484 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2485 int Offset = Lane; 2486 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2487 int OpElements = 2488 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2489 V = V.getOperand(Offset / OpElements); 2490 Offset %= OpElements; 2491 } 2492 2493 // We need to ensure the load isn't atomic or volatile. 2494 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2495 auto *Ld = cast<LoadSDNode>(V); 2496 Offset *= SVT.getStoreSize(); 2497 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2498 TypeSize::Fixed(Offset), DL); 2499 2500 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2501 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2502 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2503 SDValue IntID = 2504 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2505 SDValue Ops[] = {Ld->getChain(), 2506 IntID, 2507 DAG.getUNDEF(ContainerVT), 2508 NewAddr, 2509 DAG.getRegister(RISCV::X0, XLenVT), 2510 VL}; 2511 SDValue NewLoad = DAG.getMemIntrinsicNode( 2512 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2513 DAG.getMachineFunction().getMachineMemOperand( 2514 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2515 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2516 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2517 } 2518 2519 // Otherwise use a scalar load and splat. This will give the best 2520 // opportunity to fold a splat into the operation. ISel can turn it into 2521 // the x0 strided load if we aren't able to fold away the select. 2522 if (SVT.isFloatingPoint()) 2523 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2524 Ld->getPointerInfo().getWithOffset(Offset), 2525 Ld->getOriginalAlign(), 2526 Ld->getMemOperand()->getFlags()); 2527 else 2528 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2529 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2530 Ld->getOriginalAlign(), 2531 Ld->getMemOperand()->getFlags()); 2532 DAG.makeEquivalentMemoryOrdering(Ld, V); 2533 2534 unsigned Opc = 2535 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2536 SDValue Splat = 2537 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2538 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2539 } 2540 2541 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2542 assert(Lane < (int)NumElts && "Unexpected lane!"); 2543 SDValue Gather = 2544 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2545 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2546 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2547 } 2548 } 2549 2550 ArrayRef<int> Mask = SVN->getMask(); 2551 2552 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2553 // be undef which can be handled with a single SLIDEDOWN/UP. 2554 int LoSrc, HiSrc; 2555 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2556 if (Rotation > 0) { 2557 SDValue LoV, HiV; 2558 if (LoSrc >= 0) { 2559 LoV = LoSrc == 0 ? V1 : V2; 2560 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2561 } 2562 if (HiSrc >= 0) { 2563 HiV = HiSrc == 0 ? V1 : V2; 2564 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2565 } 2566 2567 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2568 // to slide LoV up by (NumElts - Rotation). 2569 unsigned InvRotate = NumElts - Rotation; 2570 2571 SDValue Res = DAG.getUNDEF(ContainerVT); 2572 if (HiV) { 2573 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2574 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2575 // causes multiple vsetvlis in some test cases such as lowering 2576 // reduce.mul 2577 SDValue DownVL = VL; 2578 if (LoV) 2579 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2580 Res = 2581 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2582 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2583 } 2584 if (LoV) 2585 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2586 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2587 2588 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2589 } 2590 2591 // Detect an interleave shuffle and lower to 2592 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2593 bool SwapSources; 2594 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2595 // Swap sources if needed. 2596 if (SwapSources) 2597 std::swap(V1, V2); 2598 2599 // Extract the lower half of the vectors. 2600 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2601 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2602 DAG.getConstant(0, DL, XLenVT)); 2603 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2604 DAG.getConstant(0, DL, XLenVT)); 2605 2606 // Double the element width and halve the number of elements in an int type. 2607 unsigned EltBits = VT.getScalarSizeInBits(); 2608 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2609 MVT WideIntVT = 2610 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2611 // Convert this to a scalable vector. We need to base this on the 2612 // destination size to ensure there's always a type with a smaller LMUL. 2613 MVT WideIntContainerVT = 2614 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2615 2616 // Convert sources to scalable vectors with the same element count as the 2617 // larger type. 2618 MVT HalfContainerVT = MVT::getVectorVT( 2619 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2620 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2621 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2622 2623 // Cast sources to integer. 2624 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2625 MVT IntHalfVT = 2626 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2627 V1 = DAG.getBitcast(IntHalfVT, V1); 2628 V2 = DAG.getBitcast(IntHalfVT, V2); 2629 2630 // Freeze V2 since we use it twice and we need to be sure that the add and 2631 // multiply see the same value. 2632 V2 = DAG.getFreeze(V2); 2633 2634 // Recreate TrueMask using the widened type's element count. 2635 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2636 2637 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2638 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2639 V2, TrueMask, VL); 2640 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2641 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2642 DAG.getUNDEF(IntHalfVT), 2643 DAG.getAllOnesConstant(DL, XLenVT)); 2644 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2645 V2, Multiplier, TrueMask, VL); 2646 // Add the new copies to our previous addition giving us 2^eltbits copies of 2647 // V2. This is equivalent to shifting V2 left by eltbits. This should 2648 // combine with the vwmulu.vv above to form vwmaccu.vv. 2649 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2650 TrueMask, VL); 2651 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2652 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2653 // vector VT. 2654 ContainerVT = 2655 MVT::getVectorVT(VT.getVectorElementType(), 2656 WideIntContainerVT.getVectorElementCount() * 2); 2657 Add = DAG.getBitcast(ContainerVT, Add); 2658 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2659 } 2660 2661 // Detect shuffles which can be re-expressed as vector selects; these are 2662 // shuffles in which each element in the destination is taken from an element 2663 // at the corresponding index in either source vectors. 2664 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2665 int MaskIndex = MaskIdx.value(); 2666 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2667 }); 2668 2669 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2670 2671 SmallVector<SDValue> MaskVals; 2672 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2673 // merged with a second vrgather. 2674 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2675 2676 // By default we preserve the original operand order, and use a mask to 2677 // select LHS as true and RHS as false. However, since RVV vector selects may 2678 // feature splats but only on the LHS, we may choose to invert our mask and 2679 // instead select between RHS and LHS. 2680 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2681 bool InvertMask = IsSelect == SwapOps; 2682 2683 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2684 // half. 2685 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2686 2687 // Now construct the mask that will be used by the vselect or blended 2688 // vrgather operation. For vrgathers, construct the appropriate indices into 2689 // each vector. 2690 for (int MaskIndex : Mask) { 2691 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2692 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2693 if (!IsSelect) { 2694 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2695 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2696 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2697 : DAG.getUNDEF(XLenVT)); 2698 GatherIndicesRHS.push_back( 2699 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2700 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2701 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2702 ++LHSIndexCounts[MaskIndex]; 2703 if (!IsLHSOrUndefIndex) 2704 ++RHSIndexCounts[MaskIndex - NumElts]; 2705 } 2706 } 2707 2708 if (SwapOps) { 2709 std::swap(V1, V2); 2710 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2711 } 2712 2713 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2714 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2715 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2716 2717 if (IsSelect) 2718 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2719 2720 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2721 // On such a large vector we're unable to use i8 as the index type. 2722 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2723 // may involve vector splitting if we're already at LMUL=8, or our 2724 // user-supplied maximum fixed-length LMUL. 2725 return SDValue(); 2726 } 2727 2728 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2729 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2730 MVT IndexVT = VT.changeTypeToInteger(); 2731 // Since we can't introduce illegal index types at this stage, use i16 and 2732 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2733 // than XLenVT. 2734 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2735 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2736 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2737 } 2738 2739 MVT IndexContainerVT = 2740 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2741 2742 SDValue Gather; 2743 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2744 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2745 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2746 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2747 Subtarget); 2748 } else { 2749 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2750 // If only one index is used, we can use a "splat" vrgather. 2751 // TODO: We can splat the most-common index and fix-up any stragglers, if 2752 // that's beneficial. 2753 if (LHSIndexCounts.size() == 1) { 2754 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2755 Gather = 2756 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2757 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2758 } else { 2759 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2760 LHSIndices = 2761 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2762 2763 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2764 TrueMask, VL); 2765 } 2766 } 2767 2768 // If a second vector operand is used by this shuffle, blend it in with an 2769 // additional vrgather. 2770 if (!V2.isUndef()) { 2771 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2772 // If only one index is used, we can use a "splat" vrgather. 2773 // TODO: We can splat the most-common index and fix-up any stragglers, if 2774 // that's beneficial. 2775 if (RHSIndexCounts.size() == 1) { 2776 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2777 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2778 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2779 } else { 2780 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2781 RHSIndices = 2782 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2783 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2784 VL); 2785 } 2786 2787 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2788 SelectMask = 2789 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2790 2791 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2792 Gather, VL); 2793 } 2794 2795 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2796 } 2797 2798 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2799 // Support splats for any type. These should type legalize well. 2800 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2801 return true; 2802 2803 // Only support legal VTs for other shuffles for now. 2804 if (!isTypeLegal(VT)) 2805 return false; 2806 2807 MVT SVT = VT.getSimpleVT(); 2808 2809 bool SwapSources; 2810 int LoSrc, HiSrc; 2811 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2812 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2813 } 2814 2815 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2816 // the exponent. 2817 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2818 MVT VT = Op.getSimpleValueType(); 2819 unsigned EltSize = VT.getScalarSizeInBits(); 2820 SDValue Src = Op.getOperand(0); 2821 SDLoc DL(Op); 2822 2823 // We need a FP type that can represent the value. 2824 // TODO: Use f16 for i8 when possible? 2825 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2826 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2827 2828 // Legal types should have been checked in the RISCVTargetLowering 2829 // constructor. 2830 // TODO: Splitting may make sense in some cases. 2831 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2832 "Expected legal float type!"); 2833 2834 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2835 // The trailing zero count is equal to log2 of this single bit value. 2836 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2837 SDValue Neg = 2838 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2839 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2840 } 2841 2842 // We have a legal FP type, convert to it. 2843 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2844 // Bitcast to integer and shift the exponent to the LSB. 2845 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2846 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2847 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2848 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2849 DAG.getConstant(ShiftAmt, DL, IntVT)); 2850 // Truncate back to original type to allow vnsrl. 2851 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2852 // The exponent contains log2 of the value in biased form. 2853 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2854 2855 // For trailing zeros, we just need to subtract the bias. 2856 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2857 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2858 DAG.getConstant(ExponentBias, DL, VT)); 2859 2860 // For leading zeros, we need to remove the bias and convert from log2 to 2861 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2862 unsigned Adjust = ExponentBias + (EltSize - 1); 2863 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2864 } 2865 2866 // While RVV has alignment restrictions, we should always be able to load as a 2867 // legal equivalently-sized byte-typed vector instead. This method is 2868 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2869 // the load is already correctly-aligned, it returns SDValue(). 2870 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 auto *Load = cast<LoadSDNode>(Op); 2873 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2874 2875 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2876 Load->getMemoryVT(), 2877 *Load->getMemOperand())) 2878 return SDValue(); 2879 2880 SDLoc DL(Op); 2881 MVT VT = Op.getSimpleValueType(); 2882 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2883 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2884 "Unexpected unaligned RVV load type"); 2885 MVT NewVT = 2886 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2887 assert(NewVT.isValid() && 2888 "Expecting equally-sized RVV vector types to be legal"); 2889 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2890 Load->getPointerInfo(), Load->getOriginalAlign(), 2891 Load->getMemOperand()->getFlags()); 2892 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2893 } 2894 2895 // While RVV has alignment restrictions, we should always be able to store as a 2896 // legal equivalently-sized byte-typed vector instead. This method is 2897 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2898 // returns SDValue() if the store is already correctly aligned. 2899 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2900 SelectionDAG &DAG) const { 2901 auto *Store = cast<StoreSDNode>(Op); 2902 assert(Store && Store->getValue().getValueType().isVector() && 2903 "Expected vector store"); 2904 2905 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2906 Store->getMemoryVT(), 2907 *Store->getMemOperand())) 2908 return SDValue(); 2909 2910 SDLoc DL(Op); 2911 SDValue StoredVal = Store->getValue(); 2912 MVT VT = StoredVal.getSimpleValueType(); 2913 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2914 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2915 "Unexpected unaligned RVV store type"); 2916 MVT NewVT = 2917 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2918 assert(NewVT.isValid() && 2919 "Expecting equally-sized RVV vector types to be legal"); 2920 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2921 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2922 Store->getPointerInfo(), Store->getOriginalAlign(), 2923 Store->getMemOperand()->getFlags()); 2924 } 2925 2926 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2927 SelectionDAG &DAG) const { 2928 switch (Op.getOpcode()) { 2929 default: 2930 report_fatal_error("unimplemented operand"); 2931 case ISD::GlobalAddress: 2932 return lowerGlobalAddress(Op, DAG); 2933 case ISD::BlockAddress: 2934 return lowerBlockAddress(Op, DAG); 2935 case ISD::ConstantPool: 2936 return lowerConstantPool(Op, DAG); 2937 case ISD::JumpTable: 2938 return lowerJumpTable(Op, DAG); 2939 case ISD::GlobalTLSAddress: 2940 return lowerGlobalTLSAddress(Op, DAG); 2941 case ISD::SELECT: 2942 return lowerSELECT(Op, DAG); 2943 case ISD::BRCOND: 2944 return lowerBRCOND(Op, DAG); 2945 case ISD::VASTART: 2946 return lowerVASTART(Op, DAG); 2947 case ISD::FRAMEADDR: 2948 return lowerFRAMEADDR(Op, DAG); 2949 case ISD::RETURNADDR: 2950 return lowerRETURNADDR(Op, DAG); 2951 case ISD::SHL_PARTS: 2952 return lowerShiftLeftParts(Op, DAG); 2953 case ISD::SRA_PARTS: 2954 return lowerShiftRightParts(Op, DAG, true); 2955 case ISD::SRL_PARTS: 2956 return lowerShiftRightParts(Op, DAG, false); 2957 case ISD::BITCAST: { 2958 SDLoc DL(Op); 2959 EVT VT = Op.getValueType(); 2960 SDValue Op0 = Op.getOperand(0); 2961 EVT Op0VT = Op0.getValueType(); 2962 MVT XLenVT = Subtarget.getXLenVT(); 2963 if (VT.isFixedLengthVector()) { 2964 // We can handle fixed length vector bitcasts with a simple replacement 2965 // in isel. 2966 if (Op0VT.isFixedLengthVector()) 2967 return Op; 2968 // When bitcasting from scalar to fixed-length vector, insert the scalar 2969 // into a one-element vector of the result type, and perform a vector 2970 // bitcast. 2971 if (!Op0VT.isVector()) { 2972 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2973 if (!isTypeLegal(BVT)) 2974 return SDValue(); 2975 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2976 DAG.getUNDEF(BVT), Op0, 2977 DAG.getConstant(0, DL, XLenVT))); 2978 } 2979 return SDValue(); 2980 } 2981 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2982 // thus: bitcast the vector to a one-element vector type whose element type 2983 // is the same as the result type, and extract the first element. 2984 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2985 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2986 if (!isTypeLegal(BVT)) 2987 return SDValue(); 2988 SDValue BVec = DAG.getBitcast(BVT, Op0); 2989 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2990 DAG.getConstant(0, DL, XLenVT)); 2991 } 2992 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2993 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2994 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2995 return FPConv; 2996 } 2997 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2998 Subtarget.hasStdExtF()) { 2999 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3000 SDValue FPConv = 3001 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3002 return FPConv; 3003 } 3004 return SDValue(); 3005 } 3006 case ISD::INTRINSIC_WO_CHAIN: 3007 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3008 case ISD::INTRINSIC_W_CHAIN: 3009 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3010 case ISD::INTRINSIC_VOID: 3011 return LowerINTRINSIC_VOID(Op, DAG); 3012 case ISD::BSWAP: 3013 case ISD::BITREVERSE: { 3014 MVT VT = Op.getSimpleValueType(); 3015 SDLoc DL(Op); 3016 if (Subtarget.hasStdExtZbp()) { 3017 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3018 // Start with the maximum immediate value which is the bitwidth - 1. 3019 unsigned Imm = VT.getSizeInBits() - 1; 3020 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3021 if (Op.getOpcode() == ISD::BSWAP) 3022 Imm &= ~0x7U; 3023 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3024 DAG.getConstant(Imm, DL, VT)); 3025 } 3026 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3027 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3028 // Expand bitreverse to a bswap(rev8) followed by brev8. 3029 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3030 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3031 // as brev8 by an isel pattern. 3032 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3033 DAG.getConstant(7, DL, VT)); 3034 } 3035 case ISD::FSHL: 3036 case ISD::FSHR: { 3037 MVT VT = Op.getSimpleValueType(); 3038 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3039 SDLoc DL(Op); 3040 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3041 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3042 // accidentally setting the extra bit. 3043 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3044 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3045 DAG.getConstant(ShAmtWidth, DL, VT)); 3046 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3047 // instruction use different orders. fshl will return its first operand for 3048 // shift of zero, fshr will return its second operand. fsl and fsr both 3049 // return rs1 so the ISD nodes need to have different operand orders. 3050 // Shift amount is in rs2. 3051 SDValue Op0 = Op.getOperand(0); 3052 SDValue Op1 = Op.getOperand(1); 3053 unsigned Opc = RISCVISD::FSL; 3054 if (Op.getOpcode() == ISD::FSHR) { 3055 std::swap(Op0, Op1); 3056 Opc = RISCVISD::FSR; 3057 } 3058 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3059 } 3060 case ISD::TRUNCATE: 3061 // Only custom-lower vector truncates 3062 if (!Op.getSimpleValueType().isVector()) 3063 return Op; 3064 return lowerVectorTruncLike(Op, DAG); 3065 case ISD::ANY_EXTEND: 3066 case ISD::ZERO_EXTEND: 3067 if (Op.getOperand(0).getValueType().isVector() && 3068 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3069 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3070 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3071 case ISD::SIGN_EXTEND: 3072 if (Op.getOperand(0).getValueType().isVector() && 3073 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3074 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3075 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3076 case ISD::SPLAT_VECTOR_PARTS: 3077 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3078 case ISD::INSERT_VECTOR_ELT: 3079 return lowerINSERT_VECTOR_ELT(Op, DAG); 3080 case ISD::EXTRACT_VECTOR_ELT: 3081 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3082 case ISD::VSCALE: { 3083 MVT VT = Op.getSimpleValueType(); 3084 SDLoc DL(Op); 3085 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3086 // We define our scalable vector types for lmul=1 to use a 64 bit known 3087 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3088 // vscale as VLENB / 8. 3089 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3090 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3091 report_fatal_error("Support for VLEN==32 is incomplete."); 3092 // We assume VLENB is a multiple of 8. We manually choose the best shift 3093 // here because SimplifyDemandedBits isn't always able to simplify it. 3094 uint64_t Val = Op.getConstantOperandVal(0); 3095 if (isPowerOf2_64(Val)) { 3096 uint64_t Log2 = Log2_64(Val); 3097 if (Log2 < 3) 3098 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3099 DAG.getConstant(3 - Log2, DL, VT)); 3100 if (Log2 > 3) 3101 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3102 DAG.getConstant(Log2 - 3, DL, VT)); 3103 return VLENB; 3104 } 3105 // If the multiplier is a multiple of 8, scale it down to avoid needing 3106 // to shift the VLENB value. 3107 if ((Val % 8) == 0) 3108 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3109 DAG.getConstant(Val / 8, DL, VT)); 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 case ISD::FP_ROUND: 3131 if (!Op.getValueType().isVector()) 3132 return Op; 3133 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3134 case ISD::FP_TO_SINT: 3135 case ISD::FP_TO_UINT: 3136 case ISD::SINT_TO_FP: 3137 case ISD::UINT_TO_FP: { 3138 // RVV can only do fp<->int conversions to types half/double the size as 3139 // the source. We custom-lower any conversions that do two hops into 3140 // sequences. 3141 MVT VT = Op.getSimpleValueType(); 3142 if (!VT.isVector()) 3143 return Op; 3144 SDLoc DL(Op); 3145 SDValue Src = Op.getOperand(0); 3146 MVT EltVT = VT.getVectorElementType(); 3147 MVT SrcVT = Src.getSimpleValueType(); 3148 MVT SrcEltVT = SrcVT.getVectorElementType(); 3149 unsigned EltSize = EltVT.getSizeInBits(); 3150 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3151 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3152 "Unexpected vector element types"); 3153 3154 bool IsInt2FP = SrcEltVT.isInteger(); 3155 // Widening conversions 3156 if (EltSize > (2 * SrcEltSize)) { 3157 if (IsInt2FP) { 3158 // Do a regular integer sign/zero extension then convert to float. 3159 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3160 VT.getVectorElementCount()); 3161 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3162 ? ISD::ZERO_EXTEND 3163 : ISD::SIGN_EXTEND; 3164 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3165 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3166 } 3167 // FP2Int 3168 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3169 // Do one doubling fp_extend then complete the operation by converting 3170 // to int. 3171 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3172 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3173 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3174 } 3175 3176 // Narrowing conversions 3177 if (SrcEltSize > (2 * EltSize)) { 3178 if (IsInt2FP) { 3179 // One narrowing int_to_fp, then an fp_round. 3180 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3181 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3182 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3183 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3184 } 3185 // FP2Int 3186 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3187 // representable by the integer, the result is poison. 3188 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3189 VT.getVectorElementCount()); 3190 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3191 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3192 } 3193 3194 // Scalable vectors can exit here. Patterns will handle equally-sized 3195 // conversions halving/doubling ones. 3196 if (!VT.isFixedLengthVector()) 3197 return Op; 3198 3199 // For fixed-length vectors we lower to a custom "VL" node. 3200 unsigned RVVOpc = 0; 3201 switch (Op.getOpcode()) { 3202 default: 3203 llvm_unreachable("Impossible opcode"); 3204 case ISD::FP_TO_SINT: 3205 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3206 break; 3207 case ISD::FP_TO_UINT: 3208 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3209 break; 3210 case ISD::SINT_TO_FP: 3211 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3212 break; 3213 case ISD::UINT_TO_FP: 3214 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3215 break; 3216 } 3217 3218 MVT ContainerVT, SrcContainerVT; 3219 // Derive the reference container type from the larger vector type. 3220 if (SrcEltSize > EltSize) { 3221 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3222 ContainerVT = 3223 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3224 } else { 3225 ContainerVT = getContainerForFixedLengthVector(VT); 3226 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3227 } 3228 3229 SDValue Mask, VL; 3230 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3231 3232 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3233 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3234 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3235 } 3236 case ISD::FP_TO_SINT_SAT: 3237 case ISD::FP_TO_UINT_SAT: 3238 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3239 case ISD::FTRUNC: 3240 case ISD::FCEIL: 3241 case ISD::FFLOOR: 3242 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3243 case ISD::FROUND: 3244 return lowerFROUND(Op, DAG); 3245 case ISD::VECREDUCE_ADD: 3246 case ISD::VECREDUCE_UMAX: 3247 case ISD::VECREDUCE_SMAX: 3248 case ISD::VECREDUCE_UMIN: 3249 case ISD::VECREDUCE_SMIN: 3250 return lowerVECREDUCE(Op, DAG); 3251 case ISD::VECREDUCE_AND: 3252 case ISD::VECREDUCE_OR: 3253 case ISD::VECREDUCE_XOR: 3254 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3255 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3256 return lowerVECREDUCE(Op, DAG); 3257 case ISD::VECREDUCE_FADD: 3258 case ISD::VECREDUCE_SEQ_FADD: 3259 case ISD::VECREDUCE_FMIN: 3260 case ISD::VECREDUCE_FMAX: 3261 return lowerFPVECREDUCE(Op, DAG); 3262 case ISD::VP_REDUCE_ADD: 3263 case ISD::VP_REDUCE_UMAX: 3264 case ISD::VP_REDUCE_SMAX: 3265 case ISD::VP_REDUCE_UMIN: 3266 case ISD::VP_REDUCE_SMIN: 3267 case ISD::VP_REDUCE_FADD: 3268 case ISD::VP_REDUCE_SEQ_FADD: 3269 case ISD::VP_REDUCE_FMIN: 3270 case ISD::VP_REDUCE_FMAX: 3271 return lowerVPREDUCE(Op, DAG); 3272 case ISD::VP_REDUCE_AND: 3273 case ISD::VP_REDUCE_OR: 3274 case ISD::VP_REDUCE_XOR: 3275 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3276 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3277 return lowerVPREDUCE(Op, DAG); 3278 case ISD::INSERT_SUBVECTOR: 3279 return lowerINSERT_SUBVECTOR(Op, DAG); 3280 case ISD::EXTRACT_SUBVECTOR: 3281 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3282 case ISD::STEP_VECTOR: 3283 return lowerSTEP_VECTOR(Op, DAG); 3284 case ISD::VECTOR_REVERSE: 3285 return lowerVECTOR_REVERSE(Op, DAG); 3286 case ISD::VECTOR_SPLICE: 3287 return lowerVECTOR_SPLICE(Op, DAG); 3288 case ISD::BUILD_VECTOR: 3289 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3290 case ISD::SPLAT_VECTOR: 3291 if (Op.getValueType().getVectorElementType() == MVT::i1) 3292 return lowerVectorMaskSplat(Op, DAG); 3293 return SDValue(); 3294 case ISD::VECTOR_SHUFFLE: 3295 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3296 case ISD::CONCAT_VECTORS: { 3297 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3298 // better than going through the stack, as the default expansion does. 3299 SDLoc DL(Op); 3300 MVT VT = Op.getSimpleValueType(); 3301 unsigned NumOpElts = 3302 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3303 SDValue Vec = DAG.getUNDEF(VT); 3304 for (const auto &OpIdx : enumerate(Op->ops())) { 3305 SDValue SubVec = OpIdx.value(); 3306 // Don't insert undef subvectors. 3307 if (SubVec.isUndef()) 3308 continue; 3309 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3310 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3311 } 3312 return Vec; 3313 } 3314 case ISD::LOAD: 3315 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3316 return V; 3317 if (Op.getValueType().isFixedLengthVector()) 3318 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3319 return Op; 3320 case ISD::STORE: 3321 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3322 return V; 3323 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3324 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3325 return Op; 3326 case ISD::MLOAD: 3327 case ISD::VP_LOAD: 3328 return lowerMaskedLoad(Op, DAG); 3329 case ISD::MSTORE: 3330 case ISD::VP_STORE: 3331 return lowerMaskedStore(Op, DAG); 3332 case ISD::SETCC: 3333 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3334 case ISD::ADD: 3335 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3336 case ISD::SUB: 3337 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3338 case ISD::MUL: 3339 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3340 case ISD::MULHS: 3341 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3342 case ISD::MULHU: 3343 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3344 case ISD::AND: 3345 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3346 RISCVISD::AND_VL); 3347 case ISD::OR: 3348 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3349 RISCVISD::OR_VL); 3350 case ISD::XOR: 3351 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3352 RISCVISD::XOR_VL); 3353 case ISD::SDIV: 3354 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3355 case ISD::SREM: 3356 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3357 case ISD::UDIV: 3358 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3359 case ISD::UREM: 3360 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3361 case ISD::SHL: 3362 case ISD::SRA: 3363 case ISD::SRL: 3364 if (Op.getSimpleValueType().isFixedLengthVector()) 3365 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3366 // This can be called for an i32 shift amount that needs to be promoted. 3367 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3368 "Unexpected custom legalisation"); 3369 return SDValue(); 3370 case ISD::SADDSAT: 3371 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3372 case ISD::UADDSAT: 3373 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3374 case ISD::SSUBSAT: 3375 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3376 case ISD::USUBSAT: 3377 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3378 case ISD::FADD: 3379 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3380 case ISD::FSUB: 3381 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3382 case ISD::FMUL: 3383 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3384 case ISD::FDIV: 3385 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3386 case ISD::FNEG: 3387 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3388 case ISD::FABS: 3389 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3390 case ISD::FSQRT: 3391 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3392 case ISD::FMA: 3393 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3394 case ISD::SMIN: 3395 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3396 case ISD::SMAX: 3397 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3398 case ISD::UMIN: 3399 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3400 case ISD::UMAX: 3401 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3402 case ISD::FMINNUM: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3404 case ISD::FMAXNUM: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3406 case ISD::ABS: 3407 return lowerABS(Op, DAG); 3408 case ISD::CTLZ_ZERO_UNDEF: 3409 case ISD::CTTZ_ZERO_UNDEF: 3410 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3411 case ISD::VSELECT: 3412 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3413 case ISD::FCOPYSIGN: 3414 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3415 case ISD::MGATHER: 3416 case ISD::VP_GATHER: 3417 return lowerMaskedGather(Op, DAG); 3418 case ISD::MSCATTER: 3419 case ISD::VP_SCATTER: 3420 return lowerMaskedScatter(Op, DAG); 3421 case ISD::FLT_ROUNDS_: 3422 return lowerGET_ROUNDING(Op, DAG); 3423 case ISD::SET_ROUNDING: 3424 return lowerSET_ROUNDING(Op, DAG); 3425 case ISD::VP_SELECT: 3426 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3427 case ISD::VP_MERGE: 3428 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3429 case ISD::VP_ADD: 3430 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3431 case ISD::VP_SUB: 3432 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3433 case ISD::VP_MUL: 3434 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3435 case ISD::VP_SDIV: 3436 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3437 case ISD::VP_UDIV: 3438 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3439 case ISD::VP_SREM: 3440 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3441 case ISD::VP_UREM: 3442 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3443 case ISD::VP_AND: 3444 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3445 case ISD::VP_OR: 3446 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3447 case ISD::VP_XOR: 3448 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3449 case ISD::VP_ASHR: 3450 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3451 case ISD::VP_LSHR: 3452 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3453 case ISD::VP_SHL: 3454 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3455 case ISD::VP_FADD: 3456 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3457 case ISD::VP_FSUB: 3458 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3459 case ISD::VP_FMUL: 3460 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3461 case ISD::VP_FDIV: 3462 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3463 case ISD::VP_FNEG: 3464 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3465 case ISD::VP_FMA: 3466 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3467 case ISD::VP_SIGN_EXTEND: 3468 case ISD::VP_ZERO_EXTEND: 3469 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3470 return lowerVPExtMaskOp(Op, DAG); 3471 return lowerVPOp(Op, DAG, 3472 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3473 ? RISCVISD::VSEXT_VL 3474 : RISCVISD::VZEXT_VL); 3475 case ISD::VP_TRUNCATE: 3476 return lowerVectorTruncLike(Op, DAG); 3477 case ISD::VP_FP_EXTEND: 3478 case ISD::VP_FP_ROUND: 3479 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3480 case ISD::VP_FPTOSI: 3481 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3482 case ISD::VP_FPTOUI: 3483 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3484 case ISD::VP_SITOFP: 3485 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3486 case ISD::VP_UITOFP: 3487 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3488 case ISD::VP_SETCC: 3489 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3490 return lowerVPSetCCMaskOp(Op, DAG); 3491 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3492 } 3493 } 3494 3495 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3496 SelectionDAG &DAG, unsigned Flags) { 3497 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3498 } 3499 3500 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3501 SelectionDAG &DAG, unsigned Flags) { 3502 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3503 Flags); 3504 } 3505 3506 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3507 SelectionDAG &DAG, unsigned Flags) { 3508 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3509 N->getOffset(), Flags); 3510 } 3511 3512 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3513 SelectionDAG &DAG, unsigned Flags) { 3514 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3515 } 3516 3517 template <class NodeTy> 3518 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3519 bool IsLocal) const { 3520 SDLoc DL(N); 3521 EVT Ty = getPointerTy(DAG.getDataLayout()); 3522 3523 if (isPositionIndependent()) { 3524 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3525 if (IsLocal) 3526 // Use PC-relative addressing to access the symbol. This generates the 3527 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3528 // %pcrel_lo(auipc)). 3529 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3530 3531 // Use PC-relative addressing to access the GOT for this symbol, then load 3532 // the address from the GOT. This generates the pattern (PseudoLA sym), 3533 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3534 SDValue Load = 3535 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3536 MachineFunction &MF = DAG.getMachineFunction(); 3537 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3538 MachinePointerInfo::getGOT(MF), 3539 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3540 MachineMemOperand::MOInvariant, 3541 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3542 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3543 return Load; 3544 } 3545 3546 switch (getTargetMachine().getCodeModel()) { 3547 default: 3548 report_fatal_error("Unsupported code model for lowering"); 3549 case CodeModel::Small: { 3550 // Generate a sequence for accessing addresses within the first 2 GiB of 3551 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3552 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3553 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3554 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3555 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3556 } 3557 case CodeModel::Medium: { 3558 // Generate a sequence for accessing addresses within any 2GiB range within 3559 // the address space. This generates the pattern (PseudoLLA sym), which 3560 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3561 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3562 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3563 } 3564 } 3565 } 3566 3567 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3568 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3569 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3570 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3571 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3572 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3573 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3574 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3575 3576 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3577 SelectionDAG &DAG) const { 3578 SDLoc DL(Op); 3579 EVT Ty = Op.getValueType(); 3580 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3581 int64_t Offset = N->getOffset(); 3582 MVT XLenVT = Subtarget.getXLenVT(); 3583 3584 const GlobalValue *GV = N->getGlobal(); 3585 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3586 SDValue Addr = getAddr(N, DAG, IsLocal); 3587 3588 // In order to maximise the opportunity for common subexpression elimination, 3589 // emit a separate ADD node for the global address offset instead of folding 3590 // it in the global address node. Later peephole optimisations may choose to 3591 // fold it back in when profitable. 3592 if (Offset != 0) 3593 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3594 DAG.getConstant(Offset, DL, XLenVT)); 3595 return Addr; 3596 } 3597 3598 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3599 SelectionDAG &DAG) const { 3600 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3601 3602 return getAddr(N, DAG); 3603 } 3604 3605 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3606 SelectionDAG &DAG) const { 3607 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3608 3609 return getAddr(N, DAG); 3610 } 3611 3612 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3613 SelectionDAG &DAG) const { 3614 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3615 3616 return getAddr(N, DAG); 3617 } 3618 3619 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3620 SelectionDAG &DAG, 3621 bool UseGOT) const { 3622 SDLoc DL(N); 3623 EVT Ty = getPointerTy(DAG.getDataLayout()); 3624 const GlobalValue *GV = N->getGlobal(); 3625 MVT XLenVT = Subtarget.getXLenVT(); 3626 3627 if (UseGOT) { 3628 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3629 // load the address from the GOT and add the thread pointer. This generates 3630 // the pattern (PseudoLA_TLS_IE sym), which expands to 3631 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3632 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3633 SDValue Load = 3634 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3635 MachineFunction &MF = DAG.getMachineFunction(); 3636 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3637 MachinePointerInfo::getGOT(MF), 3638 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3639 MachineMemOperand::MOInvariant, 3640 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3641 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3642 3643 // Add the thread pointer. 3644 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3645 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3646 } 3647 3648 // Generate a sequence for accessing the address relative to the thread 3649 // pointer, with the appropriate adjustment for the thread pointer offset. 3650 // This generates the pattern 3651 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3652 SDValue AddrHi = 3653 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3654 SDValue AddrAdd = 3655 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3656 SDValue AddrLo = 3657 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3658 3659 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3660 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3661 SDValue MNAdd = SDValue( 3662 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3663 0); 3664 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3665 } 3666 3667 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3668 SelectionDAG &DAG) const { 3669 SDLoc DL(N); 3670 EVT Ty = getPointerTy(DAG.getDataLayout()); 3671 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3672 const GlobalValue *GV = N->getGlobal(); 3673 3674 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3675 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3676 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3677 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3678 SDValue Load = 3679 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3680 3681 // Prepare argument list to generate call. 3682 ArgListTy Args; 3683 ArgListEntry Entry; 3684 Entry.Node = Load; 3685 Entry.Ty = CallTy; 3686 Args.push_back(Entry); 3687 3688 // Setup call to __tls_get_addr. 3689 TargetLowering::CallLoweringInfo CLI(DAG); 3690 CLI.setDebugLoc(DL) 3691 .setChain(DAG.getEntryNode()) 3692 .setLibCallee(CallingConv::C, CallTy, 3693 DAG.getExternalSymbol("__tls_get_addr", Ty), 3694 std::move(Args)); 3695 3696 return LowerCallTo(CLI).first; 3697 } 3698 3699 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3700 SelectionDAG &DAG) const { 3701 SDLoc DL(Op); 3702 EVT Ty = Op.getValueType(); 3703 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3704 int64_t Offset = N->getOffset(); 3705 MVT XLenVT = Subtarget.getXLenVT(); 3706 3707 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3708 3709 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3710 CallingConv::GHC) 3711 report_fatal_error("In GHC calling convention TLS is not supported"); 3712 3713 SDValue Addr; 3714 switch (Model) { 3715 case TLSModel::LocalExec: 3716 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3717 break; 3718 case TLSModel::InitialExec: 3719 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3720 break; 3721 case TLSModel::LocalDynamic: 3722 case TLSModel::GeneralDynamic: 3723 Addr = getDynamicTLSAddr(N, DAG); 3724 break; 3725 } 3726 3727 // In order to maximise the opportunity for common subexpression elimination, 3728 // emit a separate ADD node for the global address offset instead of folding 3729 // it in the global address node. Later peephole optimisations may choose to 3730 // fold it back in when profitable. 3731 if (Offset != 0) 3732 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3733 DAG.getConstant(Offset, DL, XLenVT)); 3734 return Addr; 3735 } 3736 3737 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3738 SDValue CondV = Op.getOperand(0); 3739 SDValue TrueV = Op.getOperand(1); 3740 SDValue FalseV = Op.getOperand(2); 3741 SDLoc DL(Op); 3742 MVT VT = Op.getSimpleValueType(); 3743 MVT XLenVT = Subtarget.getXLenVT(); 3744 3745 // Lower vector SELECTs to VSELECTs by splatting the condition. 3746 if (VT.isVector()) { 3747 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3748 SDValue CondSplat = VT.isScalableVector() 3749 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3750 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3751 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3752 } 3753 3754 // If the result type is XLenVT and CondV is the output of a SETCC node 3755 // which also operated on XLenVT inputs, then merge the SETCC node into the 3756 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3757 // compare+branch instructions. i.e.: 3758 // (select (setcc lhs, rhs, cc), truev, falsev) 3759 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3760 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3761 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3762 SDValue LHS = CondV.getOperand(0); 3763 SDValue RHS = CondV.getOperand(1); 3764 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3765 ISD::CondCode CCVal = CC->get(); 3766 3767 // Special case for a select of 2 constants that have a diffence of 1. 3768 // Normally this is done by DAGCombine, but if the select is introduced by 3769 // type legalization or op legalization, we miss it. Restricting to SETLT 3770 // case for now because that is what signed saturating add/sub need. 3771 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3772 // but we would probably want to swap the true/false values if the condition 3773 // is SETGE/SETLE to avoid an XORI. 3774 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3775 CCVal == ISD::SETLT) { 3776 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3777 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3778 if (TrueVal - 1 == FalseVal) 3779 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3780 if (TrueVal + 1 == FalseVal) 3781 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3782 } 3783 3784 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3785 3786 SDValue TargetCC = DAG.getCondCode(CCVal); 3787 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3788 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3789 } 3790 3791 // Otherwise: 3792 // (select condv, truev, falsev) 3793 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3794 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3795 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3796 3797 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3798 3799 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3800 } 3801 3802 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3803 SDValue CondV = Op.getOperand(1); 3804 SDLoc DL(Op); 3805 MVT XLenVT = Subtarget.getXLenVT(); 3806 3807 if (CondV.getOpcode() == ISD::SETCC && 3808 CondV.getOperand(0).getValueType() == XLenVT) { 3809 SDValue LHS = CondV.getOperand(0); 3810 SDValue RHS = CondV.getOperand(1); 3811 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3812 3813 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3814 3815 SDValue TargetCC = DAG.getCondCode(CCVal); 3816 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3817 LHS, RHS, TargetCC, Op.getOperand(2)); 3818 } 3819 3820 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3821 CondV, DAG.getConstant(0, DL, XLenVT), 3822 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3823 } 3824 3825 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3826 MachineFunction &MF = DAG.getMachineFunction(); 3827 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3828 3829 SDLoc DL(Op); 3830 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3831 getPointerTy(MF.getDataLayout())); 3832 3833 // vastart just stores the address of the VarArgsFrameIndex slot into the 3834 // memory location argument. 3835 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3836 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3837 MachinePointerInfo(SV)); 3838 } 3839 3840 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3841 SelectionDAG &DAG) const { 3842 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3843 MachineFunction &MF = DAG.getMachineFunction(); 3844 MachineFrameInfo &MFI = MF.getFrameInfo(); 3845 MFI.setFrameAddressIsTaken(true); 3846 Register FrameReg = RI.getFrameRegister(MF); 3847 int XLenInBytes = Subtarget.getXLen() / 8; 3848 3849 EVT VT = Op.getValueType(); 3850 SDLoc DL(Op); 3851 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3852 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3853 while (Depth--) { 3854 int Offset = -(XLenInBytes * 2); 3855 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3856 DAG.getIntPtrConstant(Offset, DL)); 3857 FrameAddr = 3858 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3859 } 3860 return FrameAddr; 3861 } 3862 3863 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3864 SelectionDAG &DAG) const { 3865 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3866 MachineFunction &MF = DAG.getMachineFunction(); 3867 MachineFrameInfo &MFI = MF.getFrameInfo(); 3868 MFI.setReturnAddressIsTaken(true); 3869 MVT XLenVT = Subtarget.getXLenVT(); 3870 int XLenInBytes = Subtarget.getXLen() / 8; 3871 3872 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3873 return SDValue(); 3874 3875 EVT VT = Op.getValueType(); 3876 SDLoc DL(Op); 3877 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3878 if (Depth) { 3879 int Off = -XLenInBytes; 3880 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3881 SDValue Offset = DAG.getConstant(Off, DL, VT); 3882 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3883 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3884 MachinePointerInfo()); 3885 } 3886 3887 // Return the value of the return address register, marking it an implicit 3888 // live-in. 3889 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3890 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3891 } 3892 3893 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3894 SelectionDAG &DAG) const { 3895 SDLoc DL(Op); 3896 SDValue Lo = Op.getOperand(0); 3897 SDValue Hi = Op.getOperand(1); 3898 SDValue Shamt = Op.getOperand(2); 3899 EVT VT = Lo.getValueType(); 3900 3901 // if Shamt-XLEN < 0: // Shamt < XLEN 3902 // Lo = Lo << Shamt 3903 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3904 // else: 3905 // Lo = 0 3906 // Hi = Lo << (Shamt-XLEN) 3907 3908 SDValue Zero = DAG.getConstant(0, DL, VT); 3909 SDValue One = DAG.getConstant(1, DL, VT); 3910 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3911 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3912 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3913 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3914 3915 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3916 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3917 SDValue ShiftRightLo = 3918 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3919 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3920 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3921 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3922 3923 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3924 3925 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3926 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3927 3928 SDValue Parts[2] = {Lo, Hi}; 3929 return DAG.getMergeValues(Parts, DL); 3930 } 3931 3932 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3933 bool IsSRA) const { 3934 SDLoc DL(Op); 3935 SDValue Lo = Op.getOperand(0); 3936 SDValue Hi = Op.getOperand(1); 3937 SDValue Shamt = Op.getOperand(2); 3938 EVT VT = Lo.getValueType(); 3939 3940 // SRA expansion: 3941 // if Shamt-XLEN < 0: // Shamt < XLEN 3942 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3943 // Hi = Hi >>s Shamt 3944 // else: 3945 // Lo = Hi >>s (Shamt-XLEN); 3946 // Hi = Hi >>s (XLEN-1) 3947 // 3948 // SRL expansion: 3949 // if Shamt-XLEN < 0: // Shamt < XLEN 3950 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3951 // Hi = Hi >>u Shamt 3952 // else: 3953 // Lo = Hi >>u (Shamt-XLEN); 3954 // Hi = 0; 3955 3956 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3957 3958 SDValue Zero = DAG.getConstant(0, DL, VT); 3959 SDValue One = DAG.getConstant(1, DL, VT); 3960 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3961 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3962 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3963 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3964 3965 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3966 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3967 SDValue ShiftLeftHi = 3968 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3969 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3970 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3971 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3972 SDValue HiFalse = 3973 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3974 3975 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3976 3977 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3978 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3979 3980 SDValue Parts[2] = {Lo, Hi}; 3981 return DAG.getMergeValues(Parts, DL); 3982 } 3983 3984 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3985 // legal equivalently-sized i8 type, so we can use that as a go-between. 3986 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3987 SelectionDAG &DAG) const { 3988 SDLoc DL(Op); 3989 MVT VT = Op.getSimpleValueType(); 3990 SDValue SplatVal = Op.getOperand(0); 3991 // All-zeros or all-ones splats are handled specially. 3992 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3993 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3994 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3995 } 3996 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3997 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3998 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3999 } 4000 MVT XLenVT = Subtarget.getXLenVT(); 4001 assert(SplatVal.getValueType() == XLenVT && 4002 "Unexpected type for i1 splat value"); 4003 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4004 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4005 DAG.getConstant(1, DL, XLenVT)); 4006 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4007 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4008 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4009 } 4010 4011 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4012 // illegal (currently only vXi64 RV32). 4013 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4014 // them to VMV_V_X_VL. 4015 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4016 SelectionDAG &DAG) const { 4017 SDLoc DL(Op); 4018 MVT VecVT = Op.getSimpleValueType(); 4019 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4020 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4021 4022 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4023 SDValue Lo = Op.getOperand(0); 4024 SDValue Hi = Op.getOperand(1); 4025 4026 if (VecVT.isFixedLengthVector()) { 4027 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4028 SDLoc DL(Op); 4029 SDValue Mask, VL; 4030 std::tie(Mask, VL) = 4031 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4032 4033 SDValue Res = 4034 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4035 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4036 } 4037 4038 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4039 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4040 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4041 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4042 // node in order to try and match RVV vector/scalar instructions. 4043 if ((LoC >> 31) == HiC) 4044 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4045 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4046 } 4047 4048 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4049 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4050 isa<ConstantSDNode>(Hi.getOperand(1)) && 4051 Hi.getConstantOperandVal(1) == 31) 4052 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4053 DAG.getRegister(RISCV::X0, MVT::i32)); 4054 4055 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4056 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4057 DAG.getUNDEF(VecVT), Lo, Hi, 4058 DAG.getRegister(RISCV::X0, MVT::i32)); 4059 } 4060 4061 // Custom-lower extensions from mask vectors by using a vselect either with 1 4062 // for zero/any-extension or -1 for sign-extension: 4063 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4064 // Note that any-extension is lowered identically to zero-extension. 4065 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4066 int64_t ExtTrueVal) const { 4067 SDLoc DL(Op); 4068 MVT VecVT = Op.getSimpleValueType(); 4069 SDValue Src = Op.getOperand(0); 4070 // Only custom-lower extensions from mask types 4071 assert(Src.getValueType().isVector() && 4072 Src.getValueType().getVectorElementType() == MVT::i1); 4073 4074 if (VecVT.isScalableVector()) { 4075 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4076 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4077 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4078 } 4079 4080 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4081 MVT I1ContainerVT = 4082 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4083 4084 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4085 4086 SDValue Mask, VL; 4087 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4088 4089 MVT XLenVT = Subtarget.getXLenVT(); 4090 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4091 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4092 4093 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4094 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4095 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4096 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4097 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4098 SplatTrueVal, SplatZero, VL); 4099 4100 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4101 } 4102 4103 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4104 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4105 MVT ExtVT = Op.getSimpleValueType(); 4106 // Only custom-lower extensions from fixed-length vector types. 4107 if (!ExtVT.isFixedLengthVector()) 4108 return Op; 4109 MVT VT = Op.getOperand(0).getSimpleValueType(); 4110 // Grab the canonical container type for the extended type. Infer the smaller 4111 // type from that to ensure the same number of vector elements, as we know 4112 // the LMUL will be sufficient to hold the smaller type. 4113 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4114 // Get the extended container type manually to ensure the same number of 4115 // vector elements between source and dest. 4116 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4117 ContainerExtVT.getVectorElementCount()); 4118 4119 SDValue Op1 = 4120 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4121 4122 SDLoc DL(Op); 4123 SDValue Mask, VL; 4124 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4125 4126 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4127 4128 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4129 } 4130 4131 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4132 // setcc operation: 4133 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4134 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4135 SelectionDAG &DAG) const { 4136 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4137 SDLoc DL(Op); 4138 EVT MaskVT = Op.getValueType(); 4139 // Only expect to custom-lower truncations to mask types 4140 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4141 "Unexpected type for vector mask lowering"); 4142 SDValue Src = Op.getOperand(0); 4143 MVT VecVT = Src.getSimpleValueType(); 4144 SDValue Mask, VL; 4145 if (IsVPTrunc) { 4146 Mask = Op.getOperand(1); 4147 VL = Op.getOperand(2); 4148 } 4149 // If this is a fixed vector, we need to convert it to a scalable vector. 4150 MVT ContainerVT = VecVT; 4151 4152 if (VecVT.isFixedLengthVector()) { 4153 ContainerVT = getContainerForFixedLengthVector(VecVT); 4154 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4155 if (IsVPTrunc) { 4156 MVT MaskContainerVT = 4157 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4158 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4159 } 4160 } 4161 4162 if (!IsVPTrunc) { 4163 std::tie(Mask, VL) = 4164 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4165 } 4166 4167 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4168 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4169 4170 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4171 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4172 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4173 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4174 4175 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4176 SDValue Trunc = 4177 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4178 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4179 DAG.getCondCode(ISD::SETNE), Mask, VL); 4180 if (MaskVT.isFixedLengthVector()) 4181 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4182 return Trunc; 4183 } 4184 4185 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4186 SelectionDAG &DAG) const { 4187 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4188 SDLoc DL(Op); 4189 4190 MVT VT = Op.getSimpleValueType(); 4191 // Only custom-lower vector truncates 4192 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4193 4194 // Truncates to mask types are handled differently 4195 if (VT.getVectorElementType() == MVT::i1) 4196 return lowerVectorMaskTruncLike(Op, DAG); 4197 4198 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4199 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4200 // truncate by one power of two at a time. 4201 MVT DstEltVT = VT.getVectorElementType(); 4202 4203 SDValue Src = Op.getOperand(0); 4204 MVT SrcVT = Src.getSimpleValueType(); 4205 MVT SrcEltVT = SrcVT.getVectorElementType(); 4206 4207 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4208 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4209 "Unexpected vector truncate lowering"); 4210 4211 MVT ContainerVT = SrcVT; 4212 SDValue Mask, VL; 4213 if (IsVPTrunc) { 4214 Mask = Op.getOperand(1); 4215 VL = Op.getOperand(2); 4216 } 4217 if (SrcVT.isFixedLengthVector()) { 4218 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4219 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4220 if (IsVPTrunc) { 4221 MVT MaskVT = getMaskTypeFor(ContainerVT); 4222 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4223 } 4224 } 4225 4226 SDValue Result = Src; 4227 if (!IsVPTrunc) { 4228 std::tie(Mask, VL) = 4229 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4230 } 4231 4232 LLVMContext &Context = *DAG.getContext(); 4233 const ElementCount Count = ContainerVT.getVectorElementCount(); 4234 do { 4235 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4236 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4237 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4238 Mask, VL); 4239 } while (SrcEltVT != DstEltVT); 4240 4241 if (SrcVT.isFixedLengthVector()) 4242 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4243 4244 return Result; 4245 } 4246 4247 SDValue 4248 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4249 SelectionDAG &DAG) const { 4250 bool IsVP = 4251 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4252 bool IsExtend = 4253 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4254 // RVV can only do truncate fp to types half the size as the source. We 4255 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4256 // conversion instruction. 4257 SDLoc DL(Op); 4258 MVT VT = Op.getSimpleValueType(); 4259 4260 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4261 4262 SDValue Src = Op.getOperand(0); 4263 MVT SrcVT = Src.getSimpleValueType(); 4264 4265 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4266 SrcVT.getVectorElementType() != MVT::f16); 4267 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4268 SrcVT.getVectorElementType() != MVT::f64); 4269 4270 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4271 4272 // For FP_ROUND/FP_EXTEND of scalable vectors, leave it to the pattern. 4273 if (!VT.isFixedLengthVector() && !IsVP && IsDirectConv) 4274 return Op; 4275 4276 // Prepare any fixed-length vector operands. 4277 MVT ContainerVT = VT; 4278 SDValue Mask, VL; 4279 if (IsVP) { 4280 Mask = Op.getOperand(1); 4281 VL = Op.getOperand(2); 4282 } 4283 if (VT.isFixedLengthVector()) { 4284 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4285 ContainerVT = 4286 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4287 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4288 if (IsVP) { 4289 MVT MaskVT = getMaskTypeFor(ContainerVT); 4290 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4291 } 4292 } 4293 4294 if (!IsVP) 4295 std::tie(Mask, VL) = 4296 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4297 4298 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4299 4300 if (IsDirectConv) { 4301 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4302 if (VT.isFixedLengthVector()) 4303 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4304 return Src; 4305 } 4306 4307 unsigned InterConvOpc = 4308 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4309 4310 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4311 SDValue IntermediateConv = 4312 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4313 SDValue Result = 4314 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4315 if (VT.isFixedLengthVector()) 4316 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4317 return Result; 4318 } 4319 4320 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4321 // first position of a vector, and that vector is slid up to the insert index. 4322 // By limiting the active vector length to index+1 and merging with the 4323 // original vector (with an undisturbed tail policy for elements >= VL), we 4324 // achieve the desired result of leaving all elements untouched except the one 4325 // at VL-1, which is replaced with the desired value. 4326 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4327 SelectionDAG &DAG) const { 4328 SDLoc DL(Op); 4329 MVT VecVT = Op.getSimpleValueType(); 4330 SDValue Vec = Op.getOperand(0); 4331 SDValue Val = Op.getOperand(1); 4332 SDValue Idx = Op.getOperand(2); 4333 4334 if (VecVT.getVectorElementType() == MVT::i1) { 4335 // FIXME: For now we just promote to an i8 vector and insert into that, 4336 // but this is probably not optimal. 4337 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4338 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4339 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4340 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4341 } 4342 4343 MVT ContainerVT = VecVT; 4344 // If the operand is a fixed-length vector, convert to a scalable one. 4345 if (VecVT.isFixedLengthVector()) { 4346 ContainerVT = getContainerForFixedLengthVector(VecVT); 4347 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4348 } 4349 4350 MVT XLenVT = Subtarget.getXLenVT(); 4351 4352 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4353 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4354 // Even i64-element vectors on RV32 can be lowered without scalar 4355 // legalization if the most-significant 32 bits of the value are not affected 4356 // by the sign-extension of the lower 32 bits. 4357 // TODO: We could also catch sign extensions of a 32-bit value. 4358 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4359 const auto *CVal = cast<ConstantSDNode>(Val); 4360 if (isInt<32>(CVal->getSExtValue())) { 4361 IsLegalInsert = true; 4362 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4363 } 4364 } 4365 4366 SDValue Mask, VL; 4367 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4368 4369 SDValue ValInVec; 4370 4371 if (IsLegalInsert) { 4372 unsigned Opc = 4373 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4374 if (isNullConstant(Idx)) { 4375 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4376 if (!VecVT.isFixedLengthVector()) 4377 return Vec; 4378 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4379 } 4380 ValInVec = 4381 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4382 } else { 4383 // On RV32, i64-element vectors must be specially handled to place the 4384 // value at element 0, by using two vslide1up instructions in sequence on 4385 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4386 // this. 4387 SDValue One = DAG.getConstant(1, DL, XLenVT); 4388 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4389 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4390 MVT I32ContainerVT = 4391 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4392 SDValue I32Mask = 4393 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4394 // Limit the active VL to two. 4395 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4396 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4397 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4398 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4399 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4400 // First slide in the hi value, then the lo in underneath it. 4401 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4402 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4403 I32Mask, InsertI64VL); 4404 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4405 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4406 I32Mask, InsertI64VL); 4407 // Bitcast back to the right container type. 4408 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4409 } 4410 4411 // Now that the value is in a vector, slide it into position. 4412 SDValue InsertVL = 4413 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4414 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4415 ValInVec, Idx, Mask, InsertVL); 4416 if (!VecVT.isFixedLengthVector()) 4417 return Slideup; 4418 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4419 } 4420 4421 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4422 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4423 // types this is done using VMV_X_S to allow us to glean information about the 4424 // sign bits of the result. 4425 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4426 SelectionDAG &DAG) const { 4427 SDLoc DL(Op); 4428 SDValue Idx = Op.getOperand(1); 4429 SDValue Vec = Op.getOperand(0); 4430 EVT EltVT = Op.getValueType(); 4431 MVT VecVT = Vec.getSimpleValueType(); 4432 MVT XLenVT = Subtarget.getXLenVT(); 4433 4434 if (VecVT.getVectorElementType() == MVT::i1) { 4435 if (VecVT.isFixedLengthVector()) { 4436 unsigned NumElts = VecVT.getVectorNumElements(); 4437 if (NumElts >= 8) { 4438 MVT WideEltVT; 4439 unsigned WidenVecLen; 4440 SDValue ExtractElementIdx; 4441 SDValue ExtractBitIdx; 4442 unsigned MaxEEW = Subtarget.getELEN(); 4443 MVT LargestEltVT = MVT::getIntegerVT( 4444 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4445 if (NumElts <= LargestEltVT.getSizeInBits()) { 4446 assert(isPowerOf2_32(NumElts) && 4447 "the number of elements should be power of 2"); 4448 WideEltVT = MVT::getIntegerVT(NumElts); 4449 WidenVecLen = 1; 4450 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4451 ExtractBitIdx = Idx; 4452 } else { 4453 WideEltVT = LargestEltVT; 4454 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4455 // extract element index = index / element width 4456 ExtractElementIdx = DAG.getNode( 4457 ISD::SRL, DL, XLenVT, Idx, 4458 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4459 // mask bit index = index % element width 4460 ExtractBitIdx = DAG.getNode( 4461 ISD::AND, DL, XLenVT, Idx, 4462 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4463 } 4464 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4465 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4466 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4467 Vec, ExtractElementIdx); 4468 // Extract the bit from GPR. 4469 SDValue ShiftRight = 4470 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4471 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4472 DAG.getConstant(1, DL, XLenVT)); 4473 } 4474 } 4475 // Otherwise, promote to an i8 vector and extract from that. 4476 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4477 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4478 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4479 } 4480 4481 // If this is a fixed vector, we need to convert it to a scalable vector. 4482 MVT ContainerVT = VecVT; 4483 if (VecVT.isFixedLengthVector()) { 4484 ContainerVT = getContainerForFixedLengthVector(VecVT); 4485 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4486 } 4487 4488 // If the index is 0, the vector is already in the right position. 4489 if (!isNullConstant(Idx)) { 4490 // Use a VL of 1 to avoid processing more elements than we need. 4491 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4492 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4493 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4494 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4495 } 4496 4497 if (!EltVT.isInteger()) { 4498 // Floating-point extracts are handled in TableGen. 4499 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4500 DAG.getConstant(0, DL, XLenVT)); 4501 } 4502 4503 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4504 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4505 } 4506 4507 // Some RVV intrinsics may claim that they want an integer operand to be 4508 // promoted or expanded. 4509 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4510 const RISCVSubtarget &Subtarget) { 4511 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4512 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4513 "Unexpected opcode"); 4514 4515 if (!Subtarget.hasVInstructions()) 4516 return SDValue(); 4517 4518 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4519 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4520 SDLoc DL(Op); 4521 4522 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4523 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4524 if (!II || !II->hasScalarOperand()) 4525 return SDValue(); 4526 4527 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4528 assert(SplatOp < Op.getNumOperands()); 4529 4530 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4531 SDValue &ScalarOp = Operands[SplatOp]; 4532 MVT OpVT = ScalarOp.getSimpleValueType(); 4533 MVT XLenVT = Subtarget.getXLenVT(); 4534 4535 // If this isn't a scalar, or its type is XLenVT we're done. 4536 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4537 return SDValue(); 4538 4539 // Simplest case is that the operand needs to be promoted to XLenVT. 4540 if (OpVT.bitsLT(XLenVT)) { 4541 // If the operand is a constant, sign extend to increase our chances 4542 // of being able to use a .vi instruction. ANY_EXTEND would become a 4543 // a zero extend and the simm5 check in isel would fail. 4544 // FIXME: Should we ignore the upper bits in isel instead? 4545 unsigned ExtOpc = 4546 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4547 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4548 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4549 } 4550 4551 // Use the previous operand to get the vXi64 VT. The result might be a mask 4552 // VT for compares. Using the previous operand assumes that the previous 4553 // operand will never have a smaller element size than a scalar operand and 4554 // that a widening operation never uses SEW=64. 4555 // NOTE: If this fails the below assert, we can probably just find the 4556 // element count from any operand or result and use it to construct the VT. 4557 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4558 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4559 4560 // The more complex case is when the scalar is larger than XLenVT. 4561 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4562 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4563 4564 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4565 // instruction to sign-extend since SEW>XLEN. 4566 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4567 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4568 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4569 } 4570 4571 switch (IntNo) { 4572 case Intrinsic::riscv_vslide1up: 4573 case Intrinsic::riscv_vslide1down: 4574 case Intrinsic::riscv_vslide1up_mask: 4575 case Intrinsic::riscv_vslide1down_mask: { 4576 // We need to special case these when the scalar is larger than XLen. 4577 unsigned NumOps = Op.getNumOperands(); 4578 bool IsMasked = NumOps == 7; 4579 4580 // Convert the vector source to the equivalent nxvXi32 vector. 4581 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4582 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4583 4584 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4585 DAG.getConstant(0, DL, XLenVT)); 4586 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4587 DAG.getConstant(1, DL, XLenVT)); 4588 4589 // Double the VL since we halved SEW. 4590 SDValue AVL = getVLOperand(Op); 4591 SDValue I32VL; 4592 4593 // Optimize for constant AVL 4594 if (isa<ConstantSDNode>(AVL)) { 4595 unsigned EltSize = VT.getScalarSizeInBits(); 4596 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4597 4598 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4599 unsigned MaxVLMAX = 4600 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4601 4602 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4603 unsigned MinVLMAX = 4604 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4605 4606 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4607 if (AVLInt <= MinVLMAX) { 4608 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4609 } else if (AVLInt >= 2 * MaxVLMAX) { 4610 // Just set vl to VLMAX in this situation 4611 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4612 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4613 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4614 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4615 SDValue SETVLMAX = DAG.getTargetConstant( 4616 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4617 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4618 LMUL); 4619 } else { 4620 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4621 // is related to the hardware implementation. 4622 // So let the following code handle 4623 } 4624 } 4625 if (!I32VL) { 4626 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4627 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4628 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4629 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4630 SDValue SETVL = 4631 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4632 // Using vsetvli instruction to get actually used length which related to 4633 // the hardware implementation 4634 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4635 SEW, LMUL); 4636 I32VL = 4637 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4638 } 4639 4640 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4641 4642 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4643 // instructions. 4644 SDValue Passthru; 4645 if (IsMasked) 4646 Passthru = DAG.getUNDEF(I32VT); 4647 else 4648 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4649 4650 if (IntNo == Intrinsic::riscv_vslide1up || 4651 IntNo == Intrinsic::riscv_vslide1up_mask) { 4652 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4653 ScalarHi, I32Mask, I32VL); 4654 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4655 ScalarLo, I32Mask, I32VL); 4656 } else { 4657 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4658 ScalarLo, I32Mask, I32VL); 4659 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4660 ScalarHi, I32Mask, I32VL); 4661 } 4662 4663 // Convert back to nxvXi64. 4664 Vec = DAG.getBitcast(VT, Vec); 4665 4666 if (!IsMasked) 4667 return Vec; 4668 // Apply mask after the operation. 4669 SDValue Mask = Operands[NumOps - 3]; 4670 SDValue MaskedOff = Operands[1]; 4671 // Assume Policy operand is the last operand. 4672 uint64_t Policy = 4673 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4674 // We don't need to select maskedoff if it's undef. 4675 if (MaskedOff.isUndef()) 4676 return Vec; 4677 // TAMU 4678 if (Policy == RISCVII::TAIL_AGNOSTIC) 4679 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4680 AVL); 4681 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4682 // It's fine because vmerge does not care mask policy. 4683 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4684 AVL); 4685 } 4686 } 4687 4688 // We need to convert the scalar to a splat vector. 4689 SDValue VL = getVLOperand(Op); 4690 assert(VL.getValueType() == XLenVT); 4691 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4692 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4693 } 4694 4695 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4696 SelectionDAG &DAG) const { 4697 unsigned IntNo = Op.getConstantOperandVal(0); 4698 SDLoc DL(Op); 4699 MVT XLenVT = Subtarget.getXLenVT(); 4700 4701 switch (IntNo) { 4702 default: 4703 break; // Don't custom lower most intrinsics. 4704 case Intrinsic::thread_pointer: { 4705 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4706 return DAG.getRegister(RISCV::X4, PtrVT); 4707 } 4708 case Intrinsic::riscv_orc_b: 4709 case Intrinsic::riscv_brev8: { 4710 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4711 unsigned Opc = 4712 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4713 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4714 DAG.getConstant(7, DL, XLenVT)); 4715 } 4716 case Intrinsic::riscv_grev: 4717 case Intrinsic::riscv_gorc: { 4718 unsigned Opc = 4719 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4720 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4721 } 4722 case Intrinsic::riscv_zip: 4723 case Intrinsic::riscv_unzip: { 4724 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4725 // For i32 the immediate is 15. For i64 the immediate is 31. 4726 unsigned Opc = 4727 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4728 unsigned BitWidth = Op.getValueSizeInBits(); 4729 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4730 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4731 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4732 } 4733 case Intrinsic::riscv_shfl: 4734 case Intrinsic::riscv_unshfl: { 4735 unsigned Opc = 4736 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4737 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4738 } 4739 case Intrinsic::riscv_bcompress: 4740 case Intrinsic::riscv_bdecompress: { 4741 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4742 : RISCVISD::BDECOMPRESS; 4743 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4744 } 4745 case Intrinsic::riscv_bfp: 4746 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4747 Op.getOperand(2)); 4748 case Intrinsic::riscv_fsl: 4749 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4750 Op.getOperand(2), Op.getOperand(3)); 4751 case Intrinsic::riscv_fsr: 4752 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4753 Op.getOperand(2), Op.getOperand(3)); 4754 case Intrinsic::riscv_vmv_x_s: 4755 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4756 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4757 Op.getOperand(1)); 4758 case Intrinsic::riscv_vmv_v_x: 4759 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4760 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4761 Subtarget); 4762 case Intrinsic::riscv_vfmv_v_f: 4763 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4764 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4765 case Intrinsic::riscv_vmv_s_x: { 4766 SDValue Scalar = Op.getOperand(2); 4767 4768 if (Scalar.getValueType().bitsLE(XLenVT)) { 4769 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4770 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4771 Op.getOperand(1), Scalar, Op.getOperand(3)); 4772 } 4773 4774 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4775 4776 // This is an i64 value that lives in two scalar registers. We have to 4777 // insert this in a convoluted way. First we build vXi64 splat containing 4778 // the two values that we assemble using some bit math. Next we'll use 4779 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4780 // to merge element 0 from our splat into the source vector. 4781 // FIXME: This is probably not the best way to do this, but it is 4782 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4783 // point. 4784 // sw lo, (a0) 4785 // sw hi, 4(a0) 4786 // vlse vX, (a0) 4787 // 4788 // vid.v vVid 4789 // vmseq.vx mMask, vVid, 0 4790 // vmerge.vvm vDest, vSrc, vVal, mMask 4791 MVT VT = Op.getSimpleValueType(); 4792 SDValue Vec = Op.getOperand(1); 4793 SDValue VL = getVLOperand(Op); 4794 4795 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4796 if (Op.getOperand(1).isUndef()) 4797 return SplattedVal; 4798 SDValue SplattedIdx = 4799 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4800 DAG.getConstant(0, DL, MVT::i32), VL); 4801 4802 MVT MaskVT = getMaskTypeFor(VT); 4803 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4804 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4805 SDValue SelectCond = 4806 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4807 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4808 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4809 Vec, VL); 4810 } 4811 } 4812 4813 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4814 } 4815 4816 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4817 SelectionDAG &DAG) const { 4818 unsigned IntNo = Op.getConstantOperandVal(1); 4819 switch (IntNo) { 4820 default: 4821 break; 4822 case Intrinsic::riscv_masked_strided_load: { 4823 SDLoc DL(Op); 4824 MVT XLenVT = Subtarget.getXLenVT(); 4825 4826 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4827 // the selection of the masked intrinsics doesn't do this for us. 4828 SDValue Mask = Op.getOperand(5); 4829 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4830 4831 MVT VT = Op->getSimpleValueType(0); 4832 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4833 4834 SDValue PassThru = Op.getOperand(2); 4835 if (!IsUnmasked) { 4836 MVT MaskVT = getMaskTypeFor(ContainerVT); 4837 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4838 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4839 } 4840 4841 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4842 4843 SDValue IntID = DAG.getTargetConstant( 4844 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4845 XLenVT); 4846 4847 auto *Load = cast<MemIntrinsicSDNode>(Op); 4848 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4849 if (IsUnmasked) 4850 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4851 else 4852 Ops.push_back(PassThru); 4853 Ops.push_back(Op.getOperand(3)); // Ptr 4854 Ops.push_back(Op.getOperand(4)); // Stride 4855 if (!IsUnmasked) 4856 Ops.push_back(Mask); 4857 Ops.push_back(VL); 4858 if (!IsUnmasked) { 4859 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4860 Ops.push_back(Policy); 4861 } 4862 4863 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4864 SDValue Result = 4865 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4866 Load->getMemoryVT(), Load->getMemOperand()); 4867 SDValue Chain = Result.getValue(1); 4868 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4869 return DAG.getMergeValues({Result, Chain}, DL); 4870 } 4871 case Intrinsic::riscv_seg2_load: 4872 case Intrinsic::riscv_seg3_load: 4873 case Intrinsic::riscv_seg4_load: 4874 case Intrinsic::riscv_seg5_load: 4875 case Intrinsic::riscv_seg6_load: 4876 case Intrinsic::riscv_seg7_load: 4877 case Intrinsic::riscv_seg8_load: { 4878 SDLoc DL(Op); 4879 static const Intrinsic::ID VlsegInts[7] = { 4880 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4881 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4882 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4883 Intrinsic::riscv_vlseg8}; 4884 unsigned NF = Op->getNumValues() - 1; 4885 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4886 MVT XLenVT = Subtarget.getXLenVT(); 4887 MVT VT = Op->getSimpleValueType(0); 4888 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4889 4890 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4891 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4892 auto *Load = cast<MemIntrinsicSDNode>(Op); 4893 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4894 ContainerVTs.push_back(MVT::Other); 4895 SDVTList VTs = DAG.getVTList(ContainerVTs); 4896 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4897 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4898 Ops.push_back(Op.getOperand(2)); 4899 Ops.push_back(VL); 4900 SDValue Result = 4901 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4902 Load->getMemoryVT(), Load->getMemOperand()); 4903 SmallVector<SDValue, 9> Results; 4904 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4905 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4906 DAG, Subtarget)); 4907 Results.push_back(Result.getValue(NF)); 4908 return DAG.getMergeValues(Results, DL); 4909 } 4910 } 4911 4912 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4913 } 4914 4915 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4916 SelectionDAG &DAG) const { 4917 unsigned IntNo = Op.getConstantOperandVal(1); 4918 switch (IntNo) { 4919 default: 4920 break; 4921 case Intrinsic::riscv_masked_strided_store: { 4922 SDLoc DL(Op); 4923 MVT XLenVT = Subtarget.getXLenVT(); 4924 4925 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4926 // the selection of the masked intrinsics doesn't do this for us. 4927 SDValue Mask = Op.getOperand(5); 4928 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4929 4930 SDValue Val = Op.getOperand(2); 4931 MVT VT = Val.getSimpleValueType(); 4932 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4933 4934 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4935 if (!IsUnmasked) { 4936 MVT MaskVT = getMaskTypeFor(ContainerVT); 4937 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4938 } 4939 4940 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4941 4942 SDValue IntID = DAG.getTargetConstant( 4943 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4944 XLenVT); 4945 4946 auto *Store = cast<MemIntrinsicSDNode>(Op); 4947 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4948 Ops.push_back(Val); 4949 Ops.push_back(Op.getOperand(3)); // Ptr 4950 Ops.push_back(Op.getOperand(4)); // Stride 4951 if (!IsUnmasked) 4952 Ops.push_back(Mask); 4953 Ops.push_back(VL); 4954 4955 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4956 Ops, Store->getMemoryVT(), 4957 Store->getMemOperand()); 4958 } 4959 } 4960 4961 return SDValue(); 4962 } 4963 4964 static MVT getLMUL1VT(MVT VT) { 4965 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4966 "Unexpected vector MVT"); 4967 return MVT::getScalableVectorVT( 4968 VT.getVectorElementType(), 4969 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4970 } 4971 4972 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4973 switch (ISDOpcode) { 4974 default: 4975 llvm_unreachable("Unhandled reduction"); 4976 case ISD::VECREDUCE_ADD: 4977 return RISCVISD::VECREDUCE_ADD_VL; 4978 case ISD::VECREDUCE_UMAX: 4979 return RISCVISD::VECREDUCE_UMAX_VL; 4980 case ISD::VECREDUCE_SMAX: 4981 return RISCVISD::VECREDUCE_SMAX_VL; 4982 case ISD::VECREDUCE_UMIN: 4983 return RISCVISD::VECREDUCE_UMIN_VL; 4984 case ISD::VECREDUCE_SMIN: 4985 return RISCVISD::VECREDUCE_SMIN_VL; 4986 case ISD::VECREDUCE_AND: 4987 return RISCVISD::VECREDUCE_AND_VL; 4988 case ISD::VECREDUCE_OR: 4989 return RISCVISD::VECREDUCE_OR_VL; 4990 case ISD::VECREDUCE_XOR: 4991 return RISCVISD::VECREDUCE_XOR_VL; 4992 } 4993 } 4994 4995 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4996 SelectionDAG &DAG, 4997 bool IsVP) const { 4998 SDLoc DL(Op); 4999 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5000 MVT VecVT = Vec.getSimpleValueType(); 5001 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5002 Op.getOpcode() == ISD::VECREDUCE_OR || 5003 Op.getOpcode() == ISD::VECREDUCE_XOR || 5004 Op.getOpcode() == ISD::VP_REDUCE_AND || 5005 Op.getOpcode() == ISD::VP_REDUCE_OR || 5006 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5007 "Unexpected reduction lowering"); 5008 5009 MVT XLenVT = Subtarget.getXLenVT(); 5010 assert(Op.getValueType() == XLenVT && 5011 "Expected reduction output to be legalized to XLenVT"); 5012 5013 MVT ContainerVT = VecVT; 5014 if (VecVT.isFixedLengthVector()) { 5015 ContainerVT = getContainerForFixedLengthVector(VecVT); 5016 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5017 } 5018 5019 SDValue Mask, VL; 5020 if (IsVP) { 5021 Mask = Op.getOperand(2); 5022 VL = Op.getOperand(3); 5023 } else { 5024 std::tie(Mask, VL) = 5025 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5026 } 5027 5028 unsigned BaseOpc; 5029 ISD::CondCode CC; 5030 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5031 5032 switch (Op.getOpcode()) { 5033 default: 5034 llvm_unreachable("Unhandled reduction"); 5035 case ISD::VECREDUCE_AND: 5036 case ISD::VP_REDUCE_AND: { 5037 // vcpop ~x == 0 5038 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5039 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5040 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5041 CC = ISD::SETEQ; 5042 BaseOpc = ISD::AND; 5043 break; 5044 } 5045 case ISD::VECREDUCE_OR: 5046 case ISD::VP_REDUCE_OR: 5047 // vcpop x != 0 5048 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5049 CC = ISD::SETNE; 5050 BaseOpc = ISD::OR; 5051 break; 5052 case ISD::VECREDUCE_XOR: 5053 case ISD::VP_REDUCE_XOR: { 5054 // ((vcpop x) & 1) != 0 5055 SDValue One = DAG.getConstant(1, DL, XLenVT); 5056 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5057 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5058 CC = ISD::SETNE; 5059 BaseOpc = ISD::XOR; 5060 break; 5061 } 5062 } 5063 5064 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5065 5066 if (!IsVP) 5067 return SetCC; 5068 5069 // Now include the start value in the operation. 5070 // Note that we must return the start value when no elements are operated 5071 // upon. The vcpop instructions we've emitted in each case above will return 5072 // 0 for an inactive vector, and so we've already received the neutral value: 5073 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5074 // can simply include the start value. 5075 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5076 } 5077 5078 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5079 SelectionDAG &DAG) const { 5080 SDLoc DL(Op); 5081 SDValue Vec = Op.getOperand(0); 5082 EVT VecEVT = Vec.getValueType(); 5083 5084 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5085 5086 // Due to ordering in legalize types we may have a vector type that needs to 5087 // be split. Do that manually so we can get down to a legal type. 5088 while (getTypeAction(*DAG.getContext(), VecEVT) == 5089 TargetLowering::TypeSplitVector) { 5090 SDValue Lo, Hi; 5091 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5092 VecEVT = Lo.getValueType(); 5093 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5094 } 5095 5096 // TODO: The type may need to be widened rather than split. Or widened before 5097 // it can be split. 5098 if (!isTypeLegal(VecEVT)) 5099 return SDValue(); 5100 5101 MVT VecVT = VecEVT.getSimpleVT(); 5102 MVT VecEltVT = VecVT.getVectorElementType(); 5103 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5104 5105 MVT ContainerVT = VecVT; 5106 if (VecVT.isFixedLengthVector()) { 5107 ContainerVT = getContainerForFixedLengthVector(VecVT); 5108 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5109 } 5110 5111 MVT M1VT = getLMUL1VT(ContainerVT); 5112 MVT XLenVT = Subtarget.getXLenVT(); 5113 5114 SDValue Mask, VL; 5115 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5116 5117 SDValue NeutralElem = 5118 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5119 SDValue IdentitySplat = 5120 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5121 M1VT, DL, DAG, Subtarget); 5122 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5123 IdentitySplat, Mask, VL); 5124 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5125 DAG.getConstant(0, DL, XLenVT)); 5126 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5127 } 5128 5129 // Given a reduction op, this function returns the matching reduction opcode, 5130 // the vector SDValue and the scalar SDValue required to lower this to a 5131 // RISCVISD node. 5132 static std::tuple<unsigned, SDValue, SDValue> 5133 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5134 SDLoc DL(Op); 5135 auto Flags = Op->getFlags(); 5136 unsigned Opcode = Op.getOpcode(); 5137 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5138 switch (Opcode) { 5139 default: 5140 llvm_unreachable("Unhandled reduction"); 5141 case ISD::VECREDUCE_FADD: { 5142 // Use positive zero if we can. It is cheaper to materialize. 5143 SDValue Zero = 5144 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5145 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5146 } 5147 case ISD::VECREDUCE_SEQ_FADD: 5148 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5149 Op.getOperand(0)); 5150 case ISD::VECREDUCE_FMIN: 5151 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5152 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5153 case ISD::VECREDUCE_FMAX: 5154 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5155 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5156 } 5157 } 5158 5159 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5160 SelectionDAG &DAG) const { 5161 SDLoc DL(Op); 5162 MVT VecEltVT = Op.getSimpleValueType(); 5163 5164 unsigned RVVOpcode; 5165 SDValue VectorVal, ScalarVal; 5166 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5167 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5168 MVT VecVT = VectorVal.getSimpleValueType(); 5169 5170 MVT ContainerVT = VecVT; 5171 if (VecVT.isFixedLengthVector()) { 5172 ContainerVT = getContainerForFixedLengthVector(VecVT); 5173 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5174 } 5175 5176 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5177 MVT XLenVT = Subtarget.getXLenVT(); 5178 5179 SDValue Mask, VL; 5180 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5181 5182 SDValue ScalarSplat = 5183 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5184 M1VT, DL, DAG, Subtarget); 5185 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5186 VectorVal, ScalarSplat, Mask, VL); 5187 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5188 DAG.getConstant(0, DL, XLenVT)); 5189 } 5190 5191 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5192 switch (ISDOpcode) { 5193 default: 5194 llvm_unreachable("Unhandled reduction"); 5195 case ISD::VP_REDUCE_ADD: 5196 return RISCVISD::VECREDUCE_ADD_VL; 5197 case ISD::VP_REDUCE_UMAX: 5198 return RISCVISD::VECREDUCE_UMAX_VL; 5199 case ISD::VP_REDUCE_SMAX: 5200 return RISCVISD::VECREDUCE_SMAX_VL; 5201 case ISD::VP_REDUCE_UMIN: 5202 return RISCVISD::VECREDUCE_UMIN_VL; 5203 case ISD::VP_REDUCE_SMIN: 5204 return RISCVISD::VECREDUCE_SMIN_VL; 5205 case ISD::VP_REDUCE_AND: 5206 return RISCVISD::VECREDUCE_AND_VL; 5207 case ISD::VP_REDUCE_OR: 5208 return RISCVISD::VECREDUCE_OR_VL; 5209 case ISD::VP_REDUCE_XOR: 5210 return RISCVISD::VECREDUCE_XOR_VL; 5211 case ISD::VP_REDUCE_FADD: 5212 return RISCVISD::VECREDUCE_FADD_VL; 5213 case ISD::VP_REDUCE_SEQ_FADD: 5214 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5215 case ISD::VP_REDUCE_FMAX: 5216 return RISCVISD::VECREDUCE_FMAX_VL; 5217 case ISD::VP_REDUCE_FMIN: 5218 return RISCVISD::VECREDUCE_FMIN_VL; 5219 } 5220 } 5221 5222 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5223 SelectionDAG &DAG) const { 5224 SDLoc DL(Op); 5225 SDValue Vec = Op.getOperand(1); 5226 EVT VecEVT = Vec.getValueType(); 5227 5228 // TODO: The type may need to be widened rather than split. Or widened before 5229 // it can be split. 5230 if (!isTypeLegal(VecEVT)) 5231 return SDValue(); 5232 5233 MVT VecVT = VecEVT.getSimpleVT(); 5234 MVT VecEltVT = VecVT.getVectorElementType(); 5235 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5236 5237 MVT ContainerVT = VecVT; 5238 if (VecVT.isFixedLengthVector()) { 5239 ContainerVT = getContainerForFixedLengthVector(VecVT); 5240 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5241 } 5242 5243 SDValue VL = Op.getOperand(3); 5244 SDValue Mask = Op.getOperand(2); 5245 5246 MVT M1VT = getLMUL1VT(ContainerVT); 5247 MVT XLenVT = Subtarget.getXLenVT(); 5248 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5249 5250 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5251 DAG.getConstant(1, DL, XLenVT), M1VT, 5252 DL, DAG, Subtarget); 5253 SDValue Reduction = 5254 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5255 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5256 DAG.getConstant(0, DL, XLenVT)); 5257 if (!VecVT.isInteger()) 5258 return Elt0; 5259 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5260 } 5261 5262 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5263 SelectionDAG &DAG) const { 5264 SDValue Vec = Op.getOperand(0); 5265 SDValue SubVec = Op.getOperand(1); 5266 MVT VecVT = Vec.getSimpleValueType(); 5267 MVT SubVecVT = SubVec.getSimpleValueType(); 5268 5269 SDLoc DL(Op); 5270 MVT XLenVT = Subtarget.getXLenVT(); 5271 unsigned OrigIdx = Op.getConstantOperandVal(2); 5272 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5273 5274 // We don't have the ability to slide mask vectors up indexed by their i1 5275 // elements; the smallest we can do is i8. Often we are able to bitcast to 5276 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5277 // into a scalable one, we might not necessarily have enough scalable 5278 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5279 if (SubVecVT.getVectorElementType() == MVT::i1 && 5280 (OrigIdx != 0 || !Vec.isUndef())) { 5281 if (VecVT.getVectorMinNumElements() >= 8 && 5282 SubVecVT.getVectorMinNumElements() >= 8) { 5283 assert(OrigIdx % 8 == 0 && "Invalid index"); 5284 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5285 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5286 "Unexpected mask vector lowering"); 5287 OrigIdx /= 8; 5288 SubVecVT = 5289 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5290 SubVecVT.isScalableVector()); 5291 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5292 VecVT.isScalableVector()); 5293 Vec = DAG.getBitcast(VecVT, Vec); 5294 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5295 } else { 5296 // We can't slide this mask vector up indexed by its i1 elements. 5297 // This poses a problem when we wish to insert a scalable vector which 5298 // can't be re-expressed as a larger type. Just choose the slow path and 5299 // extend to a larger type, then truncate back down. 5300 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5301 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5302 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5303 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5304 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5305 Op.getOperand(2)); 5306 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5307 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5308 } 5309 } 5310 5311 // If the subvector vector is a fixed-length type, we cannot use subregister 5312 // manipulation to simplify the codegen; we don't know which register of a 5313 // LMUL group contains the specific subvector as we only know the minimum 5314 // register size. Therefore we must slide the vector group up the full 5315 // amount. 5316 if (SubVecVT.isFixedLengthVector()) { 5317 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5318 return Op; 5319 MVT ContainerVT = VecVT; 5320 if (VecVT.isFixedLengthVector()) { 5321 ContainerVT = getContainerForFixedLengthVector(VecVT); 5322 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5323 } 5324 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5325 DAG.getUNDEF(ContainerVT), SubVec, 5326 DAG.getConstant(0, DL, XLenVT)); 5327 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5328 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5329 return DAG.getBitcast(Op.getValueType(), SubVec); 5330 } 5331 SDValue Mask = 5332 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5333 // Set the vector length to only the number of elements we care about. Note 5334 // that for slideup this includes the offset. 5335 SDValue VL = 5336 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5337 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5338 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5339 SubVec, SlideupAmt, Mask, VL); 5340 if (VecVT.isFixedLengthVector()) 5341 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5342 return DAG.getBitcast(Op.getValueType(), Slideup); 5343 } 5344 5345 unsigned SubRegIdx, RemIdx; 5346 std::tie(SubRegIdx, RemIdx) = 5347 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5348 VecVT, SubVecVT, OrigIdx, TRI); 5349 5350 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5351 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5352 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5353 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5354 5355 // 1. If the Idx has been completely eliminated and this subvector's size is 5356 // a vector register or a multiple thereof, or the surrounding elements are 5357 // undef, then this is a subvector insert which naturally aligns to a vector 5358 // register. These can easily be handled using subregister manipulation. 5359 // 2. If the subvector is smaller than a vector register, then the insertion 5360 // must preserve the undisturbed elements of the register. We do this by 5361 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5362 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5363 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5364 // LMUL=1 type back into the larger vector (resolving to another subregister 5365 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5366 // to avoid allocating a large register group to hold our subvector. 5367 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5368 return Op; 5369 5370 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5371 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5372 // (in our case undisturbed). This means we can set up a subvector insertion 5373 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5374 // size of the subvector. 5375 MVT InterSubVT = VecVT; 5376 SDValue AlignedExtract = Vec; 5377 unsigned AlignedIdx = OrigIdx - RemIdx; 5378 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5379 InterSubVT = getLMUL1VT(VecVT); 5380 // Extract a subvector equal to the nearest full vector register type. This 5381 // should resolve to a EXTRACT_SUBREG instruction. 5382 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5383 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5384 } 5385 5386 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5387 // For scalable vectors this must be further multiplied by vscale. 5388 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5389 5390 SDValue Mask, VL; 5391 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5392 5393 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5394 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5395 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5396 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5397 5398 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5399 DAG.getUNDEF(InterSubVT), SubVec, 5400 DAG.getConstant(0, DL, XLenVT)); 5401 5402 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5403 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5404 5405 // If required, insert this subvector back into the correct vector register. 5406 // This should resolve to an INSERT_SUBREG instruction. 5407 if (VecVT.bitsGT(InterSubVT)) 5408 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5409 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5410 5411 // We might have bitcast from a mask type: cast back to the original type if 5412 // required. 5413 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5414 } 5415 5416 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5417 SelectionDAG &DAG) const { 5418 SDValue Vec = Op.getOperand(0); 5419 MVT SubVecVT = Op.getSimpleValueType(); 5420 MVT VecVT = Vec.getSimpleValueType(); 5421 5422 SDLoc DL(Op); 5423 MVT XLenVT = Subtarget.getXLenVT(); 5424 unsigned OrigIdx = Op.getConstantOperandVal(1); 5425 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5426 5427 // We don't have the ability to slide mask vectors down indexed by their i1 5428 // elements; the smallest we can do is i8. Often we are able to bitcast to 5429 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5430 // from a scalable one, we might not necessarily have enough scalable 5431 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5432 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5433 if (VecVT.getVectorMinNumElements() >= 8 && 5434 SubVecVT.getVectorMinNumElements() >= 8) { 5435 assert(OrigIdx % 8 == 0 && "Invalid index"); 5436 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5437 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5438 "Unexpected mask vector lowering"); 5439 OrigIdx /= 8; 5440 SubVecVT = 5441 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5442 SubVecVT.isScalableVector()); 5443 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5444 VecVT.isScalableVector()); 5445 Vec = DAG.getBitcast(VecVT, Vec); 5446 } else { 5447 // We can't slide this mask vector down, indexed by its i1 elements. 5448 // This poses a problem when we wish to extract a scalable vector which 5449 // can't be re-expressed as a larger type. Just choose the slow path and 5450 // extend to a larger type, then truncate back down. 5451 // TODO: We could probably improve this when extracting certain fixed 5452 // from fixed, where we can extract as i8 and shift the correct element 5453 // right to reach the desired subvector? 5454 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5455 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5456 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5457 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5458 Op.getOperand(1)); 5459 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5460 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5461 } 5462 } 5463 5464 // If the subvector vector is a fixed-length type, we cannot use subregister 5465 // manipulation to simplify the codegen; we don't know which register of a 5466 // LMUL group contains the specific subvector as we only know the minimum 5467 // register size. Therefore we must slide the vector group down the full 5468 // amount. 5469 if (SubVecVT.isFixedLengthVector()) { 5470 // With an index of 0 this is a cast-like subvector, which can be performed 5471 // with subregister operations. 5472 if (OrigIdx == 0) 5473 return Op; 5474 MVT ContainerVT = VecVT; 5475 if (VecVT.isFixedLengthVector()) { 5476 ContainerVT = getContainerForFixedLengthVector(VecVT); 5477 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5478 } 5479 SDValue Mask = 5480 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5481 // Set the vector length to only the number of elements we care about. This 5482 // avoids sliding down elements we're going to discard straight away. 5483 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5484 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5485 SDValue Slidedown = 5486 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5487 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5488 // Now we can use a cast-like subvector extract to get the result. 5489 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5490 DAG.getConstant(0, DL, XLenVT)); 5491 return DAG.getBitcast(Op.getValueType(), Slidedown); 5492 } 5493 5494 unsigned SubRegIdx, RemIdx; 5495 std::tie(SubRegIdx, RemIdx) = 5496 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5497 VecVT, SubVecVT, OrigIdx, TRI); 5498 5499 // If the Idx has been completely eliminated then this is a subvector extract 5500 // which naturally aligns to a vector register. These can easily be handled 5501 // using subregister manipulation. 5502 if (RemIdx == 0) 5503 return Op; 5504 5505 // Else we must shift our vector register directly to extract the subvector. 5506 // Do this using VSLIDEDOWN. 5507 5508 // If the vector type is an LMUL-group type, extract a subvector equal to the 5509 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5510 // instruction. 5511 MVT InterSubVT = VecVT; 5512 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5513 InterSubVT = getLMUL1VT(VecVT); 5514 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5515 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5516 } 5517 5518 // Slide this vector register down by the desired number of elements in order 5519 // to place the desired subvector starting at element 0. 5520 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5521 // For scalable vectors this must be further multiplied by vscale. 5522 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5523 5524 SDValue Mask, VL; 5525 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5526 SDValue Slidedown = 5527 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5528 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5529 5530 // Now the vector is in the right position, extract our final subvector. This 5531 // should resolve to a COPY. 5532 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5533 DAG.getConstant(0, DL, XLenVT)); 5534 5535 // We might have bitcast from a mask type: cast back to the original type if 5536 // required. 5537 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5538 } 5539 5540 // Lower step_vector to the vid instruction. Any non-identity step value must 5541 // be accounted for my manual expansion. 5542 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5543 SelectionDAG &DAG) const { 5544 SDLoc DL(Op); 5545 MVT VT = Op.getSimpleValueType(); 5546 MVT XLenVT = Subtarget.getXLenVT(); 5547 SDValue Mask, VL; 5548 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5549 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5550 uint64_t StepValImm = Op.getConstantOperandVal(0); 5551 if (StepValImm != 1) { 5552 if (isPowerOf2_64(StepValImm)) { 5553 SDValue StepVal = 5554 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5555 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5556 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5557 } else { 5558 SDValue StepVal = lowerScalarSplat( 5559 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5560 VL, VT, DL, DAG, Subtarget); 5561 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5562 } 5563 } 5564 return StepVec; 5565 } 5566 5567 // Implement vector_reverse using vrgather.vv with indices determined by 5568 // subtracting the id of each element from (VLMAX-1). This will convert 5569 // the indices like so: 5570 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5571 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5572 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5573 SelectionDAG &DAG) const { 5574 SDLoc DL(Op); 5575 MVT VecVT = Op.getSimpleValueType(); 5576 unsigned EltSize = VecVT.getScalarSizeInBits(); 5577 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5578 5579 unsigned MaxVLMAX = 0; 5580 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5581 if (VectorBitsMax != 0) 5582 MaxVLMAX = 5583 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5584 5585 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5586 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5587 5588 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5589 // to use vrgatherei16.vv. 5590 // TODO: It's also possible to use vrgatherei16.vv for other types to 5591 // decrease register width for the index calculation. 5592 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5593 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5594 // Reverse each half, then reassemble them in reverse order. 5595 // NOTE: It's also possible that after splitting that VLMAX no longer 5596 // requires vrgatherei16.vv. 5597 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5598 SDValue Lo, Hi; 5599 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5600 EVT LoVT, HiVT; 5601 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5602 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5603 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5604 // Reassemble the low and high pieces reversed. 5605 // FIXME: This is a CONCAT_VECTORS. 5606 SDValue Res = 5607 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5608 DAG.getIntPtrConstant(0, DL)); 5609 return DAG.getNode( 5610 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5611 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5612 } 5613 5614 // Just promote the int type to i16 which will double the LMUL. 5615 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5616 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5617 } 5618 5619 MVT XLenVT = Subtarget.getXLenVT(); 5620 SDValue Mask, VL; 5621 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5622 5623 // Calculate VLMAX-1 for the desired SEW. 5624 unsigned MinElts = VecVT.getVectorMinNumElements(); 5625 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5626 DAG.getConstant(MinElts, DL, XLenVT)); 5627 SDValue VLMinus1 = 5628 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5629 5630 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5631 bool IsRV32E64 = 5632 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5633 SDValue SplatVL; 5634 if (!IsRV32E64) 5635 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5636 else 5637 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5638 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5639 5640 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5641 SDValue Indices = 5642 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5643 5644 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5645 } 5646 5647 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5648 SelectionDAG &DAG) const { 5649 SDLoc DL(Op); 5650 SDValue V1 = Op.getOperand(0); 5651 SDValue V2 = Op.getOperand(1); 5652 MVT XLenVT = Subtarget.getXLenVT(); 5653 MVT VecVT = Op.getSimpleValueType(); 5654 5655 unsigned MinElts = VecVT.getVectorMinNumElements(); 5656 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5657 DAG.getConstant(MinElts, DL, XLenVT)); 5658 5659 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5660 SDValue DownOffset, UpOffset; 5661 if (ImmValue >= 0) { 5662 // The operand is a TargetConstant, we need to rebuild it as a regular 5663 // constant. 5664 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5665 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5666 } else { 5667 // The operand is a TargetConstant, we need to rebuild it as a regular 5668 // constant rather than negating the original operand. 5669 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5670 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5671 } 5672 5673 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5674 5675 SDValue SlideDown = 5676 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5677 DownOffset, TrueMask, UpOffset); 5678 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5679 TrueMask, 5680 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5681 } 5682 5683 SDValue 5684 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5685 SelectionDAG &DAG) const { 5686 SDLoc DL(Op); 5687 auto *Load = cast<LoadSDNode>(Op); 5688 5689 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5690 Load->getMemoryVT(), 5691 *Load->getMemOperand()) && 5692 "Expecting a correctly-aligned load"); 5693 5694 MVT VT = Op.getSimpleValueType(); 5695 MVT XLenVT = Subtarget.getXLenVT(); 5696 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5697 5698 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5699 5700 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5701 SDValue IntID = DAG.getTargetConstant( 5702 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5703 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5704 if (!IsMaskOp) 5705 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5706 Ops.push_back(Load->getBasePtr()); 5707 Ops.push_back(VL); 5708 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5709 SDValue NewLoad = 5710 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5711 Load->getMemoryVT(), Load->getMemOperand()); 5712 5713 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5714 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5715 } 5716 5717 SDValue 5718 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5719 SelectionDAG &DAG) const { 5720 SDLoc DL(Op); 5721 auto *Store = cast<StoreSDNode>(Op); 5722 5723 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5724 Store->getMemoryVT(), 5725 *Store->getMemOperand()) && 5726 "Expecting a correctly-aligned store"); 5727 5728 SDValue StoreVal = Store->getValue(); 5729 MVT VT = StoreVal.getSimpleValueType(); 5730 MVT XLenVT = Subtarget.getXLenVT(); 5731 5732 // If the size less than a byte, we need to pad with zeros to make a byte. 5733 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5734 VT = MVT::v8i1; 5735 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5736 DAG.getConstant(0, DL, VT), StoreVal, 5737 DAG.getIntPtrConstant(0, DL)); 5738 } 5739 5740 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5741 5742 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5743 5744 SDValue NewValue = 5745 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5746 5747 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5748 SDValue IntID = DAG.getTargetConstant( 5749 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5750 return DAG.getMemIntrinsicNode( 5751 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5752 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5753 Store->getMemoryVT(), Store->getMemOperand()); 5754 } 5755 5756 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5757 SelectionDAG &DAG) const { 5758 SDLoc DL(Op); 5759 MVT VT = Op.getSimpleValueType(); 5760 5761 const auto *MemSD = cast<MemSDNode>(Op); 5762 EVT MemVT = MemSD->getMemoryVT(); 5763 MachineMemOperand *MMO = MemSD->getMemOperand(); 5764 SDValue Chain = MemSD->getChain(); 5765 SDValue BasePtr = MemSD->getBasePtr(); 5766 5767 SDValue Mask, PassThru, VL; 5768 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5769 Mask = VPLoad->getMask(); 5770 PassThru = DAG.getUNDEF(VT); 5771 VL = VPLoad->getVectorLength(); 5772 } else { 5773 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5774 Mask = MLoad->getMask(); 5775 PassThru = MLoad->getPassThru(); 5776 } 5777 5778 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5779 5780 MVT XLenVT = Subtarget.getXLenVT(); 5781 5782 MVT ContainerVT = VT; 5783 if (VT.isFixedLengthVector()) { 5784 ContainerVT = getContainerForFixedLengthVector(VT); 5785 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5786 if (!IsUnmasked) { 5787 MVT MaskVT = getMaskTypeFor(ContainerVT); 5788 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5789 } 5790 } 5791 5792 if (!VL) 5793 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5794 5795 unsigned IntID = 5796 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5797 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5798 if (IsUnmasked) 5799 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5800 else 5801 Ops.push_back(PassThru); 5802 Ops.push_back(BasePtr); 5803 if (!IsUnmasked) 5804 Ops.push_back(Mask); 5805 Ops.push_back(VL); 5806 if (!IsUnmasked) 5807 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5808 5809 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5810 5811 SDValue Result = 5812 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5813 Chain = Result.getValue(1); 5814 5815 if (VT.isFixedLengthVector()) 5816 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5817 5818 return DAG.getMergeValues({Result, Chain}, DL); 5819 } 5820 5821 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5822 SelectionDAG &DAG) const { 5823 SDLoc DL(Op); 5824 5825 const auto *MemSD = cast<MemSDNode>(Op); 5826 EVT MemVT = MemSD->getMemoryVT(); 5827 MachineMemOperand *MMO = MemSD->getMemOperand(); 5828 SDValue Chain = MemSD->getChain(); 5829 SDValue BasePtr = MemSD->getBasePtr(); 5830 SDValue Val, Mask, VL; 5831 5832 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5833 Val = VPStore->getValue(); 5834 Mask = VPStore->getMask(); 5835 VL = VPStore->getVectorLength(); 5836 } else { 5837 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5838 Val = MStore->getValue(); 5839 Mask = MStore->getMask(); 5840 } 5841 5842 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5843 5844 MVT VT = Val.getSimpleValueType(); 5845 MVT XLenVT = Subtarget.getXLenVT(); 5846 5847 MVT ContainerVT = VT; 5848 if (VT.isFixedLengthVector()) { 5849 ContainerVT = getContainerForFixedLengthVector(VT); 5850 5851 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5852 if (!IsUnmasked) { 5853 MVT MaskVT = getMaskTypeFor(ContainerVT); 5854 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5855 } 5856 } 5857 5858 if (!VL) 5859 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5860 5861 unsigned IntID = 5862 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5863 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5864 Ops.push_back(Val); 5865 Ops.push_back(BasePtr); 5866 if (!IsUnmasked) 5867 Ops.push_back(Mask); 5868 Ops.push_back(VL); 5869 5870 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5871 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5872 } 5873 5874 SDValue 5875 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5876 SelectionDAG &DAG) const { 5877 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5878 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5879 5880 MVT VT = Op.getSimpleValueType(); 5881 5882 SDValue Op1 = 5883 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5884 SDValue Op2 = 5885 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5886 5887 SDLoc DL(Op); 5888 SDValue VL = 5889 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5890 5891 MVT MaskVT = getMaskTypeFor(ContainerVT); 5892 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5893 5894 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5895 Op.getOperand(2), Mask, VL); 5896 5897 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5898 } 5899 5900 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5901 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5902 MVT VT = Op.getSimpleValueType(); 5903 5904 if (VT.getVectorElementType() == MVT::i1) 5905 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5906 5907 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5908 } 5909 5910 SDValue 5911 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5912 SelectionDAG &DAG) const { 5913 unsigned Opc; 5914 switch (Op.getOpcode()) { 5915 default: llvm_unreachable("Unexpected opcode!"); 5916 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5917 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5918 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5919 } 5920 5921 return lowerToScalableOp(Op, DAG, Opc); 5922 } 5923 5924 // Lower vector ABS to smax(X, sub(0, X)). 5925 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5926 SDLoc DL(Op); 5927 MVT VT = Op.getSimpleValueType(); 5928 SDValue X = Op.getOperand(0); 5929 5930 assert(VT.isFixedLengthVector() && "Unexpected type"); 5931 5932 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5933 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5934 5935 SDValue Mask, VL; 5936 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5937 5938 SDValue SplatZero = DAG.getNode( 5939 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5940 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5941 SDValue NegX = 5942 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5943 SDValue Max = 5944 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5945 5946 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5947 } 5948 5949 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5950 SDValue Op, SelectionDAG &DAG) const { 5951 SDLoc DL(Op); 5952 MVT VT = Op.getSimpleValueType(); 5953 SDValue Mag = Op.getOperand(0); 5954 SDValue Sign = Op.getOperand(1); 5955 assert(Mag.getValueType() == Sign.getValueType() && 5956 "Can only handle COPYSIGN with matching types."); 5957 5958 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5959 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5960 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5961 5962 SDValue Mask, VL; 5963 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5964 5965 SDValue CopySign = 5966 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5967 5968 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5969 } 5970 5971 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5972 SDValue Op, SelectionDAG &DAG) const { 5973 MVT VT = Op.getSimpleValueType(); 5974 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5975 5976 MVT I1ContainerVT = 5977 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5978 5979 SDValue CC = 5980 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5981 SDValue Op1 = 5982 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5983 SDValue Op2 = 5984 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5985 5986 SDLoc DL(Op); 5987 SDValue Mask, VL; 5988 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5989 5990 SDValue Select = 5991 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5992 5993 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5994 } 5995 5996 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5997 unsigned NewOpc, 5998 bool HasMask) const { 5999 MVT VT = Op.getSimpleValueType(); 6000 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6001 6002 // Create list of operands by converting existing ones to scalable types. 6003 SmallVector<SDValue, 6> Ops; 6004 for (const SDValue &V : Op->op_values()) { 6005 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6006 6007 // Pass through non-vector operands. 6008 if (!V.getValueType().isVector()) { 6009 Ops.push_back(V); 6010 continue; 6011 } 6012 6013 // "cast" fixed length vector to a scalable vector. 6014 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6015 "Only fixed length vectors are supported!"); 6016 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6017 } 6018 6019 SDLoc DL(Op); 6020 SDValue Mask, VL; 6021 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6022 if (HasMask) 6023 Ops.push_back(Mask); 6024 Ops.push_back(VL); 6025 6026 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6027 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6028 } 6029 6030 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6031 // * Operands of each node are assumed to be in the same order. 6032 // * The EVL operand is promoted from i32 to i64 on RV64. 6033 // * Fixed-length vectors are converted to their scalable-vector container 6034 // types. 6035 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6036 unsigned RISCVISDOpc) const { 6037 SDLoc DL(Op); 6038 MVT VT = Op.getSimpleValueType(); 6039 SmallVector<SDValue, 4> Ops; 6040 6041 for (const auto &OpIdx : enumerate(Op->ops())) { 6042 SDValue V = OpIdx.value(); 6043 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6044 // Pass through operands which aren't fixed-length vectors. 6045 if (!V.getValueType().isFixedLengthVector()) { 6046 Ops.push_back(V); 6047 continue; 6048 } 6049 // "cast" fixed length vector to a scalable vector. 6050 MVT OpVT = V.getSimpleValueType(); 6051 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6052 assert(useRVVForFixedLengthVectorVT(OpVT) && 6053 "Only fixed length vectors are supported!"); 6054 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6055 } 6056 6057 if (!VT.isFixedLengthVector()) 6058 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6059 6060 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6061 6062 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6063 6064 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6065 } 6066 6067 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6068 SelectionDAG &DAG) const { 6069 SDLoc DL(Op); 6070 MVT VT = Op.getSimpleValueType(); 6071 6072 SDValue Src = Op.getOperand(0); 6073 // NOTE: Mask is dropped. 6074 SDValue VL = Op.getOperand(2); 6075 6076 MVT ContainerVT = VT; 6077 if (VT.isFixedLengthVector()) { 6078 ContainerVT = getContainerForFixedLengthVector(VT); 6079 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6080 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6081 } 6082 6083 MVT XLenVT = Subtarget.getXLenVT(); 6084 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6085 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6086 DAG.getUNDEF(ContainerVT), Zero, VL); 6087 6088 SDValue SplatValue = DAG.getConstant( 6089 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6090 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6091 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6092 6093 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6094 Splat, ZeroSplat, VL); 6095 if (!VT.isFixedLengthVector()) 6096 return Result; 6097 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6098 } 6099 6100 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6101 SelectionDAG &DAG) const { 6102 SDLoc DL(Op); 6103 MVT VT = Op.getSimpleValueType(); 6104 6105 SDValue Op1 = Op.getOperand(0); 6106 SDValue Op2 = Op.getOperand(1); 6107 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6108 // NOTE: Mask is dropped. 6109 SDValue VL = Op.getOperand(4); 6110 6111 MVT ContainerVT = VT; 6112 if (VT.isFixedLengthVector()) { 6113 ContainerVT = getContainerForFixedLengthVector(VT); 6114 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6115 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6116 } 6117 6118 SDValue Result; 6119 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6120 6121 switch (Condition) { 6122 default: 6123 break; 6124 // X != Y --> (X^Y) 6125 case ISD::SETNE: 6126 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6127 break; 6128 // X == Y --> ~(X^Y) 6129 case ISD::SETEQ: { 6130 SDValue Temp = 6131 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6132 Result = 6133 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6134 break; 6135 } 6136 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6137 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6138 case ISD::SETGT: 6139 case ISD::SETULT: { 6140 SDValue Temp = 6141 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6142 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6143 break; 6144 } 6145 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6146 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6147 case ISD::SETLT: 6148 case ISD::SETUGT: { 6149 SDValue Temp = 6150 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6151 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6152 break; 6153 } 6154 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6155 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6156 case ISD::SETGE: 6157 case ISD::SETULE: { 6158 SDValue Temp = 6159 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6160 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6161 break; 6162 } 6163 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6164 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6165 case ISD::SETLE: 6166 case ISD::SETUGE: { 6167 SDValue Temp = 6168 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6169 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6170 break; 6171 } 6172 } 6173 6174 if (!VT.isFixedLengthVector()) 6175 return Result; 6176 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6177 } 6178 6179 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6180 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6181 unsigned RISCVISDOpc) const { 6182 SDLoc DL(Op); 6183 6184 SDValue Src = Op.getOperand(0); 6185 SDValue Mask = Op.getOperand(1); 6186 SDValue VL = Op.getOperand(2); 6187 6188 MVT DstVT = Op.getSimpleValueType(); 6189 MVT SrcVT = Src.getSimpleValueType(); 6190 if (DstVT.isFixedLengthVector()) { 6191 DstVT = getContainerForFixedLengthVector(DstVT); 6192 SrcVT = getContainerForFixedLengthVector(SrcVT); 6193 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6194 MVT MaskVT = getMaskTypeFor(DstVT); 6195 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6196 } 6197 6198 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6199 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6200 ? RISCVISD::VSEXT_VL 6201 : RISCVISD::VZEXT_VL; 6202 6203 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6204 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6205 6206 SDValue Result; 6207 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6208 if (SrcVT.isInteger()) { 6209 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6210 6211 // Do we need to do any pre-widening before converting? 6212 if (SrcEltSize == 1) { 6213 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6214 MVT XLenVT = Subtarget.getXLenVT(); 6215 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6216 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6217 DAG.getUNDEF(IntVT), Zero, VL); 6218 SDValue One = DAG.getConstant( 6219 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6220 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6221 DAG.getUNDEF(IntVT), One, VL); 6222 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6223 ZeroSplat, VL); 6224 } else if (DstEltSize > (2 * SrcEltSize)) { 6225 // Widen before converting. 6226 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6227 DstVT.getVectorElementCount()); 6228 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6229 } 6230 6231 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6232 } else { 6233 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6234 "Wrong input/output vector types"); 6235 6236 // Convert f16 to f32 then convert f32 to i64. 6237 if (DstEltSize > (2 * SrcEltSize)) { 6238 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6239 MVT InterimFVT = 6240 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6241 Src = 6242 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6243 } 6244 6245 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6246 } 6247 } else { // Narrowing + Conversion 6248 if (SrcVT.isInteger()) { 6249 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6250 // First do a narrowing convert to an FP type half the size, then round 6251 // the FP type to a small FP type if needed. 6252 6253 MVT InterimFVT = DstVT; 6254 if (SrcEltSize > (2 * DstEltSize)) { 6255 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6256 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6257 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6258 } 6259 6260 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6261 6262 if (InterimFVT != DstVT) { 6263 Src = Result; 6264 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6265 } 6266 } else { 6267 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6268 "Wrong input/output vector types"); 6269 // First do a narrowing conversion to an integer half the size, then 6270 // truncate if needed. 6271 6272 if (DstEltSize == 1) { 6273 // First convert to the same size integer, then convert to mask using 6274 // setcc. 6275 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6276 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6277 DstVT.getVectorElementCount()); 6278 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6279 6280 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6281 // otherwise the conversion was undefined. 6282 MVT XLenVT = Subtarget.getXLenVT(); 6283 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6284 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6285 DAG.getUNDEF(InterimIVT), SplatZero); 6286 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6287 DAG.getCondCode(ISD::SETNE), Mask, VL); 6288 } else { 6289 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6290 DstVT.getVectorElementCount()); 6291 6292 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6293 6294 while (InterimIVT != DstVT) { 6295 SrcEltSize /= 2; 6296 Src = Result; 6297 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6298 DstVT.getVectorElementCount()); 6299 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6300 Src, Mask, VL); 6301 } 6302 } 6303 } 6304 } 6305 6306 MVT VT = Op.getSimpleValueType(); 6307 if (!VT.isFixedLengthVector()) 6308 return Result; 6309 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6310 } 6311 6312 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6313 unsigned MaskOpc, 6314 unsigned VecOpc) const { 6315 MVT VT = Op.getSimpleValueType(); 6316 if (VT.getVectorElementType() != MVT::i1) 6317 return lowerVPOp(Op, DAG, VecOpc); 6318 6319 // It is safe to drop mask parameter as masked-off elements are undef. 6320 SDValue Op1 = Op->getOperand(0); 6321 SDValue Op2 = Op->getOperand(1); 6322 SDValue VL = Op->getOperand(3); 6323 6324 MVT ContainerVT = VT; 6325 const bool IsFixed = VT.isFixedLengthVector(); 6326 if (IsFixed) { 6327 ContainerVT = getContainerForFixedLengthVector(VT); 6328 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6329 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6330 } 6331 6332 SDLoc DL(Op); 6333 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6334 if (!IsFixed) 6335 return Val; 6336 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6337 } 6338 6339 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6340 // matched to a RVV indexed load. The RVV indexed load instructions only 6341 // support the "unsigned unscaled" addressing mode; indices are implicitly 6342 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6343 // signed or scaled indexing is extended to the XLEN value type and scaled 6344 // accordingly. 6345 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6346 SelectionDAG &DAG) const { 6347 SDLoc DL(Op); 6348 MVT VT = Op.getSimpleValueType(); 6349 6350 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6351 EVT MemVT = MemSD->getMemoryVT(); 6352 MachineMemOperand *MMO = MemSD->getMemOperand(); 6353 SDValue Chain = MemSD->getChain(); 6354 SDValue BasePtr = MemSD->getBasePtr(); 6355 6356 ISD::LoadExtType LoadExtType; 6357 SDValue Index, Mask, PassThru, VL; 6358 6359 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6360 Index = VPGN->getIndex(); 6361 Mask = VPGN->getMask(); 6362 PassThru = DAG.getUNDEF(VT); 6363 VL = VPGN->getVectorLength(); 6364 // VP doesn't support extending loads. 6365 LoadExtType = ISD::NON_EXTLOAD; 6366 } else { 6367 // Else it must be a MGATHER. 6368 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6369 Index = MGN->getIndex(); 6370 Mask = MGN->getMask(); 6371 PassThru = MGN->getPassThru(); 6372 LoadExtType = MGN->getExtensionType(); 6373 } 6374 6375 MVT IndexVT = Index.getSimpleValueType(); 6376 MVT XLenVT = Subtarget.getXLenVT(); 6377 6378 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6379 "Unexpected VTs!"); 6380 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6381 // Targets have to explicitly opt-in for extending vector loads. 6382 assert(LoadExtType == ISD::NON_EXTLOAD && 6383 "Unexpected extending MGATHER/VP_GATHER"); 6384 (void)LoadExtType; 6385 6386 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6387 // the selection of the masked intrinsics doesn't do this for us. 6388 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6389 6390 MVT ContainerVT = VT; 6391 if (VT.isFixedLengthVector()) { 6392 // We need to use the larger of the result and index type to determine the 6393 // scalable type to use so we don't increase LMUL for any operand/result. 6394 if (VT.bitsGE(IndexVT)) { 6395 ContainerVT = getContainerForFixedLengthVector(VT); 6396 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6397 ContainerVT.getVectorElementCount()); 6398 } else { 6399 IndexVT = getContainerForFixedLengthVector(IndexVT); 6400 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6401 IndexVT.getVectorElementCount()); 6402 } 6403 6404 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6405 6406 if (!IsUnmasked) { 6407 MVT MaskVT = getMaskTypeFor(ContainerVT); 6408 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6409 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6410 } 6411 } 6412 6413 if (!VL) 6414 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6415 6416 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6417 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6418 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6419 VL); 6420 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6421 TrueMask, VL); 6422 } 6423 6424 unsigned IntID = 6425 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6426 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6427 if (IsUnmasked) 6428 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6429 else 6430 Ops.push_back(PassThru); 6431 Ops.push_back(BasePtr); 6432 Ops.push_back(Index); 6433 if (!IsUnmasked) 6434 Ops.push_back(Mask); 6435 Ops.push_back(VL); 6436 if (!IsUnmasked) 6437 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6438 6439 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6440 SDValue Result = 6441 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6442 Chain = Result.getValue(1); 6443 6444 if (VT.isFixedLengthVector()) 6445 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6446 6447 return DAG.getMergeValues({Result, Chain}, DL); 6448 } 6449 6450 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6451 // matched to a RVV indexed store. The RVV indexed store instructions only 6452 // support the "unsigned unscaled" addressing mode; indices are implicitly 6453 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6454 // signed or scaled indexing is extended to the XLEN value type and scaled 6455 // accordingly. 6456 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6457 SelectionDAG &DAG) const { 6458 SDLoc DL(Op); 6459 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6460 EVT MemVT = MemSD->getMemoryVT(); 6461 MachineMemOperand *MMO = MemSD->getMemOperand(); 6462 SDValue Chain = MemSD->getChain(); 6463 SDValue BasePtr = MemSD->getBasePtr(); 6464 6465 bool IsTruncatingStore = false; 6466 SDValue Index, Mask, Val, VL; 6467 6468 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6469 Index = VPSN->getIndex(); 6470 Mask = VPSN->getMask(); 6471 Val = VPSN->getValue(); 6472 VL = VPSN->getVectorLength(); 6473 // VP doesn't support truncating stores. 6474 IsTruncatingStore = false; 6475 } else { 6476 // Else it must be a MSCATTER. 6477 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6478 Index = MSN->getIndex(); 6479 Mask = MSN->getMask(); 6480 Val = MSN->getValue(); 6481 IsTruncatingStore = MSN->isTruncatingStore(); 6482 } 6483 6484 MVT VT = Val.getSimpleValueType(); 6485 MVT IndexVT = Index.getSimpleValueType(); 6486 MVT XLenVT = Subtarget.getXLenVT(); 6487 6488 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6489 "Unexpected VTs!"); 6490 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6491 // Targets have to explicitly opt-in for extending vector loads and 6492 // truncating vector stores. 6493 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6494 (void)IsTruncatingStore; 6495 6496 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6497 // the selection of the masked intrinsics doesn't do this for us. 6498 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6499 6500 MVT ContainerVT = VT; 6501 if (VT.isFixedLengthVector()) { 6502 // We need to use the larger of the value and index type to determine the 6503 // scalable type to use so we don't increase LMUL for any operand/result. 6504 if (VT.bitsGE(IndexVT)) { 6505 ContainerVT = getContainerForFixedLengthVector(VT); 6506 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6507 ContainerVT.getVectorElementCount()); 6508 } else { 6509 IndexVT = getContainerForFixedLengthVector(IndexVT); 6510 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6511 IndexVT.getVectorElementCount()); 6512 } 6513 6514 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6515 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6516 6517 if (!IsUnmasked) { 6518 MVT MaskVT = getMaskTypeFor(ContainerVT); 6519 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6520 } 6521 } 6522 6523 if (!VL) 6524 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6525 6526 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6527 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6528 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6529 VL); 6530 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6531 TrueMask, VL); 6532 } 6533 6534 unsigned IntID = 6535 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6536 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6537 Ops.push_back(Val); 6538 Ops.push_back(BasePtr); 6539 Ops.push_back(Index); 6540 if (!IsUnmasked) 6541 Ops.push_back(Mask); 6542 Ops.push_back(VL); 6543 6544 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6545 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6546 } 6547 6548 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6549 SelectionDAG &DAG) const { 6550 const MVT XLenVT = Subtarget.getXLenVT(); 6551 SDLoc DL(Op); 6552 SDValue Chain = Op->getOperand(0); 6553 SDValue SysRegNo = DAG.getTargetConstant( 6554 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6555 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6556 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6557 6558 // Encoding used for rounding mode in RISCV differs from that used in 6559 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6560 // table, which consists of a sequence of 4-bit fields, each representing 6561 // corresponding FLT_ROUNDS mode. 6562 static const int Table = 6563 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6564 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6565 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6566 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6567 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6568 6569 SDValue Shift = 6570 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6571 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6572 DAG.getConstant(Table, DL, XLenVT), Shift); 6573 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6574 DAG.getConstant(7, DL, XLenVT)); 6575 6576 return DAG.getMergeValues({Masked, Chain}, DL); 6577 } 6578 6579 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6580 SelectionDAG &DAG) const { 6581 const MVT XLenVT = Subtarget.getXLenVT(); 6582 SDLoc DL(Op); 6583 SDValue Chain = Op->getOperand(0); 6584 SDValue RMValue = Op->getOperand(1); 6585 SDValue SysRegNo = DAG.getTargetConstant( 6586 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6587 6588 // Encoding used for rounding mode in RISCV differs from that used in 6589 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6590 // a table, which consists of a sequence of 4-bit fields, each representing 6591 // corresponding RISCV mode. 6592 static const unsigned Table = 6593 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6594 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6595 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6596 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6597 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6598 6599 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6600 DAG.getConstant(2, DL, XLenVT)); 6601 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6602 DAG.getConstant(Table, DL, XLenVT), Shift); 6603 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6604 DAG.getConstant(0x7, DL, XLenVT)); 6605 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6606 RMValue); 6607 } 6608 6609 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6610 switch (IntNo) { 6611 default: 6612 llvm_unreachable("Unexpected Intrinsic"); 6613 case Intrinsic::riscv_bcompress: 6614 return RISCVISD::BCOMPRESSW; 6615 case Intrinsic::riscv_bdecompress: 6616 return RISCVISD::BDECOMPRESSW; 6617 case Intrinsic::riscv_bfp: 6618 return RISCVISD::BFPW; 6619 case Intrinsic::riscv_fsl: 6620 return RISCVISD::FSLW; 6621 case Intrinsic::riscv_fsr: 6622 return RISCVISD::FSRW; 6623 } 6624 } 6625 6626 // Converts the given intrinsic to a i64 operation with any extension. 6627 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6628 unsigned IntNo) { 6629 SDLoc DL(N); 6630 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6631 // Deal with the Instruction Operands 6632 SmallVector<SDValue, 3> NewOps; 6633 for (SDValue Op : drop_begin(N->ops())) 6634 // Promote the operand to i64 type 6635 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6636 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6637 // ReplaceNodeResults requires we maintain the same type for the return value. 6638 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6639 } 6640 6641 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6642 // form of the given Opcode. 6643 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6644 switch (Opcode) { 6645 default: 6646 llvm_unreachable("Unexpected opcode"); 6647 case ISD::SHL: 6648 return RISCVISD::SLLW; 6649 case ISD::SRA: 6650 return RISCVISD::SRAW; 6651 case ISD::SRL: 6652 return RISCVISD::SRLW; 6653 case ISD::SDIV: 6654 return RISCVISD::DIVW; 6655 case ISD::UDIV: 6656 return RISCVISD::DIVUW; 6657 case ISD::UREM: 6658 return RISCVISD::REMUW; 6659 case ISD::ROTL: 6660 return RISCVISD::ROLW; 6661 case ISD::ROTR: 6662 return RISCVISD::RORW; 6663 } 6664 } 6665 6666 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6667 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6668 // otherwise be promoted to i64, making it difficult to select the 6669 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6670 // type i8/i16/i32 is lost. 6671 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6672 unsigned ExtOpc = ISD::ANY_EXTEND) { 6673 SDLoc DL(N); 6674 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6675 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6676 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6677 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6678 // ReplaceNodeResults requires we maintain the same type for the return value. 6679 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6680 } 6681 6682 // Converts the given 32-bit operation to a i64 operation with signed extension 6683 // semantic to reduce the signed extension instructions. 6684 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6685 SDLoc DL(N); 6686 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6687 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6688 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6689 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6690 DAG.getValueType(MVT::i32)); 6691 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6692 } 6693 6694 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6695 SmallVectorImpl<SDValue> &Results, 6696 SelectionDAG &DAG) const { 6697 SDLoc DL(N); 6698 switch (N->getOpcode()) { 6699 default: 6700 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6701 case ISD::STRICT_FP_TO_SINT: 6702 case ISD::STRICT_FP_TO_UINT: 6703 case ISD::FP_TO_SINT: 6704 case ISD::FP_TO_UINT: { 6705 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6706 "Unexpected custom legalisation"); 6707 bool IsStrict = N->isStrictFPOpcode(); 6708 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6709 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6710 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6711 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6712 TargetLowering::TypeSoftenFloat) { 6713 if (!isTypeLegal(Op0.getValueType())) 6714 return; 6715 if (IsStrict) { 6716 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6717 : RISCVISD::STRICT_FCVT_WU_RV64; 6718 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6719 SDValue Res = DAG.getNode( 6720 Opc, DL, VTs, N->getOperand(0), Op0, 6721 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6722 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6723 Results.push_back(Res.getValue(1)); 6724 return; 6725 } 6726 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6727 SDValue Res = 6728 DAG.getNode(Opc, DL, MVT::i64, Op0, 6729 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6730 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6731 return; 6732 } 6733 // If the FP type needs to be softened, emit a library call using the 'si' 6734 // version. If we left it to default legalization we'd end up with 'di'. If 6735 // the FP type doesn't need to be softened just let generic type 6736 // legalization promote the result type. 6737 RTLIB::Libcall LC; 6738 if (IsSigned) 6739 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6740 else 6741 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6742 MakeLibCallOptions CallOptions; 6743 EVT OpVT = Op0.getValueType(); 6744 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6745 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6746 SDValue Result; 6747 std::tie(Result, Chain) = 6748 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6749 Results.push_back(Result); 6750 if (IsStrict) 6751 Results.push_back(Chain); 6752 break; 6753 } 6754 case ISD::READCYCLECOUNTER: { 6755 assert(!Subtarget.is64Bit() && 6756 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6757 6758 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6759 SDValue RCW = 6760 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6761 6762 Results.push_back( 6763 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6764 Results.push_back(RCW.getValue(2)); 6765 break; 6766 } 6767 case ISD::MUL: { 6768 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6769 unsigned XLen = Subtarget.getXLen(); 6770 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6771 if (Size > XLen) { 6772 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6773 SDValue LHS = N->getOperand(0); 6774 SDValue RHS = N->getOperand(1); 6775 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6776 6777 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6778 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6779 // We need exactly one side to be unsigned. 6780 if (LHSIsU == RHSIsU) 6781 return; 6782 6783 auto MakeMULPair = [&](SDValue S, SDValue U) { 6784 MVT XLenVT = Subtarget.getXLenVT(); 6785 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6786 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6787 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6788 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6789 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6790 }; 6791 6792 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6793 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6794 6795 // The other operand should be signed, but still prefer MULH when 6796 // possible. 6797 if (RHSIsU && LHSIsS && !RHSIsS) 6798 Results.push_back(MakeMULPair(LHS, RHS)); 6799 else if (LHSIsU && RHSIsS && !LHSIsS) 6800 Results.push_back(MakeMULPair(RHS, LHS)); 6801 6802 return; 6803 } 6804 LLVM_FALLTHROUGH; 6805 } 6806 case ISD::ADD: 6807 case ISD::SUB: 6808 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6809 "Unexpected custom legalisation"); 6810 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6811 break; 6812 case ISD::SHL: 6813 case ISD::SRA: 6814 case ISD::SRL: 6815 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6816 "Unexpected custom legalisation"); 6817 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6818 // If we can use a BSET instruction, allow default promotion to apply. 6819 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6820 isOneConstant(N->getOperand(0))) 6821 break; 6822 Results.push_back(customLegalizeToWOp(N, DAG)); 6823 break; 6824 } 6825 6826 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6827 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6828 // shift amount. 6829 if (N->getOpcode() == ISD::SHL) { 6830 SDLoc DL(N); 6831 SDValue NewOp0 = 6832 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6833 SDValue NewOp1 = 6834 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6835 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6836 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6837 DAG.getValueType(MVT::i32)); 6838 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6839 } 6840 6841 break; 6842 case ISD::ROTL: 6843 case ISD::ROTR: 6844 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6845 "Unexpected custom legalisation"); 6846 Results.push_back(customLegalizeToWOp(N, DAG)); 6847 break; 6848 case ISD::CTTZ: 6849 case ISD::CTTZ_ZERO_UNDEF: 6850 case ISD::CTLZ: 6851 case ISD::CTLZ_ZERO_UNDEF: { 6852 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6853 "Unexpected custom legalisation"); 6854 6855 SDValue NewOp0 = 6856 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6857 bool IsCTZ = 6858 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6859 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6860 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6861 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6862 return; 6863 } 6864 case ISD::SDIV: 6865 case ISD::UDIV: 6866 case ISD::UREM: { 6867 MVT VT = N->getSimpleValueType(0); 6868 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6869 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6870 "Unexpected custom legalisation"); 6871 // Don't promote division/remainder by constant since we should expand those 6872 // to multiply by magic constant. 6873 // FIXME: What if the expansion is disabled for minsize. 6874 if (N->getOperand(1).getOpcode() == ISD::Constant) 6875 return; 6876 6877 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6878 // the upper 32 bits. For other types we need to sign or zero extend 6879 // based on the opcode. 6880 unsigned ExtOpc = ISD::ANY_EXTEND; 6881 if (VT != MVT::i32) 6882 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6883 : ISD::ZERO_EXTEND; 6884 6885 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6886 break; 6887 } 6888 case ISD::UADDO: 6889 case ISD::USUBO: { 6890 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6891 "Unexpected custom legalisation"); 6892 bool IsAdd = N->getOpcode() == ISD::UADDO; 6893 // Create an ADDW or SUBW. 6894 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6895 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6896 SDValue Res = 6897 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6898 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6899 DAG.getValueType(MVT::i32)); 6900 6901 SDValue Overflow; 6902 if (IsAdd && isOneConstant(RHS)) { 6903 // Special case uaddo X, 1 overflowed if the addition result is 0. 6904 // The general case (X + C) < C is not necessarily beneficial. Although we 6905 // reduce the live range of X, we may introduce the materialization of 6906 // constant C, especially when the setcc result is used by branch. We have 6907 // no compare with constant and branch instructions. 6908 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6909 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6910 } else { 6911 // Sign extend the LHS and perform an unsigned compare with the ADDW 6912 // result. Since the inputs are sign extended from i32, this is equivalent 6913 // to comparing the lower 32 bits. 6914 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6915 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6916 IsAdd ? ISD::SETULT : ISD::SETUGT); 6917 } 6918 6919 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6920 Results.push_back(Overflow); 6921 return; 6922 } 6923 case ISD::UADDSAT: 6924 case ISD::USUBSAT: { 6925 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6926 "Unexpected custom legalisation"); 6927 if (Subtarget.hasStdExtZbb()) { 6928 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6929 // sign extend allows overflow of the lower 32 bits to be detected on 6930 // the promoted size. 6931 SDValue LHS = 6932 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6933 SDValue RHS = 6934 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6935 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6936 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6937 return; 6938 } 6939 6940 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6941 // promotion for UADDO/USUBO. 6942 Results.push_back(expandAddSubSat(N, DAG)); 6943 return; 6944 } 6945 case ISD::ABS: { 6946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6947 "Unexpected custom legalisation"); 6948 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6949 6950 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6951 6952 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6953 6954 // Freeze the source so we can increase it's use count. 6955 Src = DAG.getFreeze(Src); 6956 6957 // Copy sign bit to all bits using the sraiw pattern. 6958 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6959 DAG.getValueType(MVT::i32)); 6960 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6961 DAG.getConstant(31, DL, MVT::i64)); 6962 6963 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6964 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6965 6966 // NOTE: The result is only required to be anyextended, but sext is 6967 // consistent with type legalization of sub. 6968 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6969 DAG.getValueType(MVT::i32)); 6970 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6971 return; 6972 } 6973 case ISD::BITCAST: { 6974 EVT VT = N->getValueType(0); 6975 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6976 SDValue Op0 = N->getOperand(0); 6977 EVT Op0VT = Op0.getValueType(); 6978 MVT XLenVT = Subtarget.getXLenVT(); 6979 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6980 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6981 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6982 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6983 Subtarget.hasStdExtF()) { 6984 SDValue FPConv = 6985 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6986 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6987 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6988 isTypeLegal(Op0VT)) { 6989 // Custom-legalize bitcasts from fixed-length vector types to illegal 6990 // scalar types in order to improve codegen. Bitcast the vector to a 6991 // one-element vector type whose element type is the same as the result 6992 // type, and extract the first element. 6993 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6994 if (isTypeLegal(BVT)) { 6995 SDValue BVec = DAG.getBitcast(BVT, Op0); 6996 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6997 DAG.getConstant(0, DL, XLenVT))); 6998 } 6999 } 7000 break; 7001 } 7002 case RISCVISD::GREV: 7003 case RISCVISD::GORC: 7004 case RISCVISD::SHFL: { 7005 MVT VT = N->getSimpleValueType(0); 7006 MVT XLenVT = Subtarget.getXLenVT(); 7007 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7008 "Unexpected custom legalisation"); 7009 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7010 assert((Subtarget.hasStdExtZbp() || 7011 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7012 N->getConstantOperandVal(1) == 7)) && 7013 "Unexpected extension"); 7014 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7015 SDValue NewOp1 = 7016 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7017 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7018 // ReplaceNodeResults requires we maintain the same type for the return 7019 // value. 7020 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7021 break; 7022 } 7023 case ISD::BSWAP: 7024 case ISD::BITREVERSE: { 7025 MVT VT = N->getSimpleValueType(0); 7026 MVT XLenVT = Subtarget.getXLenVT(); 7027 assert((VT == MVT::i8 || VT == MVT::i16 || 7028 (VT == MVT::i32 && Subtarget.is64Bit())) && 7029 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7030 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7031 unsigned Imm = VT.getSizeInBits() - 1; 7032 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7033 if (N->getOpcode() == ISD::BSWAP) 7034 Imm &= ~0x7U; 7035 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7036 DAG.getConstant(Imm, DL, XLenVT)); 7037 // ReplaceNodeResults requires we maintain the same type for the return 7038 // value. 7039 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7040 break; 7041 } 7042 case ISD::FSHL: 7043 case ISD::FSHR: { 7044 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7045 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7046 SDValue NewOp0 = 7047 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7048 SDValue NewOp1 = 7049 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7050 SDValue NewShAmt = 7051 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7052 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7053 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7054 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7055 DAG.getConstant(0x1f, DL, MVT::i64)); 7056 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7057 // instruction use different orders. fshl will return its first operand for 7058 // shift of zero, fshr will return its second operand. fsl and fsr both 7059 // return rs1 so the ISD nodes need to have different operand orders. 7060 // Shift amount is in rs2. 7061 unsigned Opc = RISCVISD::FSLW; 7062 if (N->getOpcode() == ISD::FSHR) { 7063 std::swap(NewOp0, NewOp1); 7064 Opc = RISCVISD::FSRW; 7065 } 7066 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7067 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7068 break; 7069 } 7070 case ISD::EXTRACT_VECTOR_ELT: { 7071 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7072 // type is illegal (currently only vXi64 RV32). 7073 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7074 // transferred to the destination register. We issue two of these from the 7075 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7076 // first element. 7077 SDValue Vec = N->getOperand(0); 7078 SDValue Idx = N->getOperand(1); 7079 7080 // The vector type hasn't been legalized yet so we can't issue target 7081 // specific nodes if it needs legalization. 7082 // FIXME: We would manually legalize if it's important. 7083 if (!isTypeLegal(Vec.getValueType())) 7084 return; 7085 7086 MVT VecVT = Vec.getSimpleValueType(); 7087 7088 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7089 VecVT.getVectorElementType() == MVT::i64 && 7090 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7091 7092 // If this is a fixed vector, we need to convert it to a scalable vector. 7093 MVT ContainerVT = VecVT; 7094 if (VecVT.isFixedLengthVector()) { 7095 ContainerVT = getContainerForFixedLengthVector(VecVT); 7096 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7097 } 7098 7099 MVT XLenVT = Subtarget.getXLenVT(); 7100 7101 // Use a VL of 1 to avoid processing more elements than we need. 7102 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7103 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7104 7105 // Unless the index is known to be 0, we must slide the vector down to get 7106 // the desired element into index 0. 7107 if (!isNullConstant(Idx)) { 7108 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7109 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7110 } 7111 7112 // Extract the lower XLEN bits of the correct vector element. 7113 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7114 7115 // To extract the upper XLEN bits of the vector element, shift the first 7116 // element right by 32 bits and re-extract the lower XLEN bits. 7117 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7118 DAG.getUNDEF(ContainerVT), 7119 DAG.getConstant(32, DL, XLenVT), VL); 7120 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7121 ThirtyTwoV, Mask, VL); 7122 7123 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7124 7125 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7126 break; 7127 } 7128 case ISD::INTRINSIC_WO_CHAIN: { 7129 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7130 switch (IntNo) { 7131 default: 7132 llvm_unreachable( 7133 "Don't know how to custom type legalize this intrinsic!"); 7134 case Intrinsic::riscv_grev: 7135 case Intrinsic::riscv_gorc: { 7136 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7137 "Unexpected custom legalisation"); 7138 SDValue NewOp1 = 7139 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7140 SDValue NewOp2 = 7141 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7142 unsigned Opc = 7143 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7144 // If the control is a constant, promote the node by clearing any extra 7145 // bits bits in the control. isel will form greviw/gorciw if the result is 7146 // sign extended. 7147 if (isa<ConstantSDNode>(NewOp2)) { 7148 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7149 DAG.getConstant(0x1f, DL, MVT::i64)); 7150 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7151 } 7152 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7153 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7154 break; 7155 } 7156 case Intrinsic::riscv_bcompress: 7157 case Intrinsic::riscv_bdecompress: 7158 case Intrinsic::riscv_bfp: 7159 case Intrinsic::riscv_fsl: 7160 case Intrinsic::riscv_fsr: { 7161 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7162 "Unexpected custom legalisation"); 7163 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7164 break; 7165 } 7166 case Intrinsic::riscv_orc_b: { 7167 // Lower to the GORCI encoding for orc.b with the operand extended. 7168 SDValue NewOp = 7169 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7170 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7171 DAG.getConstant(7, DL, MVT::i64)); 7172 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7173 return; 7174 } 7175 case Intrinsic::riscv_shfl: 7176 case Intrinsic::riscv_unshfl: { 7177 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7178 "Unexpected custom legalisation"); 7179 SDValue NewOp1 = 7180 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7181 SDValue NewOp2 = 7182 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7183 unsigned Opc = 7184 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7185 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7186 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7187 // will be shuffled the same way as the lower 32 bit half, but the two 7188 // halves won't cross. 7189 if (isa<ConstantSDNode>(NewOp2)) { 7190 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7191 DAG.getConstant(0xf, DL, MVT::i64)); 7192 Opc = 7193 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7194 } 7195 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7196 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7197 break; 7198 } 7199 case Intrinsic::riscv_vmv_x_s: { 7200 EVT VT = N->getValueType(0); 7201 MVT XLenVT = Subtarget.getXLenVT(); 7202 if (VT.bitsLT(XLenVT)) { 7203 // Simple case just extract using vmv.x.s and truncate. 7204 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7205 Subtarget.getXLenVT(), N->getOperand(1)); 7206 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7207 return; 7208 } 7209 7210 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7211 "Unexpected custom legalization"); 7212 7213 // We need to do the move in two steps. 7214 SDValue Vec = N->getOperand(1); 7215 MVT VecVT = Vec.getSimpleValueType(); 7216 7217 // First extract the lower XLEN bits of the element. 7218 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7219 7220 // To extract the upper XLEN bits of the vector element, shift the first 7221 // element right by 32 bits and re-extract the lower XLEN bits. 7222 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7223 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7224 7225 SDValue ThirtyTwoV = 7226 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7227 DAG.getConstant(32, DL, XLenVT), VL); 7228 SDValue LShr32 = 7229 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7230 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7231 7232 Results.push_back( 7233 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7234 break; 7235 } 7236 } 7237 break; 7238 } 7239 case ISD::VECREDUCE_ADD: 7240 case ISD::VECREDUCE_AND: 7241 case ISD::VECREDUCE_OR: 7242 case ISD::VECREDUCE_XOR: 7243 case ISD::VECREDUCE_SMAX: 7244 case ISD::VECREDUCE_UMAX: 7245 case ISD::VECREDUCE_SMIN: 7246 case ISD::VECREDUCE_UMIN: 7247 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7248 Results.push_back(V); 7249 break; 7250 case ISD::VP_REDUCE_ADD: 7251 case ISD::VP_REDUCE_AND: 7252 case ISD::VP_REDUCE_OR: 7253 case ISD::VP_REDUCE_XOR: 7254 case ISD::VP_REDUCE_SMAX: 7255 case ISD::VP_REDUCE_UMAX: 7256 case ISD::VP_REDUCE_SMIN: 7257 case ISD::VP_REDUCE_UMIN: 7258 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7259 Results.push_back(V); 7260 break; 7261 case ISD::FLT_ROUNDS_: { 7262 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7263 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7264 Results.push_back(Res.getValue(0)); 7265 Results.push_back(Res.getValue(1)); 7266 break; 7267 } 7268 } 7269 } 7270 7271 // A structure to hold one of the bit-manipulation patterns below. Together, a 7272 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7273 // (or (and (shl x, 1), 0xAAAAAAAA), 7274 // (and (srl x, 1), 0x55555555)) 7275 struct RISCVBitmanipPat { 7276 SDValue Op; 7277 unsigned ShAmt; 7278 bool IsSHL; 7279 7280 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7281 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7282 } 7283 }; 7284 7285 // Matches patterns of the form 7286 // (and (shl x, C2), (C1 << C2)) 7287 // (and (srl x, C2), C1) 7288 // (shl (and x, C1), C2) 7289 // (srl (and x, (C1 << C2)), C2) 7290 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7291 // The expected masks for each shift amount are specified in BitmanipMasks where 7292 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7293 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7294 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7295 // XLen is 64. 7296 static Optional<RISCVBitmanipPat> 7297 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7298 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7299 "Unexpected number of masks"); 7300 Optional<uint64_t> Mask; 7301 // Optionally consume a mask around the shift operation. 7302 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7303 Mask = Op.getConstantOperandVal(1); 7304 Op = Op.getOperand(0); 7305 } 7306 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7307 return None; 7308 bool IsSHL = Op.getOpcode() == ISD::SHL; 7309 7310 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7311 return None; 7312 uint64_t ShAmt = Op.getConstantOperandVal(1); 7313 7314 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7315 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7316 return None; 7317 // If we don't have enough masks for 64 bit, then we must be trying to 7318 // match SHFL so we're only allowed to shift 1/4 of the width. 7319 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7320 return None; 7321 7322 SDValue Src = Op.getOperand(0); 7323 7324 // The expected mask is shifted left when the AND is found around SHL 7325 // patterns. 7326 // ((x >> 1) & 0x55555555) 7327 // ((x << 1) & 0xAAAAAAAA) 7328 bool SHLExpMask = IsSHL; 7329 7330 if (!Mask) { 7331 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7332 // the mask is all ones: consume that now. 7333 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7334 Mask = Src.getConstantOperandVal(1); 7335 Src = Src.getOperand(0); 7336 // The expected mask is now in fact shifted left for SRL, so reverse the 7337 // decision. 7338 // ((x & 0xAAAAAAAA) >> 1) 7339 // ((x & 0x55555555) << 1) 7340 SHLExpMask = !SHLExpMask; 7341 } else { 7342 // Use a default shifted mask of all-ones if there's no AND, truncated 7343 // down to the expected width. This simplifies the logic later on. 7344 Mask = maskTrailingOnes<uint64_t>(Width); 7345 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7346 } 7347 } 7348 7349 unsigned MaskIdx = Log2_32(ShAmt); 7350 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7351 7352 if (SHLExpMask) 7353 ExpMask <<= ShAmt; 7354 7355 if (Mask != ExpMask) 7356 return None; 7357 7358 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7359 } 7360 7361 // Matches any of the following bit-manipulation patterns: 7362 // (and (shl x, 1), (0x55555555 << 1)) 7363 // (and (srl x, 1), 0x55555555) 7364 // (shl (and x, 0x55555555), 1) 7365 // (srl (and x, (0x55555555 << 1)), 1) 7366 // where the shift amount and mask may vary thus: 7367 // [1] = 0x55555555 / 0xAAAAAAAA 7368 // [2] = 0x33333333 / 0xCCCCCCCC 7369 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7370 // [8] = 0x00FF00FF / 0xFF00FF00 7371 // [16] = 0x0000FFFF / 0xFFFFFFFF 7372 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7373 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7374 // These are the unshifted masks which we use to match bit-manipulation 7375 // patterns. They may be shifted left in certain circumstances. 7376 static const uint64_t BitmanipMasks[] = { 7377 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7378 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7379 7380 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7381 } 7382 7383 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7384 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7385 auto BinOpToRVVReduce = [](unsigned Opc) { 7386 switch (Opc) { 7387 default: 7388 llvm_unreachable("Unhandled binary to transfrom reduction"); 7389 case ISD::ADD: 7390 return RISCVISD::VECREDUCE_ADD_VL; 7391 case ISD::UMAX: 7392 return RISCVISD::VECREDUCE_UMAX_VL; 7393 case ISD::SMAX: 7394 return RISCVISD::VECREDUCE_SMAX_VL; 7395 case ISD::UMIN: 7396 return RISCVISD::VECREDUCE_UMIN_VL; 7397 case ISD::SMIN: 7398 return RISCVISD::VECREDUCE_SMIN_VL; 7399 case ISD::AND: 7400 return RISCVISD::VECREDUCE_AND_VL; 7401 case ISD::OR: 7402 return RISCVISD::VECREDUCE_OR_VL; 7403 case ISD::XOR: 7404 return RISCVISD::VECREDUCE_XOR_VL; 7405 case ISD::FADD: 7406 return RISCVISD::VECREDUCE_FADD_VL; 7407 case ISD::FMAXNUM: 7408 return RISCVISD::VECREDUCE_FMAX_VL; 7409 case ISD::FMINNUM: 7410 return RISCVISD::VECREDUCE_FMIN_VL; 7411 } 7412 }; 7413 7414 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7415 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7416 isNullConstant(V.getOperand(1)) && 7417 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7418 }; 7419 7420 unsigned Opc = N->getOpcode(); 7421 unsigned ReduceIdx; 7422 if (IsReduction(N->getOperand(0), Opc)) 7423 ReduceIdx = 0; 7424 else if (IsReduction(N->getOperand(1), Opc)) 7425 ReduceIdx = 1; 7426 else 7427 return SDValue(); 7428 7429 // Skip if FADD disallows reassociation but the combiner needs. 7430 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7431 return SDValue(); 7432 7433 SDValue Extract = N->getOperand(ReduceIdx); 7434 SDValue Reduce = Extract.getOperand(0); 7435 if (!Reduce.hasOneUse()) 7436 return SDValue(); 7437 7438 SDValue ScalarV = Reduce.getOperand(2); 7439 7440 // Make sure that ScalarV is a splat with VL=1. 7441 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7442 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7443 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7444 return SDValue(); 7445 7446 if (!isOneConstant(ScalarV.getOperand(2))) 7447 return SDValue(); 7448 7449 // TODO: Deal with value other than neutral element. 7450 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7451 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7452 isNullFPConstant(V)) 7453 return true; 7454 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7455 N->getFlags()) == V; 7456 }; 7457 7458 // Check the scalar of ScalarV is neutral element 7459 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7460 return SDValue(); 7461 7462 if (!ScalarV.hasOneUse()) 7463 return SDValue(); 7464 7465 EVT SplatVT = ScalarV.getValueType(); 7466 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7467 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7468 if (SplatVT.isInteger()) { 7469 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7470 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7471 SplatOpc = RISCVISD::VMV_S_X_VL; 7472 else 7473 SplatOpc = RISCVISD::VMV_V_X_VL; 7474 } 7475 7476 SDValue NewScalarV = 7477 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7478 ScalarV.getOperand(2)); 7479 SDValue NewReduce = 7480 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7481 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7482 Reduce.getOperand(3), Reduce.getOperand(4)); 7483 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7484 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7485 } 7486 7487 // Match the following pattern as a GREVI(W) operation 7488 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7489 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7490 const RISCVSubtarget &Subtarget) { 7491 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7492 EVT VT = Op.getValueType(); 7493 7494 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7495 auto LHS = matchGREVIPat(Op.getOperand(0)); 7496 auto RHS = matchGREVIPat(Op.getOperand(1)); 7497 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7498 SDLoc DL(Op); 7499 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7500 DAG.getConstant(LHS->ShAmt, DL, VT)); 7501 } 7502 } 7503 return SDValue(); 7504 } 7505 7506 // Matches any the following pattern as a GORCI(W) operation 7507 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7508 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7509 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7510 // Note that with the variant of 3., 7511 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7512 // the inner pattern will first be matched as GREVI and then the outer 7513 // pattern will be matched to GORC via the first rule above. 7514 // 4. (or (rotl/rotr x, bitwidth/2), x) 7515 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7516 const RISCVSubtarget &Subtarget) { 7517 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7518 EVT VT = Op.getValueType(); 7519 7520 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7521 SDLoc DL(Op); 7522 SDValue Op0 = Op.getOperand(0); 7523 SDValue Op1 = Op.getOperand(1); 7524 7525 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7526 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7527 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7528 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7529 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7530 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7531 if ((Reverse.getOpcode() == ISD::ROTL || 7532 Reverse.getOpcode() == ISD::ROTR) && 7533 Reverse.getOperand(0) == X && 7534 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7535 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7536 if (RotAmt == (VT.getSizeInBits() / 2)) 7537 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7538 DAG.getConstant(RotAmt, DL, VT)); 7539 } 7540 return SDValue(); 7541 }; 7542 7543 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7544 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7545 return V; 7546 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7547 return V; 7548 7549 // OR is commutable so canonicalize its OR operand to the left 7550 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7551 std::swap(Op0, Op1); 7552 if (Op0.getOpcode() != ISD::OR) 7553 return SDValue(); 7554 SDValue OrOp0 = Op0.getOperand(0); 7555 SDValue OrOp1 = Op0.getOperand(1); 7556 auto LHS = matchGREVIPat(OrOp0); 7557 // OR is commutable so swap the operands and try again: x might have been 7558 // on the left 7559 if (!LHS) { 7560 std::swap(OrOp0, OrOp1); 7561 LHS = matchGREVIPat(OrOp0); 7562 } 7563 auto RHS = matchGREVIPat(Op1); 7564 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7565 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7566 DAG.getConstant(LHS->ShAmt, DL, VT)); 7567 } 7568 } 7569 return SDValue(); 7570 } 7571 7572 // Matches any of the following bit-manipulation patterns: 7573 // (and (shl x, 1), (0x22222222 << 1)) 7574 // (and (srl x, 1), 0x22222222) 7575 // (shl (and x, 0x22222222), 1) 7576 // (srl (and x, (0x22222222 << 1)), 1) 7577 // where the shift amount and mask may vary thus: 7578 // [1] = 0x22222222 / 0x44444444 7579 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7580 // [4] = 0x00F000F0 / 0x0F000F00 7581 // [8] = 0x0000FF00 / 0x00FF0000 7582 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7583 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7584 // These are the unshifted masks which we use to match bit-manipulation 7585 // patterns. They may be shifted left in certain circumstances. 7586 static const uint64_t BitmanipMasks[] = { 7587 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7588 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7589 7590 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7591 } 7592 7593 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7594 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7595 const RISCVSubtarget &Subtarget) { 7596 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7597 EVT VT = Op.getValueType(); 7598 7599 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7600 return SDValue(); 7601 7602 SDValue Op0 = Op.getOperand(0); 7603 SDValue Op1 = Op.getOperand(1); 7604 7605 // Or is commutable so canonicalize the second OR to the LHS. 7606 if (Op0.getOpcode() != ISD::OR) 7607 std::swap(Op0, Op1); 7608 if (Op0.getOpcode() != ISD::OR) 7609 return SDValue(); 7610 7611 // We found an inner OR, so our operands are the operands of the inner OR 7612 // and the other operand of the outer OR. 7613 SDValue A = Op0.getOperand(0); 7614 SDValue B = Op0.getOperand(1); 7615 SDValue C = Op1; 7616 7617 auto Match1 = matchSHFLPat(A); 7618 auto Match2 = matchSHFLPat(B); 7619 7620 // If neither matched, we failed. 7621 if (!Match1 && !Match2) 7622 return SDValue(); 7623 7624 // We had at least one match. if one failed, try the remaining C operand. 7625 if (!Match1) { 7626 std::swap(A, C); 7627 Match1 = matchSHFLPat(A); 7628 if (!Match1) 7629 return SDValue(); 7630 } else if (!Match2) { 7631 std::swap(B, C); 7632 Match2 = matchSHFLPat(B); 7633 if (!Match2) 7634 return SDValue(); 7635 } 7636 assert(Match1 && Match2); 7637 7638 // Make sure our matches pair up. 7639 if (!Match1->formsPairWith(*Match2)) 7640 return SDValue(); 7641 7642 // All the remains is to make sure C is an AND with the same input, that masks 7643 // out the bits that are being shuffled. 7644 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7645 C.getOperand(0) != Match1->Op) 7646 return SDValue(); 7647 7648 uint64_t Mask = C.getConstantOperandVal(1); 7649 7650 static const uint64_t BitmanipMasks[] = { 7651 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7652 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7653 }; 7654 7655 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7656 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7657 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7658 7659 if (Mask != ExpMask) 7660 return SDValue(); 7661 7662 SDLoc DL(Op); 7663 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7664 DAG.getConstant(Match1->ShAmt, DL, VT)); 7665 } 7666 7667 // Optimize (add (shl x, c0), (shl y, c1)) -> 7668 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7669 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7670 const RISCVSubtarget &Subtarget) { 7671 // Perform this optimization only in the zba extension. 7672 if (!Subtarget.hasStdExtZba()) 7673 return SDValue(); 7674 7675 // Skip for vector types and larger types. 7676 EVT VT = N->getValueType(0); 7677 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7678 return SDValue(); 7679 7680 // The two operand nodes must be SHL and have no other use. 7681 SDValue N0 = N->getOperand(0); 7682 SDValue N1 = N->getOperand(1); 7683 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7684 !N0->hasOneUse() || !N1->hasOneUse()) 7685 return SDValue(); 7686 7687 // Check c0 and c1. 7688 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7689 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7690 if (!N0C || !N1C) 7691 return SDValue(); 7692 int64_t C0 = N0C->getSExtValue(); 7693 int64_t C1 = N1C->getSExtValue(); 7694 if (C0 <= 0 || C1 <= 0) 7695 return SDValue(); 7696 7697 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7698 int64_t Bits = std::min(C0, C1); 7699 int64_t Diff = std::abs(C0 - C1); 7700 if (Diff != 1 && Diff != 2 && Diff != 3) 7701 return SDValue(); 7702 7703 // Build nodes. 7704 SDLoc DL(N); 7705 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7706 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7707 SDValue NA0 = 7708 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7709 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7710 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7711 } 7712 7713 // Combine 7714 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7715 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7716 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7717 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7718 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7719 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7720 // The grev patterns represents BSWAP. 7721 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7722 // off the grev. 7723 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7724 const RISCVSubtarget &Subtarget) { 7725 bool IsWInstruction = 7726 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7727 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7728 IsWInstruction) && 7729 "Unexpected opcode!"); 7730 SDValue Src = N->getOperand(0); 7731 EVT VT = N->getValueType(0); 7732 SDLoc DL(N); 7733 7734 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7735 return SDValue(); 7736 7737 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7738 !isa<ConstantSDNode>(Src.getOperand(1))) 7739 return SDValue(); 7740 7741 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7742 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7743 7744 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7745 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7746 unsigned ShAmt1 = N->getConstantOperandVal(1); 7747 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7748 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7749 return SDValue(); 7750 7751 Src = Src.getOperand(0); 7752 7753 // Toggle bit the MSB of the shift. 7754 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7755 if (CombinedShAmt == 0) 7756 return Src; 7757 7758 SDValue Res = DAG.getNode( 7759 RISCVISD::GREV, DL, VT, Src, 7760 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7761 if (!IsWInstruction) 7762 return Res; 7763 7764 // Sign extend the result to match the behavior of the rotate. This will be 7765 // selected to GREVIW in isel. 7766 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7767 DAG.getValueType(MVT::i32)); 7768 } 7769 7770 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7771 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7772 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7773 // not undo itself, but they are redundant. 7774 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7775 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7776 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7777 SDValue Src = N->getOperand(0); 7778 7779 if (Src.getOpcode() != N->getOpcode()) 7780 return SDValue(); 7781 7782 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7783 !isa<ConstantSDNode>(Src.getOperand(1))) 7784 return SDValue(); 7785 7786 unsigned ShAmt1 = N->getConstantOperandVal(1); 7787 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7788 Src = Src.getOperand(0); 7789 7790 unsigned CombinedShAmt; 7791 if (IsGORC) 7792 CombinedShAmt = ShAmt1 | ShAmt2; 7793 else 7794 CombinedShAmt = ShAmt1 ^ ShAmt2; 7795 7796 if (CombinedShAmt == 0) 7797 return Src; 7798 7799 SDLoc DL(N); 7800 return DAG.getNode( 7801 N->getOpcode(), DL, N->getValueType(0), Src, 7802 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7803 } 7804 7805 // Combine a constant select operand into its use: 7806 // 7807 // (and (select cond, -1, c), x) 7808 // -> (select cond, x, (and x, c)) [AllOnes=1] 7809 // (or (select cond, 0, c), x) 7810 // -> (select cond, x, (or x, c)) [AllOnes=0] 7811 // (xor (select cond, 0, c), x) 7812 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7813 // (add (select cond, 0, c), x) 7814 // -> (select cond, x, (add x, c)) [AllOnes=0] 7815 // (sub x, (select cond, 0, c)) 7816 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7817 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7818 SelectionDAG &DAG, bool AllOnes) { 7819 EVT VT = N->getValueType(0); 7820 7821 // Skip vectors. 7822 if (VT.isVector()) 7823 return SDValue(); 7824 7825 if ((Slct.getOpcode() != ISD::SELECT && 7826 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7827 !Slct.hasOneUse()) 7828 return SDValue(); 7829 7830 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7831 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7832 }; 7833 7834 bool SwapSelectOps; 7835 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7836 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7837 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7838 SDValue NonConstantVal; 7839 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7840 SwapSelectOps = false; 7841 NonConstantVal = FalseVal; 7842 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7843 SwapSelectOps = true; 7844 NonConstantVal = TrueVal; 7845 } else 7846 return SDValue(); 7847 7848 // Slct is now know to be the desired identity constant when CC is true. 7849 TrueVal = OtherOp; 7850 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7851 // Unless SwapSelectOps says the condition should be false. 7852 if (SwapSelectOps) 7853 std::swap(TrueVal, FalseVal); 7854 7855 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7856 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7857 {Slct.getOperand(0), Slct.getOperand(1), 7858 Slct.getOperand(2), TrueVal, FalseVal}); 7859 7860 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7861 {Slct.getOperand(0), TrueVal, FalseVal}); 7862 } 7863 7864 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7865 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7866 bool AllOnes) { 7867 SDValue N0 = N->getOperand(0); 7868 SDValue N1 = N->getOperand(1); 7869 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7870 return Result; 7871 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7872 return Result; 7873 return SDValue(); 7874 } 7875 7876 // Transform (add (mul x, c0), c1) -> 7877 // (add (mul (add x, c1/c0), c0), c1%c0). 7878 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7879 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7880 // to an infinite loop in DAGCombine if transformed. 7881 // Or transform (add (mul x, c0), c1) -> 7882 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7883 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7884 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7885 // lead to an infinite loop in DAGCombine if transformed. 7886 // Or transform (add (mul x, c0), c1) -> 7887 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7888 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7889 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7890 // lead to an infinite loop in DAGCombine if transformed. 7891 // Or transform (add (mul x, c0), c1) -> 7892 // (mul (add x, c1/c0), c0). 7893 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7894 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7895 const RISCVSubtarget &Subtarget) { 7896 // Skip for vector types and larger types. 7897 EVT VT = N->getValueType(0); 7898 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7899 return SDValue(); 7900 // The first operand node must be a MUL and has no other use. 7901 SDValue N0 = N->getOperand(0); 7902 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7903 return SDValue(); 7904 // Check if c0 and c1 match above conditions. 7905 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7906 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7907 if (!N0C || !N1C) 7908 return SDValue(); 7909 // If N0C has multiple uses it's possible one of the cases in 7910 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7911 // in an infinite loop. 7912 if (!N0C->hasOneUse()) 7913 return SDValue(); 7914 int64_t C0 = N0C->getSExtValue(); 7915 int64_t C1 = N1C->getSExtValue(); 7916 int64_t CA, CB; 7917 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7918 return SDValue(); 7919 // Search for proper CA (non-zero) and CB that both are simm12. 7920 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7921 !isInt<12>(C0 * (C1 / C0))) { 7922 CA = C1 / C0; 7923 CB = C1 % C0; 7924 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7925 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7926 CA = C1 / C0 + 1; 7927 CB = C1 % C0 - C0; 7928 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7929 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7930 CA = C1 / C0 - 1; 7931 CB = C1 % C0 + C0; 7932 } else 7933 return SDValue(); 7934 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7935 SDLoc DL(N); 7936 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7937 DAG.getConstant(CA, DL, VT)); 7938 SDValue New1 = 7939 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7940 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7941 } 7942 7943 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7944 const RISCVSubtarget &Subtarget) { 7945 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7946 return V; 7947 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7948 return V; 7949 if (SDValue V = combineBinOpToReduce(N, DAG)) 7950 return V; 7951 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7952 // (select lhs, rhs, cc, x, (add x, y)) 7953 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7954 } 7955 7956 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7957 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7958 // (select lhs, rhs, cc, x, (sub x, y)) 7959 SDValue N0 = N->getOperand(0); 7960 SDValue N1 = N->getOperand(1); 7961 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7962 } 7963 7964 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 7965 const RISCVSubtarget &Subtarget) { 7966 SDValue N0 = N->getOperand(0); 7967 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 7968 // extending X. This is safe since we only need the LSB after the shift and 7969 // shift amounts larger than 31 would produce poison. If we wait until 7970 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 7971 // to use a BEXT instruction. 7972 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 7973 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 7974 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 7975 N0.hasOneUse()) { 7976 SDLoc DL(N); 7977 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 7978 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 7979 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 7980 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 7981 DAG.getConstant(1, DL, MVT::i64)); 7982 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 7983 } 7984 7985 if (SDValue V = combineBinOpToReduce(N, DAG)) 7986 return V; 7987 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, Subtarget); 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 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