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 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, 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, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 494 ISD::VP_FPTOUI}; 495 496 static const unsigned FloatingPointVPOps[] = { 497 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 498 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 499 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 500 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT, 501 ISD::VP_SITOFP, ISD::VP_UITOFP}; 502 503 if (!Subtarget.is64Bit()) { 504 // We must custom-lower certain vXi64 operations on RV32 due to the vector 505 // element type being illegal. 506 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 507 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 508 509 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 512 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 513 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 515 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 516 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 517 518 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 521 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 522 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 524 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 525 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 526 } 527 528 for (MVT VT : BoolVecVTs) { 529 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 530 531 // Mask VTs are custom-expanded into a series of standard nodes 532 setOperationAction(ISD::TRUNCATE, VT, Custom); 533 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 534 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 535 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 536 537 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 538 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 539 540 setOperationAction(ISD::SELECT, VT, Custom); 541 setOperationAction(ISD::SELECT_CC, VT, Expand); 542 setOperationAction(ISD::VSELECT, VT, Expand); 543 setOperationAction(ISD::VP_MERGE, VT, Expand); 544 setOperationAction(ISD::VP_SELECT, VT, Expand); 545 546 setOperationAction(ISD::VP_AND, VT, Custom); 547 setOperationAction(ISD::VP_OR, VT, Custom); 548 setOperationAction(ISD::VP_XOR, VT, Custom); 549 550 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 551 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 552 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 553 554 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 555 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 556 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 557 558 // RVV has native int->float & float->int conversions where the 559 // element type sizes are within one power-of-two of each other. Any 560 // wider distances between type sizes have to be lowered as sequences 561 // which progressively narrow the gap in stages. 562 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 563 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 564 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 565 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 566 567 // Expand all extending loads to types larger than this, and truncating 568 // stores from types larger than this. 569 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 570 setTruncStoreAction(OtherVT, VT, Expand); 571 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 572 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 573 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 574 } 575 576 setOperationAction(ISD::VP_FPTOSI, VT, Custom); 577 setOperationAction(ISD::VP_FPTOUI, VT, Custom); 578 } 579 580 for (MVT VT : IntVecVTs) { 581 if (VT.getVectorElementType() == MVT::i64 && 582 !Subtarget.hasVInstructionsI64()) 583 continue; 584 585 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 586 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 587 588 // Vectors implement MULHS/MULHU. 589 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 590 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 591 592 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 593 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 594 setOperationAction(ISD::MULHU, VT, Expand); 595 setOperationAction(ISD::MULHS, VT, Expand); 596 } 597 598 setOperationAction(ISD::SMIN, VT, Legal); 599 setOperationAction(ISD::SMAX, VT, Legal); 600 setOperationAction(ISD::UMIN, VT, Legal); 601 setOperationAction(ISD::UMAX, VT, Legal); 602 603 setOperationAction(ISD::ROTL, VT, Expand); 604 setOperationAction(ISD::ROTR, VT, Expand); 605 606 setOperationAction(ISD::CTTZ, VT, Expand); 607 setOperationAction(ISD::CTLZ, VT, Expand); 608 setOperationAction(ISD::CTPOP, VT, Expand); 609 610 setOperationAction(ISD::BSWAP, VT, Expand); 611 612 // Custom-lower extensions and truncations from/to mask types. 613 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 614 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 615 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 616 617 // RVV has native int->float & float->int conversions where the 618 // element type sizes are within one power-of-two of each other. Any 619 // wider distances between type sizes have to be lowered as sequences 620 // which progressively narrow the gap in stages. 621 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 622 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 623 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 624 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 625 626 setOperationAction(ISD::SADDSAT, VT, Legal); 627 setOperationAction(ISD::UADDSAT, VT, Legal); 628 setOperationAction(ISD::SSUBSAT, VT, Legal); 629 setOperationAction(ISD::USUBSAT, VT, Legal); 630 631 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 632 // nodes which truncate by one power of two at a time. 633 setOperationAction(ISD::TRUNCATE, VT, Custom); 634 635 // Custom-lower insert/extract operations to simplify patterns. 636 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 637 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 638 639 // Custom-lower reduction operations to set up the corresponding custom 640 // nodes' operands. 641 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 644 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 645 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 646 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 647 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 648 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 649 650 for (unsigned VPOpc : IntegerVPOps) 651 setOperationAction(VPOpc, VT, Custom); 652 653 setOperationAction(ISD::LOAD, VT, Custom); 654 setOperationAction(ISD::STORE, VT, Custom); 655 656 setOperationAction(ISD::MLOAD, VT, Custom); 657 setOperationAction(ISD::MSTORE, VT, Custom); 658 setOperationAction(ISD::MGATHER, VT, Custom); 659 setOperationAction(ISD::MSCATTER, VT, Custom); 660 661 setOperationAction(ISD::VP_LOAD, VT, Custom); 662 setOperationAction(ISD::VP_STORE, VT, Custom); 663 setOperationAction(ISD::VP_GATHER, VT, Custom); 664 setOperationAction(ISD::VP_SCATTER, VT, Custom); 665 666 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 667 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 668 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 669 670 setOperationAction(ISD::SELECT, VT, Custom); 671 setOperationAction(ISD::SELECT_CC, VT, Expand); 672 673 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 674 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 675 676 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 677 setTruncStoreAction(VT, OtherVT, Expand); 678 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 679 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 680 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 681 } 682 683 // Splice 684 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 685 686 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 687 // type that can represent the value exactly. 688 if (VT.getVectorElementType() != MVT::i64) { 689 MVT FloatEltVT = 690 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 691 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 692 if (isTypeLegal(FloatVT)) { 693 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 694 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 695 } 696 } 697 } 698 699 // Expand various CCs to best match the RVV ISA, which natively supports UNE 700 // but no other unordered comparisons, and supports all ordered comparisons 701 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 702 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 703 // and we pattern-match those back to the "original", swapping operands once 704 // more. This way we catch both operations and both "vf" and "fv" forms with 705 // fewer patterns. 706 static const ISD::CondCode VFPCCToExpand[] = { 707 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 708 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 709 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 710 }; 711 712 // Sets common operation actions on RVV floating-point vector types. 713 const auto SetCommonVFPActions = [&](MVT VT) { 714 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 715 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 716 // sizes are within one power-of-two of each other. Therefore conversions 717 // between vXf16 and vXf64 must be lowered as sequences which convert via 718 // vXf32. 719 setOperationAction(ISD::FP_ROUND, VT, Custom); 720 setOperationAction(ISD::FP_EXTEND, VT, Custom); 721 // Custom-lower insert/extract operations to simplify patterns. 722 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 724 // Expand various condition codes (explained above). 725 for (auto CC : VFPCCToExpand) 726 setCondCodeAction(CC, VT, Expand); 727 728 setOperationAction(ISD::FMINNUM, VT, Legal); 729 setOperationAction(ISD::FMAXNUM, VT, Legal); 730 731 setOperationAction(ISD::FTRUNC, VT, Custom); 732 setOperationAction(ISD::FCEIL, VT, Custom); 733 setOperationAction(ISD::FFLOOR, VT, Custom); 734 setOperationAction(ISD::FROUND, VT, Custom); 735 736 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 737 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 738 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 739 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 740 741 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 742 743 setOperationAction(ISD::LOAD, VT, Custom); 744 setOperationAction(ISD::STORE, VT, Custom); 745 746 setOperationAction(ISD::MLOAD, VT, Custom); 747 setOperationAction(ISD::MSTORE, VT, Custom); 748 setOperationAction(ISD::MGATHER, VT, Custom); 749 setOperationAction(ISD::MSCATTER, VT, Custom); 750 751 setOperationAction(ISD::VP_LOAD, VT, Custom); 752 setOperationAction(ISD::VP_STORE, VT, Custom); 753 setOperationAction(ISD::VP_GATHER, VT, Custom); 754 setOperationAction(ISD::VP_SCATTER, VT, Custom); 755 756 setOperationAction(ISD::SELECT, VT, Custom); 757 setOperationAction(ISD::SELECT_CC, VT, Expand); 758 759 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 760 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 761 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 762 763 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 764 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 765 766 for (unsigned VPOpc : FloatingPointVPOps) 767 setOperationAction(VPOpc, VT, Custom); 768 }; 769 770 // Sets common extload/truncstore actions on RVV floating-point vector 771 // types. 772 const auto SetCommonVFPExtLoadTruncStoreActions = 773 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 774 for (auto SmallVT : SmallerVTs) { 775 setTruncStoreAction(VT, SmallVT, Expand); 776 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 777 } 778 }; 779 780 if (Subtarget.hasVInstructionsF16()) 781 for (MVT VT : F16VecVTs) 782 SetCommonVFPActions(VT); 783 784 for (MVT VT : F32VecVTs) { 785 if (Subtarget.hasVInstructionsF32()) 786 SetCommonVFPActions(VT); 787 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 788 } 789 790 for (MVT VT : F64VecVTs) { 791 if (Subtarget.hasVInstructionsF64()) 792 SetCommonVFPActions(VT); 793 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 794 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 795 } 796 797 if (Subtarget.useRVVForFixedLengthVectors()) { 798 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 799 if (!useRVVForFixedLengthVectorVT(VT)) 800 continue; 801 802 // By default everything must be expanded. 803 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 804 setOperationAction(Op, VT, Expand); 805 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 806 setTruncStoreAction(VT, OtherVT, Expand); 807 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 808 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 809 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 810 } 811 812 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 813 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 814 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 815 816 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 817 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 818 819 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 821 822 setOperationAction(ISD::LOAD, VT, Custom); 823 setOperationAction(ISD::STORE, VT, Custom); 824 825 setOperationAction(ISD::SETCC, VT, Custom); 826 827 setOperationAction(ISD::SELECT, VT, Custom); 828 829 setOperationAction(ISD::TRUNCATE, VT, Custom); 830 831 setOperationAction(ISD::BITCAST, VT, Custom); 832 833 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 834 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 835 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 836 837 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 838 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 839 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 840 841 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 842 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 843 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 844 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 845 846 // Operations below are different for between masks and other vectors. 847 if (VT.getVectorElementType() == MVT::i1) { 848 setOperationAction(ISD::VP_AND, VT, Custom); 849 setOperationAction(ISD::VP_OR, VT, Custom); 850 setOperationAction(ISD::VP_XOR, VT, Custom); 851 setOperationAction(ISD::AND, VT, Custom); 852 setOperationAction(ISD::OR, VT, Custom); 853 setOperationAction(ISD::XOR, VT, Custom); 854 855 setOperationAction(ISD::VP_FPTOSI, VT, Custom); 856 setOperationAction(ISD::VP_FPTOUI, VT, Custom); 857 continue; 858 } 859 860 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 861 // it before type legalization for i64 vectors on RV32. It will then be 862 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 863 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 864 // improvements first. 865 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 866 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 867 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 868 } 869 870 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 871 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 872 873 setOperationAction(ISD::MLOAD, VT, Custom); 874 setOperationAction(ISD::MSTORE, VT, Custom); 875 setOperationAction(ISD::MGATHER, VT, Custom); 876 setOperationAction(ISD::MSCATTER, VT, Custom); 877 878 setOperationAction(ISD::VP_LOAD, VT, Custom); 879 setOperationAction(ISD::VP_STORE, VT, Custom); 880 setOperationAction(ISD::VP_GATHER, VT, Custom); 881 setOperationAction(ISD::VP_SCATTER, VT, Custom); 882 883 setOperationAction(ISD::ADD, VT, Custom); 884 setOperationAction(ISD::MUL, VT, Custom); 885 setOperationAction(ISD::SUB, VT, Custom); 886 setOperationAction(ISD::AND, VT, Custom); 887 setOperationAction(ISD::OR, VT, Custom); 888 setOperationAction(ISD::XOR, VT, Custom); 889 setOperationAction(ISD::SDIV, VT, Custom); 890 setOperationAction(ISD::SREM, VT, Custom); 891 setOperationAction(ISD::UDIV, VT, Custom); 892 setOperationAction(ISD::UREM, VT, Custom); 893 setOperationAction(ISD::SHL, VT, Custom); 894 setOperationAction(ISD::SRA, VT, Custom); 895 setOperationAction(ISD::SRL, VT, Custom); 896 897 setOperationAction(ISD::SMIN, VT, Custom); 898 setOperationAction(ISD::SMAX, VT, Custom); 899 setOperationAction(ISD::UMIN, VT, Custom); 900 setOperationAction(ISD::UMAX, VT, Custom); 901 setOperationAction(ISD::ABS, VT, Custom); 902 903 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 904 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 905 setOperationAction(ISD::MULHS, VT, Custom); 906 setOperationAction(ISD::MULHU, VT, Custom); 907 } 908 909 setOperationAction(ISD::SADDSAT, VT, Custom); 910 setOperationAction(ISD::UADDSAT, VT, Custom); 911 setOperationAction(ISD::SSUBSAT, VT, Custom); 912 setOperationAction(ISD::USUBSAT, VT, Custom); 913 914 setOperationAction(ISD::VSELECT, VT, Custom); 915 setOperationAction(ISD::SELECT_CC, VT, Expand); 916 917 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 918 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 919 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 920 921 // Custom-lower reduction operations to set up the corresponding custom 922 // nodes' operands. 923 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 924 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 925 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 926 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 927 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 928 929 for (unsigned VPOpc : IntegerVPOps) 930 setOperationAction(VPOpc, VT, Custom); 931 932 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 933 // type that can represent the value exactly. 934 if (VT.getVectorElementType() != MVT::i64) { 935 MVT FloatEltVT = 936 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 937 EVT FloatVT = 938 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 939 if (isTypeLegal(FloatVT)) { 940 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 941 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 942 } 943 } 944 } 945 946 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 947 if (!useRVVForFixedLengthVectorVT(VT)) 948 continue; 949 950 // By default everything must be expanded. 951 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 952 setOperationAction(Op, VT, Expand); 953 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 954 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 955 setTruncStoreAction(VT, OtherVT, Expand); 956 } 957 958 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 959 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 960 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 961 962 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 963 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 964 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 965 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 966 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 967 968 setOperationAction(ISD::LOAD, VT, Custom); 969 setOperationAction(ISD::STORE, VT, Custom); 970 setOperationAction(ISD::MLOAD, VT, Custom); 971 setOperationAction(ISD::MSTORE, VT, Custom); 972 setOperationAction(ISD::MGATHER, VT, Custom); 973 setOperationAction(ISD::MSCATTER, VT, Custom); 974 975 setOperationAction(ISD::VP_LOAD, VT, Custom); 976 setOperationAction(ISD::VP_STORE, VT, Custom); 977 setOperationAction(ISD::VP_GATHER, VT, Custom); 978 setOperationAction(ISD::VP_SCATTER, VT, Custom); 979 980 setOperationAction(ISD::FADD, VT, Custom); 981 setOperationAction(ISD::FSUB, VT, Custom); 982 setOperationAction(ISD::FMUL, VT, Custom); 983 setOperationAction(ISD::FDIV, VT, Custom); 984 setOperationAction(ISD::FNEG, VT, Custom); 985 setOperationAction(ISD::FABS, VT, Custom); 986 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 987 setOperationAction(ISD::FSQRT, VT, Custom); 988 setOperationAction(ISD::FMA, VT, Custom); 989 setOperationAction(ISD::FMINNUM, VT, Custom); 990 setOperationAction(ISD::FMAXNUM, VT, Custom); 991 992 setOperationAction(ISD::FP_ROUND, VT, Custom); 993 setOperationAction(ISD::FP_EXTEND, VT, Custom); 994 995 setOperationAction(ISD::FTRUNC, VT, Custom); 996 setOperationAction(ISD::FCEIL, VT, Custom); 997 setOperationAction(ISD::FFLOOR, VT, Custom); 998 setOperationAction(ISD::FROUND, VT, Custom); 999 1000 for (auto CC : VFPCCToExpand) 1001 setCondCodeAction(CC, VT, Expand); 1002 1003 setOperationAction(ISD::VSELECT, VT, Custom); 1004 setOperationAction(ISD::SELECT, VT, Custom); 1005 setOperationAction(ISD::SELECT_CC, VT, Expand); 1006 1007 setOperationAction(ISD::BITCAST, VT, Custom); 1008 1009 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1010 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1011 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1012 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1013 1014 for (unsigned VPOpc : FloatingPointVPOps) 1015 setOperationAction(VPOpc, VT, Custom); 1016 } 1017 1018 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1019 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1020 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1021 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1022 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1023 if (Subtarget.hasStdExtZfh()) 1024 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1025 if (Subtarget.hasStdExtF()) 1026 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1027 if (Subtarget.hasStdExtD()) 1028 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1029 } 1030 } 1031 1032 // Function alignments. 1033 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1034 setMinFunctionAlignment(FunctionAlignment); 1035 setPrefFunctionAlignment(FunctionAlignment); 1036 1037 setMinimumJumpTableEntries(5); 1038 1039 // Jumps are expensive, compared to logic 1040 setJumpIsExpensive(); 1041 1042 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 1043 ISD::OR, ISD::XOR}); 1044 1045 if (Subtarget.hasStdExtZbp()) 1046 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 1047 if (Subtarget.hasStdExtZbkb()) 1048 setTargetDAGCombine(ISD::BITREVERSE); 1049 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 1050 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1051 if (Subtarget.hasStdExtF()) 1052 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 1053 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 1054 if (Subtarget.hasVInstructions()) 1055 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 1056 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 1057 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 1058 1059 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1060 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1061 } 1062 1063 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1064 LLVMContext &Context, 1065 EVT VT) const { 1066 if (!VT.isVector()) 1067 return getPointerTy(DL); 1068 if (Subtarget.hasVInstructions() && 1069 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1070 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1071 return VT.changeVectorElementTypeToInteger(); 1072 } 1073 1074 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1075 return Subtarget.getXLenVT(); 1076 } 1077 1078 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1079 const CallInst &I, 1080 MachineFunction &MF, 1081 unsigned Intrinsic) const { 1082 auto &DL = I.getModule()->getDataLayout(); 1083 switch (Intrinsic) { 1084 default: 1085 return false; 1086 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1087 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1088 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1089 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1090 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1091 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1092 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1093 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1094 case Intrinsic::riscv_masked_cmpxchg_i32: 1095 Info.opc = ISD::INTRINSIC_W_CHAIN; 1096 Info.memVT = MVT::i32; 1097 Info.ptrVal = I.getArgOperand(0); 1098 Info.offset = 0; 1099 Info.align = Align(4); 1100 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1101 MachineMemOperand::MOVolatile; 1102 return true; 1103 case Intrinsic::riscv_masked_strided_load: 1104 Info.opc = ISD::INTRINSIC_W_CHAIN; 1105 Info.ptrVal = I.getArgOperand(1); 1106 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1107 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1108 Info.size = MemoryLocation::UnknownSize; 1109 Info.flags |= MachineMemOperand::MOLoad; 1110 return true; 1111 case Intrinsic::riscv_masked_strided_store: 1112 Info.opc = ISD::INTRINSIC_VOID; 1113 Info.ptrVal = I.getArgOperand(1); 1114 Info.memVT = 1115 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1116 Info.align = Align( 1117 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1118 8); 1119 Info.size = MemoryLocation::UnknownSize; 1120 Info.flags |= MachineMemOperand::MOStore; 1121 return true; 1122 case Intrinsic::riscv_seg2_load: 1123 case Intrinsic::riscv_seg3_load: 1124 case Intrinsic::riscv_seg4_load: 1125 case Intrinsic::riscv_seg5_load: 1126 case Intrinsic::riscv_seg6_load: 1127 case Intrinsic::riscv_seg7_load: 1128 case Intrinsic::riscv_seg8_load: 1129 Info.opc = ISD::INTRINSIC_W_CHAIN; 1130 Info.ptrVal = I.getArgOperand(0); 1131 Info.memVT = 1132 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1133 Info.align = 1134 Align(DL.getTypeSizeInBits( 1135 I.getType()->getStructElementType(0)->getScalarType()) / 1136 8); 1137 Info.size = MemoryLocation::UnknownSize; 1138 Info.flags |= MachineMemOperand::MOLoad; 1139 return true; 1140 } 1141 } 1142 1143 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1144 const AddrMode &AM, Type *Ty, 1145 unsigned AS, 1146 Instruction *I) const { 1147 // No global is ever allowed as a base. 1148 if (AM.BaseGV) 1149 return false; 1150 1151 // Require a 12-bit signed offset. 1152 if (!isInt<12>(AM.BaseOffs)) 1153 return false; 1154 1155 switch (AM.Scale) { 1156 case 0: // "r+i" or just "i", depending on HasBaseReg. 1157 break; 1158 case 1: 1159 if (!AM.HasBaseReg) // allow "r+i". 1160 break; 1161 return false; // disallow "r+r" or "r+r+i". 1162 default: 1163 return false; 1164 } 1165 1166 return true; 1167 } 1168 1169 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1170 return isInt<12>(Imm); 1171 } 1172 1173 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1174 return isInt<12>(Imm); 1175 } 1176 1177 // On RV32, 64-bit integers are split into their high and low parts and held 1178 // in two different registers, so the trunc is free since the low register can 1179 // just be used. 1180 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1181 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1182 return false; 1183 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1184 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1185 return (SrcBits == 64 && DestBits == 32); 1186 } 1187 1188 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1189 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1190 !SrcVT.isInteger() || !DstVT.isInteger()) 1191 return false; 1192 unsigned SrcBits = SrcVT.getSizeInBits(); 1193 unsigned DestBits = DstVT.getSizeInBits(); 1194 return (SrcBits == 64 && DestBits == 32); 1195 } 1196 1197 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1198 // Zexts are free if they can be combined with a load. 1199 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1200 // poorly with type legalization of compares preferring sext. 1201 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1202 EVT MemVT = LD->getMemoryVT(); 1203 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1204 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1205 LD->getExtensionType() == ISD::ZEXTLOAD)) 1206 return true; 1207 } 1208 1209 return TargetLowering::isZExtFree(Val, VT2); 1210 } 1211 1212 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1213 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1214 } 1215 1216 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1217 return Subtarget.hasStdExtZbb(); 1218 } 1219 1220 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1221 return Subtarget.hasStdExtZbb(); 1222 } 1223 1224 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1225 EVT VT = Y.getValueType(); 1226 1227 // FIXME: Support vectors once we have tests. 1228 if (VT.isVector()) 1229 return false; 1230 1231 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1232 Subtarget.hasStdExtZbkb()) && 1233 !isa<ConstantSDNode>(Y); 1234 } 1235 1236 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1237 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1238 auto *C = dyn_cast<ConstantSDNode>(Y); 1239 return C && C->getAPIntValue().ule(10); 1240 } 1241 1242 /// Check if sinking \p I's operands to I's basic block is profitable, because 1243 /// the operands can be folded into a target instruction, e.g. 1244 /// splats of scalars can fold into vector instructions. 1245 bool RISCVTargetLowering::shouldSinkOperands( 1246 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1247 using namespace llvm::PatternMatch; 1248 1249 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1250 return false; 1251 1252 auto IsSinker = [&](Instruction *I, int Operand) { 1253 switch (I->getOpcode()) { 1254 case Instruction::Add: 1255 case Instruction::Sub: 1256 case Instruction::Mul: 1257 case Instruction::And: 1258 case Instruction::Or: 1259 case Instruction::Xor: 1260 case Instruction::FAdd: 1261 case Instruction::FSub: 1262 case Instruction::FMul: 1263 case Instruction::FDiv: 1264 case Instruction::ICmp: 1265 case Instruction::FCmp: 1266 return true; 1267 case Instruction::Shl: 1268 case Instruction::LShr: 1269 case Instruction::AShr: 1270 case Instruction::UDiv: 1271 case Instruction::SDiv: 1272 case Instruction::URem: 1273 case Instruction::SRem: 1274 return Operand == 1; 1275 case Instruction::Call: 1276 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1277 switch (II->getIntrinsicID()) { 1278 case Intrinsic::fma: 1279 case Intrinsic::vp_fma: 1280 return Operand == 0 || Operand == 1; 1281 // FIXME: Our patterns can only match vx/vf instructions when the splat 1282 // it on the RHS, because TableGen doesn't recognize our VP operations 1283 // as commutative. 1284 case Intrinsic::vp_add: 1285 case Intrinsic::vp_mul: 1286 case Intrinsic::vp_and: 1287 case Intrinsic::vp_or: 1288 case Intrinsic::vp_xor: 1289 case Intrinsic::vp_fadd: 1290 case Intrinsic::vp_fmul: 1291 case Intrinsic::vp_shl: 1292 case Intrinsic::vp_lshr: 1293 case Intrinsic::vp_ashr: 1294 case Intrinsic::vp_udiv: 1295 case Intrinsic::vp_sdiv: 1296 case Intrinsic::vp_urem: 1297 case Intrinsic::vp_srem: 1298 return Operand == 1; 1299 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1300 // explicit patterns for both LHS and RHS (as 'vr' versions). 1301 case Intrinsic::vp_sub: 1302 case Intrinsic::vp_fsub: 1303 case Intrinsic::vp_fdiv: 1304 return Operand == 0 || Operand == 1; 1305 default: 1306 return false; 1307 } 1308 } 1309 return false; 1310 default: 1311 return false; 1312 } 1313 }; 1314 1315 for (auto OpIdx : enumerate(I->operands())) { 1316 if (!IsSinker(I, OpIdx.index())) 1317 continue; 1318 1319 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1320 // Make sure we are not already sinking this operand 1321 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1322 continue; 1323 1324 // We are looking for a splat that can be sunk. 1325 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1326 m_Undef(), m_ZeroMask()))) 1327 continue; 1328 1329 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1330 // and vector registers 1331 for (Use &U : Op->uses()) { 1332 Instruction *Insn = cast<Instruction>(U.getUser()); 1333 if (!IsSinker(Insn, U.getOperandNo())) 1334 return false; 1335 } 1336 1337 Ops.push_back(&Op->getOperandUse(0)); 1338 Ops.push_back(&OpIdx.value()); 1339 } 1340 return true; 1341 } 1342 1343 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1344 bool ForCodeSize) const { 1345 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1346 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1347 return false; 1348 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1349 return false; 1350 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1351 return false; 1352 return Imm.isZero(); 1353 } 1354 1355 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1356 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1357 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1358 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1359 } 1360 1361 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1362 CallingConv::ID CC, 1363 EVT VT) const { 1364 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1365 // We might still end up using a GPR but that will be decided based on ABI. 1366 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1367 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1368 return MVT::f32; 1369 1370 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1371 } 1372 1373 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1374 CallingConv::ID CC, 1375 EVT VT) const { 1376 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1377 // We might still end up using a GPR but that will be decided based on ABI. 1378 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1379 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1380 return 1; 1381 1382 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1383 } 1384 1385 // Changes the condition code and swaps operands if necessary, so the SetCC 1386 // operation matches one of the comparisons supported directly by branches 1387 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1388 // with 1/-1. 1389 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1390 ISD::CondCode &CC, SelectionDAG &DAG) { 1391 // Convert X > -1 to X >= 0. 1392 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1393 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1394 CC = ISD::SETGE; 1395 return; 1396 } 1397 // Convert X < 1 to 0 >= X. 1398 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1399 RHS = LHS; 1400 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1401 CC = ISD::SETGE; 1402 return; 1403 } 1404 1405 switch (CC) { 1406 default: 1407 break; 1408 case ISD::SETGT: 1409 case ISD::SETLE: 1410 case ISD::SETUGT: 1411 case ISD::SETULE: 1412 CC = ISD::getSetCCSwappedOperands(CC); 1413 std::swap(LHS, RHS); 1414 break; 1415 } 1416 } 1417 1418 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1419 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1420 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1421 if (VT.getVectorElementType() == MVT::i1) 1422 KnownSize *= 8; 1423 1424 switch (KnownSize) { 1425 default: 1426 llvm_unreachable("Invalid LMUL."); 1427 case 8: 1428 return RISCVII::VLMUL::LMUL_F8; 1429 case 16: 1430 return RISCVII::VLMUL::LMUL_F4; 1431 case 32: 1432 return RISCVII::VLMUL::LMUL_F2; 1433 case 64: 1434 return RISCVII::VLMUL::LMUL_1; 1435 case 128: 1436 return RISCVII::VLMUL::LMUL_2; 1437 case 256: 1438 return RISCVII::VLMUL::LMUL_4; 1439 case 512: 1440 return RISCVII::VLMUL::LMUL_8; 1441 } 1442 } 1443 1444 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1445 switch (LMul) { 1446 default: 1447 llvm_unreachable("Invalid LMUL."); 1448 case RISCVII::VLMUL::LMUL_F8: 1449 case RISCVII::VLMUL::LMUL_F4: 1450 case RISCVII::VLMUL::LMUL_F2: 1451 case RISCVII::VLMUL::LMUL_1: 1452 return RISCV::VRRegClassID; 1453 case RISCVII::VLMUL::LMUL_2: 1454 return RISCV::VRM2RegClassID; 1455 case RISCVII::VLMUL::LMUL_4: 1456 return RISCV::VRM4RegClassID; 1457 case RISCVII::VLMUL::LMUL_8: 1458 return RISCV::VRM8RegClassID; 1459 } 1460 } 1461 1462 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1463 RISCVII::VLMUL LMUL = getLMUL(VT); 1464 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1465 LMUL == RISCVII::VLMUL::LMUL_F4 || 1466 LMUL == RISCVII::VLMUL::LMUL_F2 || 1467 LMUL == RISCVII::VLMUL::LMUL_1) { 1468 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1469 "Unexpected subreg numbering"); 1470 return RISCV::sub_vrm1_0 + Index; 1471 } 1472 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1473 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1474 "Unexpected subreg numbering"); 1475 return RISCV::sub_vrm2_0 + Index; 1476 } 1477 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1478 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1479 "Unexpected subreg numbering"); 1480 return RISCV::sub_vrm4_0 + Index; 1481 } 1482 llvm_unreachable("Invalid vector type."); 1483 } 1484 1485 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1486 if (VT.getVectorElementType() == MVT::i1) 1487 return RISCV::VRRegClassID; 1488 return getRegClassIDForLMUL(getLMUL(VT)); 1489 } 1490 1491 // Attempt to decompose a subvector insert/extract between VecVT and 1492 // SubVecVT via subregister indices. Returns the subregister index that 1493 // can perform the subvector insert/extract with the given element index, as 1494 // well as the index corresponding to any leftover subvectors that must be 1495 // further inserted/extracted within the register class for SubVecVT. 1496 std::pair<unsigned, unsigned> 1497 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1498 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1499 const RISCVRegisterInfo *TRI) { 1500 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1501 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1502 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1503 "Register classes not ordered"); 1504 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1505 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1506 // Try to compose a subregister index that takes us from the incoming 1507 // LMUL>1 register class down to the outgoing one. At each step we half 1508 // the LMUL: 1509 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1510 // Note that this is not guaranteed to find a subregister index, such as 1511 // when we are extracting from one VR type to another. 1512 unsigned SubRegIdx = RISCV::NoSubRegister; 1513 for (const unsigned RCID : 1514 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1515 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1516 VecVT = VecVT.getHalfNumVectorElementsVT(); 1517 bool IsHi = 1518 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1519 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1520 getSubregIndexByMVT(VecVT, IsHi)); 1521 if (IsHi) 1522 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1523 } 1524 return {SubRegIdx, InsertExtractIdx}; 1525 } 1526 1527 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1528 // stores for those types. 1529 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1530 return !Subtarget.useRVVForFixedLengthVectors() || 1531 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1532 } 1533 1534 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1535 if (ScalarTy->isPointerTy()) 1536 return true; 1537 1538 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1539 ScalarTy->isIntegerTy(32)) 1540 return true; 1541 1542 if (ScalarTy->isIntegerTy(64)) 1543 return Subtarget.hasVInstructionsI64(); 1544 1545 if (ScalarTy->isHalfTy()) 1546 return Subtarget.hasVInstructionsF16(); 1547 if (ScalarTy->isFloatTy()) 1548 return Subtarget.hasVInstructionsF32(); 1549 if (ScalarTy->isDoubleTy()) 1550 return Subtarget.hasVInstructionsF64(); 1551 1552 return false; 1553 } 1554 1555 static SDValue getVLOperand(SDValue Op) { 1556 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1557 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1558 "Unexpected opcode"); 1559 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1560 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1561 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1562 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1563 if (!II) 1564 return SDValue(); 1565 return Op.getOperand(II->VLOperand + 1 + HasChain); 1566 } 1567 1568 static bool useRVVForFixedLengthVectorVT(MVT VT, 1569 const RISCVSubtarget &Subtarget) { 1570 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1571 if (!Subtarget.useRVVForFixedLengthVectors()) 1572 return false; 1573 1574 // We only support a set of vector types with a consistent maximum fixed size 1575 // across all supported vector element types to avoid legalization issues. 1576 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1577 // fixed-length vector type we support is 1024 bytes. 1578 if (VT.getFixedSizeInBits() > 1024 * 8) 1579 return false; 1580 1581 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1582 1583 MVT EltVT = VT.getVectorElementType(); 1584 1585 // Don't use RVV for vectors we cannot scalarize if required. 1586 switch (EltVT.SimpleTy) { 1587 // i1 is supported but has different rules. 1588 default: 1589 return false; 1590 case MVT::i1: 1591 // Masks can only use a single register. 1592 if (VT.getVectorNumElements() > MinVLen) 1593 return false; 1594 MinVLen /= 8; 1595 break; 1596 case MVT::i8: 1597 case MVT::i16: 1598 case MVT::i32: 1599 break; 1600 case MVT::i64: 1601 if (!Subtarget.hasVInstructionsI64()) 1602 return false; 1603 break; 1604 case MVT::f16: 1605 if (!Subtarget.hasVInstructionsF16()) 1606 return false; 1607 break; 1608 case MVT::f32: 1609 if (!Subtarget.hasVInstructionsF32()) 1610 return false; 1611 break; 1612 case MVT::f64: 1613 if (!Subtarget.hasVInstructionsF64()) 1614 return false; 1615 break; 1616 } 1617 1618 // Reject elements larger than ELEN. 1619 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1620 return false; 1621 1622 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1623 // Don't use RVV for types that don't fit. 1624 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1625 return false; 1626 1627 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1628 // the base fixed length RVV support in place. 1629 if (!VT.isPow2VectorType()) 1630 return false; 1631 1632 return true; 1633 } 1634 1635 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1636 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1637 } 1638 1639 // Return the largest legal scalable vector type that matches VT's element type. 1640 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1641 const RISCVSubtarget &Subtarget) { 1642 // This may be called before legal types are setup. 1643 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1644 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1645 "Expected legal fixed length vector!"); 1646 1647 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1648 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1649 1650 MVT EltVT = VT.getVectorElementType(); 1651 switch (EltVT.SimpleTy) { 1652 default: 1653 llvm_unreachable("unexpected element type for RVV container"); 1654 case MVT::i1: 1655 case MVT::i8: 1656 case MVT::i16: 1657 case MVT::i32: 1658 case MVT::i64: 1659 case MVT::f16: 1660 case MVT::f32: 1661 case MVT::f64: { 1662 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1663 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1664 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1665 unsigned NumElts = 1666 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1667 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1668 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1669 return MVT::getScalableVectorVT(EltVT, NumElts); 1670 } 1671 } 1672 } 1673 1674 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1675 const RISCVSubtarget &Subtarget) { 1676 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1677 Subtarget); 1678 } 1679 1680 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1681 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1682 } 1683 1684 // Grow V to consume an entire RVV register. 1685 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1686 const RISCVSubtarget &Subtarget) { 1687 assert(VT.isScalableVector() && 1688 "Expected to convert into a scalable vector!"); 1689 assert(V.getValueType().isFixedLengthVector() && 1690 "Expected a fixed length vector operand!"); 1691 SDLoc DL(V); 1692 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1693 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1694 } 1695 1696 // Shrink V so it's just big enough to maintain a VT's worth of data. 1697 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1698 const RISCVSubtarget &Subtarget) { 1699 assert(VT.isFixedLengthVector() && 1700 "Expected to convert into a fixed length vector!"); 1701 assert(V.getValueType().isScalableVector() && 1702 "Expected a scalable vector operand!"); 1703 SDLoc DL(V); 1704 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1705 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1706 } 1707 1708 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1709 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1710 // the vector type that it is contained in. 1711 static std::pair<SDValue, SDValue> 1712 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1713 const RISCVSubtarget &Subtarget) { 1714 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1715 MVT XLenVT = Subtarget.getXLenVT(); 1716 SDValue VL = VecVT.isFixedLengthVector() 1717 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1718 : DAG.getRegister(RISCV::X0, XLenVT); 1719 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1720 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1721 return {Mask, VL}; 1722 } 1723 1724 // As above but assuming the given type is a scalable vector type. 1725 static std::pair<SDValue, SDValue> 1726 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1727 const RISCVSubtarget &Subtarget) { 1728 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1729 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1730 } 1731 1732 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1733 // of either is (currently) supported. This can get us into an infinite loop 1734 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1735 // as a ..., etc. 1736 // Until either (or both) of these can reliably lower any node, reporting that 1737 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1738 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1739 // which is not desirable. 1740 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1741 EVT VT, unsigned DefinedValues) const { 1742 return false; 1743 } 1744 1745 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1746 const RISCVSubtarget &Subtarget) { 1747 // RISCV FP-to-int conversions saturate to the destination register size, but 1748 // don't produce 0 for nan. We can use a conversion instruction and fix the 1749 // nan case with a compare and a select. 1750 SDValue Src = Op.getOperand(0); 1751 1752 EVT DstVT = Op.getValueType(); 1753 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1754 1755 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1756 unsigned Opc; 1757 if (SatVT == DstVT) 1758 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1759 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1760 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1761 else 1762 return SDValue(); 1763 // FIXME: Support other SatVTs by clamping before or after the conversion. 1764 1765 SDLoc DL(Op); 1766 SDValue FpToInt = DAG.getNode( 1767 Opc, DL, DstVT, Src, 1768 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1769 1770 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1771 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1772 } 1773 1774 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1775 // and back. Taking care to avoid converting values that are nan or already 1776 // correct. 1777 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1778 // have FRM dependencies modeled yet. 1779 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1780 MVT VT = Op.getSimpleValueType(); 1781 assert(VT.isVector() && "Unexpected type"); 1782 1783 SDLoc DL(Op); 1784 1785 // Freeze the source since we are increasing the number of uses. 1786 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1787 1788 // Truncate to integer and convert back to FP. 1789 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1790 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1791 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1792 1793 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1794 1795 if (Op.getOpcode() == ISD::FCEIL) { 1796 // If the truncated value is the greater than or equal to the original 1797 // value, we've computed the ceil. Otherwise, we went the wrong way and 1798 // need to increase by 1. 1799 // FIXME: This should use a masked operation. Handle here or in isel? 1800 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1801 DAG.getConstantFP(1.0, DL, VT)); 1802 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1803 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1804 } else if (Op.getOpcode() == ISD::FFLOOR) { 1805 // If the truncated value is the less than or equal to the original value, 1806 // we've computed the floor. Otherwise, we went the wrong way and need to 1807 // decrease by 1. 1808 // FIXME: This should use a masked operation. Handle here or in isel? 1809 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1810 DAG.getConstantFP(1.0, DL, VT)); 1811 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1812 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1813 } 1814 1815 // Restore the original sign so that -0.0 is preserved. 1816 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1817 1818 // Determine the largest integer that can be represented exactly. This and 1819 // values larger than it don't have any fractional bits so don't need to 1820 // be converted. 1821 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1822 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1823 APFloat MaxVal = APFloat(FltSem); 1824 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1825 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1826 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1827 1828 // If abs(Src) was larger than MaxVal or nan, keep it. 1829 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1830 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1831 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1832 } 1833 1834 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1835 // This mode isn't supported in vector hardware on RISCV. But as long as we 1836 // aren't compiling with trapping math, we can emulate this with 1837 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1838 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1839 // dependencies modeled yet. 1840 // FIXME: Use masked operations to avoid final merge. 1841 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1842 MVT VT = Op.getSimpleValueType(); 1843 assert(VT.isVector() && "Unexpected type"); 1844 1845 SDLoc DL(Op); 1846 1847 // Freeze the source since we are increasing the number of uses. 1848 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1849 1850 // We do the conversion on the absolute value and fix the sign at the end. 1851 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1852 1853 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1854 bool Ignored; 1855 APFloat Point5Pred = APFloat(0.5f); 1856 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1857 Point5Pred.next(/*nextDown*/ true); 1858 1859 // Add the adjustment. 1860 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1861 DAG.getConstantFP(Point5Pred, DL, VT)); 1862 1863 // Truncate to integer and convert back to fp. 1864 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1865 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1866 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1867 1868 // Restore the original sign. 1869 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1870 1871 // Determine the largest integer that can be represented exactly. This and 1872 // values larger than it don't have any fractional bits so don't need to 1873 // be converted. 1874 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1875 APFloat MaxVal = APFloat(FltSem); 1876 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1877 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1878 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1879 1880 // If abs(Src) was larger than MaxVal or nan, keep it. 1881 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1882 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1883 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1884 } 1885 1886 struct VIDSequence { 1887 int64_t StepNumerator; 1888 unsigned StepDenominator; 1889 int64_t Addend; 1890 }; 1891 1892 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1893 // to the (non-zero) step S and start value X. This can be then lowered as the 1894 // RVV sequence (VID * S) + X, for example. 1895 // The step S is represented as an integer numerator divided by a positive 1896 // denominator. Note that the implementation currently only identifies 1897 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1898 // cannot detect 2/3, for example. 1899 // Note that this method will also match potentially unappealing index 1900 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1901 // determine whether this is worth generating code for. 1902 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1903 unsigned NumElts = Op.getNumOperands(); 1904 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1905 if (!Op.getValueType().isInteger()) 1906 return None; 1907 1908 Optional<unsigned> SeqStepDenom; 1909 Optional<int64_t> SeqStepNum, SeqAddend; 1910 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1911 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1912 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1913 // Assume undef elements match the sequence; we just have to be careful 1914 // when interpolating across them. 1915 if (Op.getOperand(Idx).isUndef()) 1916 continue; 1917 // The BUILD_VECTOR must be all constants. 1918 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1919 return None; 1920 1921 uint64_t Val = Op.getConstantOperandVal(Idx) & 1922 maskTrailingOnes<uint64_t>(EltSizeInBits); 1923 1924 if (PrevElt) { 1925 // Calculate the step since the last non-undef element, and ensure 1926 // it's consistent across the entire sequence. 1927 unsigned IdxDiff = Idx - PrevElt->second; 1928 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1929 1930 // A zero-value value difference means that we're somewhere in the middle 1931 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1932 // step change before evaluating the sequence. 1933 if (ValDiff != 0) { 1934 int64_t Remainder = ValDiff % IdxDiff; 1935 // Normalize the step if it's greater than 1. 1936 if (Remainder != ValDiff) { 1937 // The difference must cleanly divide the element span. 1938 if (Remainder != 0) 1939 return None; 1940 ValDiff /= IdxDiff; 1941 IdxDiff = 1; 1942 } 1943 1944 if (!SeqStepNum) 1945 SeqStepNum = ValDiff; 1946 else if (ValDiff != SeqStepNum) 1947 return None; 1948 1949 if (!SeqStepDenom) 1950 SeqStepDenom = IdxDiff; 1951 else if (IdxDiff != *SeqStepDenom) 1952 return None; 1953 } 1954 } 1955 1956 // Record and/or check any addend. 1957 if (SeqStepNum && SeqStepDenom) { 1958 uint64_t ExpectedVal = 1959 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1960 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1961 if (!SeqAddend) 1962 SeqAddend = Addend; 1963 else if (SeqAddend != Addend) 1964 return None; 1965 } 1966 1967 // Record this non-undef element for later. 1968 if (!PrevElt || PrevElt->first != Val) 1969 PrevElt = std::make_pair(Val, Idx); 1970 } 1971 // We need to have logged both a step and an addend for this to count as 1972 // a legal index sequence. 1973 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1974 return None; 1975 1976 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1977 } 1978 1979 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1980 // and lower it as a VRGATHER_VX_VL from the source vector. 1981 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1982 SelectionDAG &DAG, 1983 const RISCVSubtarget &Subtarget) { 1984 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1985 return SDValue(); 1986 SDValue Vec = SplatVal.getOperand(0); 1987 // Only perform this optimization on vectors of the same size for simplicity. 1988 if (Vec.getValueType() != VT) 1989 return SDValue(); 1990 SDValue Idx = SplatVal.getOperand(1); 1991 // The index must be a legal type. 1992 if (Idx.getValueType() != Subtarget.getXLenVT()) 1993 return SDValue(); 1994 1995 MVT ContainerVT = VT; 1996 if (VT.isFixedLengthVector()) { 1997 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1998 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1999 } 2000 2001 SDValue Mask, VL; 2002 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2003 2004 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2005 Idx, Mask, VL); 2006 2007 if (!VT.isFixedLengthVector()) 2008 return Gather; 2009 2010 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2011 } 2012 2013 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2014 const RISCVSubtarget &Subtarget) { 2015 MVT VT = Op.getSimpleValueType(); 2016 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2017 2018 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2019 2020 SDLoc DL(Op); 2021 SDValue Mask, VL; 2022 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2023 2024 MVT XLenVT = Subtarget.getXLenVT(); 2025 unsigned NumElts = Op.getNumOperands(); 2026 2027 if (VT.getVectorElementType() == MVT::i1) { 2028 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2029 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2030 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2031 } 2032 2033 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2034 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2035 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2036 } 2037 2038 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2039 // scalar integer chunks whose bit-width depends on the number of mask 2040 // bits and XLEN. 2041 // First, determine the most appropriate scalar integer type to use. This 2042 // is at most XLenVT, but may be shrunk to a smaller vector element type 2043 // according to the size of the final vector - use i8 chunks rather than 2044 // XLenVT if we're producing a v8i1. This results in more consistent 2045 // codegen across RV32 and RV64. 2046 unsigned NumViaIntegerBits = 2047 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2048 NumViaIntegerBits = std::min(NumViaIntegerBits, 2049 Subtarget.getMaxELENForFixedLengthVectors()); 2050 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2051 // If we have to use more than one INSERT_VECTOR_ELT then this 2052 // optimization is likely to increase code size; avoid peforming it in 2053 // such a case. We can use a load from a constant pool in this case. 2054 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2055 return SDValue(); 2056 // Now we can create our integer vector type. Note that it may be larger 2057 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2058 MVT IntegerViaVecVT = 2059 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2060 divideCeil(NumElts, NumViaIntegerBits)); 2061 2062 uint64_t Bits = 0; 2063 unsigned BitPos = 0, IntegerEltIdx = 0; 2064 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2065 2066 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2067 // Once we accumulate enough bits to fill our scalar type, insert into 2068 // our vector and clear our accumulated data. 2069 if (I != 0 && I % NumViaIntegerBits == 0) { 2070 if (NumViaIntegerBits <= 32) 2071 Bits = SignExtend64(Bits, 32); 2072 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2073 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2074 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2075 Bits = 0; 2076 BitPos = 0; 2077 IntegerEltIdx++; 2078 } 2079 SDValue V = Op.getOperand(I); 2080 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2081 Bits |= ((uint64_t)BitValue << BitPos); 2082 } 2083 2084 // Insert the (remaining) scalar value into position in our integer 2085 // vector type. 2086 if (NumViaIntegerBits <= 32) 2087 Bits = SignExtend64(Bits, 32); 2088 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2089 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2090 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2091 2092 if (NumElts < NumViaIntegerBits) { 2093 // If we're producing a smaller vector than our minimum legal integer 2094 // type, bitcast to the equivalent (known-legal) mask type, and extract 2095 // our final mask. 2096 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2097 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2098 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2099 DAG.getConstant(0, DL, XLenVT)); 2100 } else { 2101 // Else we must have produced an integer type with the same size as the 2102 // mask type; bitcast for the final result. 2103 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2104 Vec = DAG.getBitcast(VT, Vec); 2105 } 2106 2107 return Vec; 2108 } 2109 2110 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2111 // vector type, we have a legal equivalently-sized i8 type, so we can use 2112 // that. 2113 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2114 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2115 2116 SDValue WideVec; 2117 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2118 // For a splat, perform a scalar truncate before creating the wider 2119 // vector. 2120 assert(Splat.getValueType() == XLenVT && 2121 "Unexpected type for i1 splat value"); 2122 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2123 DAG.getConstant(1, DL, XLenVT)); 2124 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2125 } else { 2126 SmallVector<SDValue, 8> Ops(Op->op_values()); 2127 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2128 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2129 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2130 } 2131 2132 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2133 } 2134 2135 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2136 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2137 return Gather; 2138 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2139 : RISCVISD::VMV_V_X_VL; 2140 Splat = 2141 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2142 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2143 } 2144 2145 // Try and match index sequences, which we can lower to the vid instruction 2146 // with optional modifications. An all-undef vector is matched by 2147 // getSplatValue, above. 2148 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2149 int64_t StepNumerator = SimpleVID->StepNumerator; 2150 unsigned StepDenominator = SimpleVID->StepDenominator; 2151 int64_t Addend = SimpleVID->Addend; 2152 2153 assert(StepNumerator != 0 && "Invalid step"); 2154 bool Negate = false; 2155 int64_t SplatStepVal = StepNumerator; 2156 unsigned StepOpcode = ISD::MUL; 2157 if (StepNumerator != 1) { 2158 if (isPowerOf2_64(std::abs(StepNumerator))) { 2159 Negate = StepNumerator < 0; 2160 StepOpcode = ISD::SHL; 2161 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2162 } 2163 } 2164 2165 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2166 // threshold since it's the immediate value many RVV instructions accept. 2167 // There is no vmul.vi instruction so ensure multiply constant can fit in 2168 // a single addi instruction. 2169 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2170 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2171 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2172 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2173 // Convert right out of the scalable type so we can use standard ISD 2174 // nodes for the rest of the computation. If we used scalable types with 2175 // these, we'd lose the fixed-length vector info and generate worse 2176 // vsetvli code. 2177 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2178 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2179 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2180 SDValue SplatStep = DAG.getSplatBuildVector( 2181 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2182 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2183 } 2184 if (StepDenominator != 1) { 2185 SDValue SplatStep = DAG.getSplatBuildVector( 2186 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2187 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2188 } 2189 if (Addend != 0 || Negate) { 2190 SDValue SplatAddend = DAG.getSplatBuildVector( 2191 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2192 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2193 } 2194 return VID; 2195 } 2196 } 2197 2198 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2199 // when re-interpreted as a vector with a larger element type. For example, 2200 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2201 // could be instead splat as 2202 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2203 // TODO: This optimization could also work on non-constant splats, but it 2204 // would require bit-manipulation instructions to construct the splat value. 2205 SmallVector<SDValue> Sequence; 2206 unsigned EltBitSize = VT.getScalarSizeInBits(); 2207 const auto *BV = cast<BuildVectorSDNode>(Op); 2208 if (VT.isInteger() && EltBitSize < 64 && 2209 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2210 BV->getRepeatedSequence(Sequence) && 2211 (Sequence.size() * EltBitSize) <= 64) { 2212 unsigned SeqLen = Sequence.size(); 2213 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2214 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2215 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2216 ViaIntVT == MVT::i64) && 2217 "Unexpected sequence type"); 2218 2219 unsigned EltIdx = 0; 2220 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2221 uint64_t SplatValue = 0; 2222 // Construct the amalgamated value which can be splatted as this larger 2223 // vector type. 2224 for (const auto &SeqV : Sequence) { 2225 if (!SeqV.isUndef()) 2226 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2227 << (EltIdx * EltBitSize)); 2228 EltIdx++; 2229 } 2230 2231 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2232 // achieve better constant materializion. 2233 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2234 SplatValue = SignExtend64(SplatValue, 32); 2235 2236 // Since we can't introduce illegal i64 types at this stage, we can only 2237 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2238 // way we can use RVV instructions to splat. 2239 assert((ViaIntVT.bitsLE(XLenVT) || 2240 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2241 "Unexpected bitcast sequence"); 2242 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2243 SDValue ViaVL = 2244 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2245 MVT ViaContainerVT = 2246 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2247 SDValue Splat = 2248 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2249 DAG.getUNDEF(ViaContainerVT), 2250 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2251 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2252 return DAG.getBitcast(VT, Splat); 2253 } 2254 } 2255 2256 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2257 // which constitute a large proportion of the elements. In such cases we can 2258 // splat a vector with the dominant element and make up the shortfall with 2259 // INSERT_VECTOR_ELTs. 2260 // Note that this includes vectors of 2 elements by association. The 2261 // upper-most element is the "dominant" one, allowing us to use a splat to 2262 // "insert" the upper element, and an insert of the lower element at position 2263 // 0, which improves codegen. 2264 SDValue DominantValue; 2265 unsigned MostCommonCount = 0; 2266 DenseMap<SDValue, unsigned> ValueCounts; 2267 unsigned NumUndefElts = 2268 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2269 2270 // Track the number of scalar loads we know we'd be inserting, estimated as 2271 // any non-zero floating-point constant. Other kinds of element are either 2272 // already in registers or are materialized on demand. The threshold at which 2273 // a vector load is more desirable than several scalar materializion and 2274 // vector-insertion instructions is not known. 2275 unsigned NumScalarLoads = 0; 2276 2277 for (SDValue V : Op->op_values()) { 2278 if (V.isUndef()) 2279 continue; 2280 2281 ValueCounts.insert(std::make_pair(V, 0)); 2282 unsigned &Count = ValueCounts[V]; 2283 2284 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2285 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2286 2287 // Is this value dominant? In case of a tie, prefer the highest element as 2288 // it's cheaper to insert near the beginning of a vector than it is at the 2289 // end. 2290 if (++Count >= MostCommonCount) { 2291 DominantValue = V; 2292 MostCommonCount = Count; 2293 } 2294 } 2295 2296 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2297 unsigned NumDefElts = NumElts - NumUndefElts; 2298 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2299 2300 // Don't perform this optimization when optimizing for size, since 2301 // materializing elements and inserting them tends to cause code bloat. 2302 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2303 ((MostCommonCount > DominantValueCountThreshold) || 2304 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2305 // Start by splatting the most common element. 2306 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2307 2308 DenseSet<SDValue> Processed{DominantValue}; 2309 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2310 for (const auto &OpIdx : enumerate(Op->ops())) { 2311 const SDValue &V = OpIdx.value(); 2312 if (V.isUndef() || !Processed.insert(V).second) 2313 continue; 2314 if (ValueCounts[V] == 1) { 2315 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2316 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2317 } else { 2318 // Blend in all instances of this value using a VSELECT, using a 2319 // mask where each bit signals whether that element is the one 2320 // we're after. 2321 SmallVector<SDValue> Ops; 2322 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2323 return DAG.getConstant(V == V1, DL, XLenVT); 2324 }); 2325 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2326 DAG.getBuildVector(SelMaskTy, DL, Ops), 2327 DAG.getSplatBuildVector(VT, DL, V), Vec); 2328 } 2329 } 2330 2331 return Vec; 2332 } 2333 2334 return SDValue(); 2335 } 2336 2337 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2338 SDValue Lo, SDValue Hi, SDValue VL, 2339 SelectionDAG &DAG) { 2340 if (!Passthru) 2341 Passthru = DAG.getUNDEF(VT); 2342 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2343 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2344 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2345 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2346 // node in order to try and match RVV vector/scalar instructions. 2347 if ((LoC >> 31) == HiC) 2348 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2349 2350 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2351 // vmv.v.x whose EEW = 32 to lower it. 2352 auto *Const = dyn_cast<ConstantSDNode>(VL); 2353 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2354 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2355 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2356 // access the subtarget here now. 2357 auto InterVec = DAG.getNode( 2358 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2359 DAG.getRegister(RISCV::X0, MVT::i32)); 2360 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2361 } 2362 } 2363 2364 // Fall back to a stack store and stride x0 vector load. 2365 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2366 Hi, VL); 2367 } 2368 2369 // Called by type legalization to handle splat of i64 on RV32. 2370 // FIXME: We can optimize this when the type has sign or zero bits in one 2371 // of the halves. 2372 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2373 SDValue Scalar, SDValue VL, 2374 SelectionDAG &DAG) { 2375 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2376 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2377 DAG.getConstant(0, DL, MVT::i32)); 2378 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2379 DAG.getConstant(1, DL, MVT::i32)); 2380 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2381 } 2382 2383 // This function lowers a splat of a scalar operand Splat with the vector 2384 // length VL. It ensures the final sequence is type legal, which is useful when 2385 // lowering a splat after type legalization. 2386 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2387 MVT VT, SDLoc DL, SelectionDAG &DAG, 2388 const RISCVSubtarget &Subtarget) { 2389 bool HasPassthru = Passthru && !Passthru.isUndef(); 2390 if (!HasPassthru && !Passthru) 2391 Passthru = DAG.getUNDEF(VT); 2392 if (VT.isFloatingPoint()) { 2393 // If VL is 1, we could use vfmv.s.f. 2394 if (isOneConstant(VL)) 2395 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2396 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2397 } 2398 2399 MVT XLenVT = Subtarget.getXLenVT(); 2400 2401 // Simplest case is that the operand needs to be promoted to XLenVT. 2402 if (Scalar.getValueType().bitsLE(XLenVT)) { 2403 // If the operand is a constant, sign extend to increase our chances 2404 // of being able to use a .vi instruction. ANY_EXTEND would become a 2405 // a zero extend and the simm5 check in isel would fail. 2406 // FIXME: Should we ignore the upper bits in isel instead? 2407 unsigned ExtOpc = 2408 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2409 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2410 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2411 // If VL is 1 and the scalar value won't benefit from immediate, we could 2412 // use vmv.s.x. 2413 if (isOneConstant(VL) && 2414 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2415 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2416 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2417 } 2418 2419 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2420 "Unexpected scalar for splat lowering!"); 2421 2422 if (isOneConstant(VL) && isNullConstant(Scalar)) 2423 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2424 DAG.getConstant(0, DL, XLenVT), VL); 2425 2426 // Otherwise use the more complicated splatting algorithm. 2427 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2428 } 2429 2430 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2431 const RISCVSubtarget &Subtarget) { 2432 // We need to be able to widen elements to the next larger integer type. 2433 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2434 return false; 2435 2436 int Size = Mask.size(); 2437 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2438 2439 int Srcs[] = {-1, -1}; 2440 for (int i = 0; i != Size; ++i) { 2441 // Ignore undef elements. 2442 if (Mask[i] < 0) 2443 continue; 2444 2445 // Is this an even or odd element. 2446 int Pol = i % 2; 2447 2448 // Ensure we consistently use the same source for this element polarity. 2449 int Src = Mask[i] / Size; 2450 if (Srcs[Pol] < 0) 2451 Srcs[Pol] = Src; 2452 if (Srcs[Pol] != Src) 2453 return false; 2454 2455 // Make sure the element within the source is appropriate for this element 2456 // in the destination. 2457 int Elt = Mask[i] % Size; 2458 if (Elt != i / 2) 2459 return false; 2460 } 2461 2462 // We need to find a source for each polarity and they can't be the same. 2463 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2464 return false; 2465 2466 // Swap the sources if the second source was in the even polarity. 2467 SwapSources = Srcs[0] > Srcs[1]; 2468 2469 return true; 2470 } 2471 2472 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2473 /// and then extract the original number of elements from the rotated result. 2474 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2475 /// returned rotation amount is for a rotate right, where elements move from 2476 /// higher elements to lower elements. \p LoSrc indicates the first source 2477 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2478 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2479 /// 0 or 1 if a rotation is found. 2480 /// 2481 /// NOTE: We talk about rotate to the right which matches how bit shift and 2482 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2483 /// and the table below write vectors with the lowest elements on the left. 2484 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2485 int Size = Mask.size(); 2486 2487 // We need to detect various ways of spelling a rotation: 2488 // [11, 12, 13, 14, 15, 0, 1, 2] 2489 // [-1, 12, 13, 14, -1, -1, 1, -1] 2490 // [-1, -1, -1, -1, -1, -1, 1, 2] 2491 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2492 // [-1, 4, 5, 6, -1, -1, 9, -1] 2493 // [-1, 4, 5, 6, -1, -1, -1, -1] 2494 int Rotation = 0; 2495 LoSrc = -1; 2496 HiSrc = -1; 2497 for (int i = 0; i != Size; ++i) { 2498 int M = Mask[i]; 2499 if (M < 0) 2500 continue; 2501 2502 // Determine where a rotate vector would have started. 2503 int StartIdx = i - (M % Size); 2504 // The identity rotation isn't interesting, stop. 2505 if (StartIdx == 0) 2506 return -1; 2507 2508 // If we found the tail of a vector the rotation must be the missing 2509 // front. If we found the head of a vector, it must be how much of the 2510 // head. 2511 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2512 2513 if (Rotation == 0) 2514 Rotation = CandidateRotation; 2515 else if (Rotation != CandidateRotation) 2516 // The rotations don't match, so we can't match this mask. 2517 return -1; 2518 2519 // Compute which value this mask is pointing at. 2520 int MaskSrc = M < Size ? 0 : 1; 2521 2522 // Compute which of the two target values this index should be assigned to. 2523 // This reflects whether the high elements are remaining or the low elemnts 2524 // are remaining. 2525 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2526 2527 // Either set up this value if we've not encountered it before, or check 2528 // that it remains consistent. 2529 if (TargetSrc < 0) 2530 TargetSrc = MaskSrc; 2531 else if (TargetSrc != MaskSrc) 2532 // This may be a rotation, but it pulls from the inputs in some 2533 // unsupported interleaving. 2534 return -1; 2535 } 2536 2537 // Check that we successfully analyzed the mask, and normalize the results. 2538 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2539 assert((LoSrc >= 0 || HiSrc >= 0) && 2540 "Failed to find a rotated input vector!"); 2541 2542 return Rotation; 2543 } 2544 2545 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2546 const RISCVSubtarget &Subtarget) { 2547 SDValue V1 = Op.getOperand(0); 2548 SDValue V2 = Op.getOperand(1); 2549 SDLoc DL(Op); 2550 MVT XLenVT = Subtarget.getXLenVT(); 2551 MVT VT = Op.getSimpleValueType(); 2552 unsigned NumElts = VT.getVectorNumElements(); 2553 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2554 2555 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2556 2557 SDValue TrueMask, VL; 2558 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2559 2560 if (SVN->isSplat()) { 2561 const int Lane = SVN->getSplatIndex(); 2562 if (Lane >= 0) { 2563 MVT SVT = VT.getVectorElementType(); 2564 2565 // Turn splatted vector load into a strided load with an X0 stride. 2566 SDValue V = V1; 2567 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2568 // with undef. 2569 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2570 int Offset = Lane; 2571 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2572 int OpElements = 2573 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2574 V = V.getOperand(Offset / OpElements); 2575 Offset %= OpElements; 2576 } 2577 2578 // We need to ensure the load isn't atomic or volatile. 2579 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2580 auto *Ld = cast<LoadSDNode>(V); 2581 Offset *= SVT.getStoreSize(); 2582 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2583 TypeSize::Fixed(Offset), DL); 2584 2585 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2586 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2587 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2588 SDValue IntID = 2589 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2590 SDValue Ops[] = {Ld->getChain(), 2591 IntID, 2592 DAG.getUNDEF(ContainerVT), 2593 NewAddr, 2594 DAG.getRegister(RISCV::X0, XLenVT), 2595 VL}; 2596 SDValue NewLoad = DAG.getMemIntrinsicNode( 2597 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2598 DAG.getMachineFunction().getMachineMemOperand( 2599 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2600 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2601 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2602 } 2603 2604 // Otherwise use a scalar load and splat. This will give the best 2605 // opportunity to fold a splat into the operation. ISel can turn it into 2606 // the x0 strided load if we aren't able to fold away the select. 2607 if (SVT.isFloatingPoint()) 2608 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2609 Ld->getPointerInfo().getWithOffset(Offset), 2610 Ld->getOriginalAlign(), 2611 Ld->getMemOperand()->getFlags()); 2612 else 2613 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2614 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2615 Ld->getOriginalAlign(), 2616 Ld->getMemOperand()->getFlags()); 2617 DAG.makeEquivalentMemoryOrdering(Ld, V); 2618 2619 unsigned Opc = 2620 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2621 SDValue Splat = 2622 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2623 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2624 } 2625 2626 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2627 assert(Lane < (int)NumElts && "Unexpected lane!"); 2628 SDValue Gather = 2629 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2630 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2631 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2632 } 2633 } 2634 2635 ArrayRef<int> Mask = SVN->getMask(); 2636 2637 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2638 // be undef which can be handled with a single SLIDEDOWN/UP. 2639 int LoSrc, HiSrc; 2640 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2641 if (Rotation > 0) { 2642 SDValue LoV, HiV; 2643 if (LoSrc >= 0) { 2644 LoV = LoSrc == 0 ? V1 : V2; 2645 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2646 } 2647 if (HiSrc >= 0) { 2648 HiV = HiSrc == 0 ? V1 : V2; 2649 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2650 } 2651 2652 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2653 // to slide LoV up by (NumElts - Rotation). 2654 unsigned InvRotate = NumElts - Rotation; 2655 2656 SDValue Res = DAG.getUNDEF(ContainerVT); 2657 if (HiV) { 2658 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2659 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2660 // causes multiple vsetvlis in some test cases such as lowering 2661 // reduce.mul 2662 SDValue DownVL = VL; 2663 if (LoV) 2664 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2665 Res = 2666 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2667 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2668 } 2669 if (LoV) 2670 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2671 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2672 2673 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2674 } 2675 2676 // Detect an interleave shuffle and lower to 2677 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2678 bool SwapSources; 2679 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2680 // Swap sources if needed. 2681 if (SwapSources) 2682 std::swap(V1, V2); 2683 2684 // Extract the lower half of the vectors. 2685 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2686 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2687 DAG.getConstant(0, DL, XLenVT)); 2688 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2689 DAG.getConstant(0, DL, XLenVT)); 2690 2691 // Double the element width and halve the number of elements in an int type. 2692 unsigned EltBits = VT.getScalarSizeInBits(); 2693 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2694 MVT WideIntVT = 2695 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2696 // Convert this to a scalable vector. We need to base this on the 2697 // destination size to ensure there's always a type with a smaller LMUL. 2698 MVT WideIntContainerVT = 2699 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2700 2701 // Convert sources to scalable vectors with the same element count as the 2702 // larger type. 2703 MVT HalfContainerVT = MVT::getVectorVT( 2704 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2705 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2706 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2707 2708 // Cast sources to integer. 2709 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2710 MVT IntHalfVT = 2711 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2712 V1 = DAG.getBitcast(IntHalfVT, V1); 2713 V2 = DAG.getBitcast(IntHalfVT, V2); 2714 2715 // Freeze V2 since we use it twice and we need to be sure that the add and 2716 // multiply see the same value. 2717 V2 = DAG.getFreeze(V2); 2718 2719 // Recreate TrueMask using the widened type's element count. 2720 MVT MaskVT = 2721 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2722 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2723 2724 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2725 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2726 V2, TrueMask, VL); 2727 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2728 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2729 DAG.getUNDEF(IntHalfVT), 2730 DAG.getAllOnesConstant(DL, XLenVT)); 2731 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2732 V2, Multiplier, TrueMask, VL); 2733 // Add the new copies to our previous addition giving us 2^eltbits copies of 2734 // V2. This is equivalent to shifting V2 left by eltbits. This should 2735 // combine with the vwmulu.vv above to form vwmaccu.vv. 2736 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2737 TrueMask, VL); 2738 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2739 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2740 // vector VT. 2741 ContainerVT = 2742 MVT::getVectorVT(VT.getVectorElementType(), 2743 WideIntContainerVT.getVectorElementCount() * 2); 2744 Add = DAG.getBitcast(ContainerVT, Add); 2745 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2746 } 2747 2748 // Detect shuffles which can be re-expressed as vector selects; these are 2749 // shuffles in which each element in the destination is taken from an element 2750 // at the corresponding index in either source vectors. 2751 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2752 int MaskIndex = MaskIdx.value(); 2753 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2754 }); 2755 2756 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2757 2758 SmallVector<SDValue> MaskVals; 2759 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2760 // merged with a second vrgather. 2761 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2762 2763 // By default we preserve the original operand order, and use a mask to 2764 // select LHS as true and RHS as false. However, since RVV vector selects may 2765 // feature splats but only on the LHS, we may choose to invert our mask and 2766 // instead select between RHS and LHS. 2767 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2768 bool InvertMask = IsSelect == SwapOps; 2769 2770 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2771 // half. 2772 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2773 2774 // Now construct the mask that will be used by the vselect or blended 2775 // vrgather operation. For vrgathers, construct the appropriate indices into 2776 // each vector. 2777 for (int MaskIndex : Mask) { 2778 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2779 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2780 if (!IsSelect) { 2781 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2782 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2783 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2784 : DAG.getUNDEF(XLenVT)); 2785 GatherIndicesRHS.push_back( 2786 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2787 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2788 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2789 ++LHSIndexCounts[MaskIndex]; 2790 if (!IsLHSOrUndefIndex) 2791 ++RHSIndexCounts[MaskIndex - NumElts]; 2792 } 2793 } 2794 2795 if (SwapOps) { 2796 std::swap(V1, V2); 2797 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2798 } 2799 2800 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2801 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2802 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2803 2804 if (IsSelect) 2805 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2806 2807 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2808 // On such a large vector we're unable to use i8 as the index type. 2809 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2810 // may involve vector splitting if we're already at LMUL=8, or our 2811 // user-supplied maximum fixed-length LMUL. 2812 return SDValue(); 2813 } 2814 2815 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2816 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2817 MVT IndexVT = VT.changeTypeToInteger(); 2818 // Since we can't introduce illegal index types at this stage, use i16 and 2819 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2820 // than XLenVT. 2821 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2822 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2823 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2824 } 2825 2826 MVT IndexContainerVT = 2827 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2828 2829 SDValue Gather; 2830 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2831 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2832 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2833 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2834 Subtarget); 2835 } else { 2836 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2837 // If only one index is used, we can use a "splat" vrgather. 2838 // TODO: We can splat the most-common index and fix-up any stragglers, if 2839 // that's beneficial. 2840 if (LHSIndexCounts.size() == 1) { 2841 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2842 Gather = 2843 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2844 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2845 } else { 2846 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2847 LHSIndices = 2848 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2849 2850 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2851 TrueMask, VL); 2852 } 2853 } 2854 2855 // If a second vector operand is used by this shuffle, blend it in with an 2856 // additional vrgather. 2857 if (!V2.isUndef()) { 2858 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2859 // If only one index is used, we can use a "splat" vrgather. 2860 // TODO: We can splat the most-common index and fix-up any stragglers, if 2861 // that's beneficial. 2862 if (RHSIndexCounts.size() == 1) { 2863 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2864 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2865 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2866 } else { 2867 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2868 RHSIndices = 2869 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2870 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2871 VL); 2872 } 2873 2874 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2875 SelectMask = 2876 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2877 2878 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2879 Gather, VL); 2880 } 2881 2882 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2883 } 2884 2885 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2886 // Support splats for any type. These should type legalize well. 2887 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2888 return true; 2889 2890 // Only support legal VTs for other shuffles for now. 2891 if (!isTypeLegal(VT)) 2892 return false; 2893 2894 MVT SVT = VT.getSimpleVT(); 2895 2896 bool SwapSources; 2897 int LoSrc, HiSrc; 2898 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2899 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2900 } 2901 2902 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2903 SDLoc DL, SelectionDAG &DAG, 2904 const RISCVSubtarget &Subtarget) { 2905 if (VT.isScalableVector()) 2906 return DAG.getFPExtendOrRound(Op, DL, VT); 2907 assert(VT.isFixedLengthVector() && 2908 "Unexpected value type for RVV FP extend/round lowering"); 2909 SDValue Mask, VL; 2910 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2911 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2912 ? RISCVISD::FP_EXTEND_VL 2913 : RISCVISD::FP_ROUND_VL; 2914 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2915 } 2916 2917 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2918 // the exponent. 2919 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2920 MVT VT = Op.getSimpleValueType(); 2921 unsigned EltSize = VT.getScalarSizeInBits(); 2922 SDValue Src = Op.getOperand(0); 2923 SDLoc DL(Op); 2924 2925 // We need a FP type that can represent the value. 2926 // TODO: Use f16 for i8 when possible? 2927 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2928 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2929 2930 // Legal types should have been checked in the RISCVTargetLowering 2931 // constructor. 2932 // TODO: Splitting may make sense in some cases. 2933 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2934 "Expected legal float type!"); 2935 2936 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2937 // The trailing zero count is equal to log2 of this single bit value. 2938 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2939 SDValue Neg = 2940 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2941 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2942 } 2943 2944 // We have a legal FP type, convert to it. 2945 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2946 // Bitcast to integer and shift the exponent to the LSB. 2947 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2948 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2949 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2950 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2951 DAG.getConstant(ShiftAmt, DL, IntVT)); 2952 // Truncate back to original type to allow vnsrl. 2953 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2954 // The exponent contains log2 of the value in biased form. 2955 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2956 2957 // For trailing zeros, we just need to subtract the bias. 2958 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2959 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2960 DAG.getConstant(ExponentBias, DL, VT)); 2961 2962 // For leading zeros, we need to remove the bias and convert from log2 to 2963 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2964 unsigned Adjust = ExponentBias + (EltSize - 1); 2965 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2966 } 2967 2968 // While RVV has alignment restrictions, we should always be able to load as a 2969 // legal equivalently-sized byte-typed vector instead. This method is 2970 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2971 // the load is already correctly-aligned, it returns SDValue(). 2972 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2973 SelectionDAG &DAG) const { 2974 auto *Load = cast<LoadSDNode>(Op); 2975 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2976 2977 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2978 Load->getMemoryVT(), 2979 *Load->getMemOperand())) 2980 return SDValue(); 2981 2982 SDLoc DL(Op); 2983 MVT VT = Op.getSimpleValueType(); 2984 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2985 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2986 "Unexpected unaligned RVV load type"); 2987 MVT NewVT = 2988 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2989 assert(NewVT.isValid() && 2990 "Expecting equally-sized RVV vector types to be legal"); 2991 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2992 Load->getPointerInfo(), Load->getOriginalAlign(), 2993 Load->getMemOperand()->getFlags()); 2994 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2995 } 2996 2997 // While RVV has alignment restrictions, we should always be able to store as a 2998 // legal equivalently-sized byte-typed vector instead. This method is 2999 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3000 // returns SDValue() if the store is already correctly aligned. 3001 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3002 SelectionDAG &DAG) const { 3003 auto *Store = cast<StoreSDNode>(Op); 3004 assert(Store && Store->getValue().getValueType().isVector() && 3005 "Expected vector store"); 3006 3007 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3008 Store->getMemoryVT(), 3009 *Store->getMemOperand())) 3010 return SDValue(); 3011 3012 SDLoc DL(Op); 3013 SDValue StoredVal = Store->getValue(); 3014 MVT VT = StoredVal.getSimpleValueType(); 3015 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3016 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3017 "Unexpected unaligned RVV store type"); 3018 MVT NewVT = 3019 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3020 assert(NewVT.isValid() && 3021 "Expecting equally-sized RVV vector types to be legal"); 3022 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3023 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3024 Store->getPointerInfo(), Store->getOriginalAlign(), 3025 Store->getMemOperand()->getFlags()); 3026 } 3027 3028 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3029 SelectionDAG &DAG) const { 3030 switch (Op.getOpcode()) { 3031 default: 3032 report_fatal_error("unimplemented operand"); 3033 case ISD::GlobalAddress: 3034 return lowerGlobalAddress(Op, DAG); 3035 case ISD::BlockAddress: 3036 return lowerBlockAddress(Op, DAG); 3037 case ISD::ConstantPool: 3038 return lowerConstantPool(Op, DAG); 3039 case ISD::JumpTable: 3040 return lowerJumpTable(Op, DAG); 3041 case ISD::GlobalTLSAddress: 3042 return lowerGlobalTLSAddress(Op, DAG); 3043 case ISD::SELECT: 3044 return lowerSELECT(Op, DAG); 3045 case ISD::BRCOND: 3046 return lowerBRCOND(Op, DAG); 3047 case ISD::VASTART: 3048 return lowerVASTART(Op, DAG); 3049 case ISD::FRAMEADDR: 3050 return lowerFRAMEADDR(Op, DAG); 3051 case ISD::RETURNADDR: 3052 return lowerRETURNADDR(Op, DAG); 3053 case ISD::SHL_PARTS: 3054 return lowerShiftLeftParts(Op, DAG); 3055 case ISD::SRA_PARTS: 3056 return lowerShiftRightParts(Op, DAG, true); 3057 case ISD::SRL_PARTS: 3058 return lowerShiftRightParts(Op, DAG, false); 3059 case ISD::BITCAST: { 3060 SDLoc DL(Op); 3061 EVT VT = Op.getValueType(); 3062 SDValue Op0 = Op.getOperand(0); 3063 EVT Op0VT = Op0.getValueType(); 3064 MVT XLenVT = Subtarget.getXLenVT(); 3065 if (VT.isFixedLengthVector()) { 3066 // We can handle fixed length vector bitcasts with a simple replacement 3067 // in isel. 3068 if (Op0VT.isFixedLengthVector()) 3069 return Op; 3070 // When bitcasting from scalar to fixed-length vector, insert the scalar 3071 // into a one-element vector of the result type, and perform a vector 3072 // bitcast. 3073 if (!Op0VT.isVector()) { 3074 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3075 if (!isTypeLegal(BVT)) 3076 return SDValue(); 3077 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3078 DAG.getUNDEF(BVT), Op0, 3079 DAG.getConstant(0, DL, XLenVT))); 3080 } 3081 return SDValue(); 3082 } 3083 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3084 // thus: bitcast the vector to a one-element vector type whose element type 3085 // is the same as the result type, and extract the first element. 3086 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3087 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3088 if (!isTypeLegal(BVT)) 3089 return SDValue(); 3090 SDValue BVec = DAG.getBitcast(BVT, Op0); 3091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3092 DAG.getConstant(0, DL, XLenVT)); 3093 } 3094 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3095 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3096 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3097 return FPConv; 3098 } 3099 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3100 Subtarget.hasStdExtF()) { 3101 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3102 SDValue FPConv = 3103 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3104 return FPConv; 3105 } 3106 return SDValue(); 3107 } 3108 case ISD::INTRINSIC_WO_CHAIN: 3109 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3110 case ISD::INTRINSIC_W_CHAIN: 3111 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3112 case ISD::INTRINSIC_VOID: 3113 return LowerINTRINSIC_VOID(Op, DAG); 3114 case ISD::BSWAP: 3115 case ISD::BITREVERSE: { 3116 MVT VT = Op.getSimpleValueType(); 3117 SDLoc DL(Op); 3118 if (Subtarget.hasStdExtZbp()) { 3119 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3120 // Start with the maximum immediate value which is the bitwidth - 1. 3121 unsigned Imm = VT.getSizeInBits() - 1; 3122 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3123 if (Op.getOpcode() == ISD::BSWAP) 3124 Imm &= ~0x7U; 3125 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3126 DAG.getConstant(Imm, DL, VT)); 3127 } 3128 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3129 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3130 // Expand bitreverse to a bswap(rev8) followed by brev8. 3131 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3132 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3133 // as brev8 by an isel pattern. 3134 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3135 DAG.getConstant(7, DL, VT)); 3136 } 3137 case ISD::FSHL: 3138 case ISD::FSHR: { 3139 MVT VT = Op.getSimpleValueType(); 3140 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3141 SDLoc DL(Op); 3142 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3143 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3144 // accidentally setting the extra bit. 3145 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3146 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3147 DAG.getConstant(ShAmtWidth, DL, VT)); 3148 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3149 // instruction use different orders. fshl will return its first operand for 3150 // shift of zero, fshr will return its second operand. fsl and fsr both 3151 // return rs1 so the ISD nodes need to have different operand orders. 3152 // Shift amount is in rs2. 3153 SDValue Op0 = Op.getOperand(0); 3154 SDValue Op1 = Op.getOperand(1); 3155 unsigned Opc = RISCVISD::FSL; 3156 if (Op.getOpcode() == ISD::FSHR) { 3157 std::swap(Op0, Op1); 3158 Opc = RISCVISD::FSR; 3159 } 3160 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3161 } 3162 case ISD::TRUNCATE: { 3163 SDLoc DL(Op); 3164 MVT VT = Op.getSimpleValueType(); 3165 // Only custom-lower vector truncates 3166 if (!VT.isVector()) 3167 return Op; 3168 3169 // Truncates to mask types are handled differently 3170 if (VT.getVectorElementType() == MVT::i1) 3171 return lowerVectorMaskTrunc(Op, DAG); 3172 3173 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3174 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3175 // truncate by one power of two at a time. 3176 MVT DstEltVT = VT.getVectorElementType(); 3177 3178 SDValue Src = Op.getOperand(0); 3179 MVT SrcVT = Src.getSimpleValueType(); 3180 MVT SrcEltVT = SrcVT.getVectorElementType(); 3181 3182 assert(DstEltVT.bitsLT(SrcEltVT) && 3183 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3184 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3185 "Unexpected vector truncate lowering"); 3186 3187 MVT ContainerVT = SrcVT; 3188 if (SrcVT.isFixedLengthVector()) { 3189 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3190 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3191 } 3192 3193 SDValue Result = Src; 3194 SDValue Mask, VL; 3195 std::tie(Mask, VL) = 3196 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3197 LLVMContext &Context = *DAG.getContext(); 3198 const ElementCount Count = ContainerVT.getVectorElementCount(); 3199 do { 3200 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3201 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3202 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3203 Mask, VL); 3204 } while (SrcEltVT != DstEltVT); 3205 3206 if (SrcVT.isFixedLengthVector()) 3207 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3208 3209 return Result; 3210 } 3211 case ISD::ANY_EXTEND: 3212 case ISD::ZERO_EXTEND: 3213 if (Op.getOperand(0).getValueType().isVector() && 3214 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3215 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3216 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3217 case ISD::SIGN_EXTEND: 3218 if (Op.getOperand(0).getValueType().isVector() && 3219 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3220 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3221 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3222 case ISD::SPLAT_VECTOR_PARTS: 3223 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3224 case ISD::INSERT_VECTOR_ELT: 3225 return lowerINSERT_VECTOR_ELT(Op, DAG); 3226 case ISD::EXTRACT_VECTOR_ELT: 3227 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3228 case ISD::VSCALE: { 3229 MVT VT = Op.getSimpleValueType(); 3230 SDLoc DL(Op); 3231 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3232 // We define our scalable vector types for lmul=1 to use a 64 bit known 3233 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3234 // vscale as VLENB / 8. 3235 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3236 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3237 report_fatal_error("Support for VLEN==32 is incomplete."); 3238 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3239 // We assume VLENB is a multiple of 8. We manually choose the best shift 3240 // here because SimplifyDemandedBits isn't always able to simplify it. 3241 uint64_t Val = Op.getConstantOperandVal(0); 3242 if (isPowerOf2_64(Val)) { 3243 uint64_t Log2 = Log2_64(Val); 3244 if (Log2 < 3) 3245 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3246 DAG.getConstant(3 - Log2, DL, VT)); 3247 if (Log2 > 3) 3248 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3249 DAG.getConstant(Log2 - 3, DL, VT)); 3250 return VLENB; 3251 } 3252 // If the multiplier is a multiple of 8, scale it down to avoid needing 3253 // to shift the VLENB value. 3254 if ((Val % 8) == 0) 3255 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3256 DAG.getConstant(Val / 8, DL, VT)); 3257 } 3258 3259 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3260 DAG.getConstant(3, DL, VT)); 3261 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3262 } 3263 case ISD::FPOWI: { 3264 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3265 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3266 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3267 Op.getOperand(1).getValueType() == MVT::i32) { 3268 SDLoc DL(Op); 3269 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3270 SDValue Powi = 3271 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3272 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3273 DAG.getIntPtrConstant(0, DL)); 3274 } 3275 return SDValue(); 3276 } 3277 case ISD::FP_EXTEND: { 3278 // RVV can only do fp_extend to types double the size as the source. We 3279 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3280 // via f32. 3281 SDLoc DL(Op); 3282 MVT VT = Op.getSimpleValueType(); 3283 SDValue Src = Op.getOperand(0); 3284 MVT SrcVT = Src.getSimpleValueType(); 3285 3286 // Prepare any fixed-length vector operands. 3287 MVT ContainerVT = VT; 3288 if (SrcVT.isFixedLengthVector()) { 3289 ContainerVT = getContainerForFixedLengthVector(VT); 3290 MVT SrcContainerVT = 3291 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3292 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3293 } 3294 3295 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3296 SrcVT.getVectorElementType() != MVT::f16) { 3297 // For scalable vectors, we only need to close the gap between 3298 // vXf16->vXf64. 3299 if (!VT.isFixedLengthVector()) 3300 return Op; 3301 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3302 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3303 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3304 } 3305 3306 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3307 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3308 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3309 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3310 3311 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3312 DL, DAG, Subtarget); 3313 if (VT.isFixedLengthVector()) 3314 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3315 return Extend; 3316 } 3317 case ISD::FP_ROUND: { 3318 // RVV can only do fp_round to types half the size as the source. We 3319 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3320 // conversion instruction. 3321 SDLoc DL(Op); 3322 MVT VT = Op.getSimpleValueType(); 3323 SDValue Src = Op.getOperand(0); 3324 MVT SrcVT = Src.getSimpleValueType(); 3325 3326 // Prepare any fixed-length vector operands. 3327 MVT ContainerVT = VT; 3328 if (VT.isFixedLengthVector()) { 3329 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3330 ContainerVT = 3331 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3332 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3333 } 3334 3335 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3336 SrcVT.getVectorElementType() != MVT::f64) { 3337 // For scalable vectors, we only need to close the gap between 3338 // vXf64<->vXf16. 3339 if (!VT.isFixedLengthVector()) 3340 return Op; 3341 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3342 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3343 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3344 } 3345 3346 SDValue Mask, VL; 3347 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3348 3349 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3350 SDValue IntermediateRound = 3351 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3352 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3353 DL, DAG, Subtarget); 3354 3355 if (VT.isFixedLengthVector()) 3356 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3357 return Round; 3358 } 3359 case ISD::FP_TO_SINT: 3360 case ISD::FP_TO_UINT: 3361 case ISD::SINT_TO_FP: 3362 case ISD::UINT_TO_FP: { 3363 // RVV can only do fp<->int conversions to types half/double the size as 3364 // the source. We custom-lower any conversions that do two hops into 3365 // sequences. 3366 MVT VT = Op.getSimpleValueType(); 3367 if (!VT.isVector()) 3368 return Op; 3369 SDLoc DL(Op); 3370 SDValue Src = Op.getOperand(0); 3371 MVT EltVT = VT.getVectorElementType(); 3372 MVT SrcVT = Src.getSimpleValueType(); 3373 MVT SrcEltVT = SrcVT.getVectorElementType(); 3374 unsigned EltSize = EltVT.getSizeInBits(); 3375 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3376 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3377 "Unexpected vector element types"); 3378 3379 bool IsInt2FP = SrcEltVT.isInteger(); 3380 // Widening conversions 3381 if (EltSize > (2 * SrcEltSize)) { 3382 if (IsInt2FP) { 3383 // Do a regular integer sign/zero extension then convert to float. 3384 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3385 VT.getVectorElementCount()); 3386 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3387 ? ISD::ZERO_EXTEND 3388 : ISD::SIGN_EXTEND; 3389 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3390 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3391 } 3392 // FP2Int 3393 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3394 // Do one doubling fp_extend then complete the operation by converting 3395 // to int. 3396 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3397 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3398 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3399 } 3400 3401 // Narrowing conversions 3402 if (SrcEltSize > (2 * EltSize)) { 3403 if (IsInt2FP) { 3404 // One narrowing int_to_fp, then an fp_round. 3405 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3406 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3407 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3408 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3409 } 3410 // FP2Int 3411 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3412 // representable by the integer, the result is poison. 3413 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3414 VT.getVectorElementCount()); 3415 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3416 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3417 } 3418 3419 // Scalable vectors can exit here. Patterns will handle equally-sized 3420 // conversions halving/doubling ones. 3421 if (!VT.isFixedLengthVector()) 3422 return Op; 3423 3424 // For fixed-length vectors we lower to a custom "VL" node. 3425 unsigned RVVOpc = 0; 3426 switch (Op.getOpcode()) { 3427 default: 3428 llvm_unreachable("Impossible opcode"); 3429 case ISD::FP_TO_SINT: 3430 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3431 break; 3432 case ISD::FP_TO_UINT: 3433 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3434 break; 3435 case ISD::SINT_TO_FP: 3436 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3437 break; 3438 case ISD::UINT_TO_FP: 3439 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3440 break; 3441 } 3442 3443 MVT ContainerVT, SrcContainerVT; 3444 // Derive the reference container type from the larger vector type. 3445 if (SrcEltSize > EltSize) { 3446 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3447 ContainerVT = 3448 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3449 } else { 3450 ContainerVT = getContainerForFixedLengthVector(VT); 3451 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3452 } 3453 3454 SDValue Mask, VL; 3455 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3456 3457 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3458 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3459 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3460 } 3461 case ISD::FP_TO_SINT_SAT: 3462 case ISD::FP_TO_UINT_SAT: 3463 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3464 case ISD::FTRUNC: 3465 case ISD::FCEIL: 3466 case ISD::FFLOOR: 3467 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3468 case ISD::FROUND: 3469 return lowerFROUND(Op, DAG); 3470 case ISD::VECREDUCE_ADD: 3471 case ISD::VECREDUCE_UMAX: 3472 case ISD::VECREDUCE_SMAX: 3473 case ISD::VECREDUCE_UMIN: 3474 case ISD::VECREDUCE_SMIN: 3475 return lowerVECREDUCE(Op, DAG); 3476 case ISD::VECREDUCE_AND: 3477 case ISD::VECREDUCE_OR: 3478 case ISD::VECREDUCE_XOR: 3479 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3480 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3481 return lowerVECREDUCE(Op, DAG); 3482 case ISD::VECREDUCE_FADD: 3483 case ISD::VECREDUCE_SEQ_FADD: 3484 case ISD::VECREDUCE_FMIN: 3485 case ISD::VECREDUCE_FMAX: 3486 return lowerFPVECREDUCE(Op, DAG); 3487 case ISD::VP_REDUCE_ADD: 3488 case ISD::VP_REDUCE_UMAX: 3489 case ISD::VP_REDUCE_SMAX: 3490 case ISD::VP_REDUCE_UMIN: 3491 case ISD::VP_REDUCE_SMIN: 3492 case ISD::VP_REDUCE_FADD: 3493 case ISD::VP_REDUCE_SEQ_FADD: 3494 case ISD::VP_REDUCE_FMIN: 3495 case ISD::VP_REDUCE_FMAX: 3496 return lowerVPREDUCE(Op, DAG); 3497 case ISD::VP_REDUCE_AND: 3498 case ISD::VP_REDUCE_OR: 3499 case ISD::VP_REDUCE_XOR: 3500 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3501 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3502 return lowerVPREDUCE(Op, DAG); 3503 case ISD::INSERT_SUBVECTOR: 3504 return lowerINSERT_SUBVECTOR(Op, DAG); 3505 case ISD::EXTRACT_SUBVECTOR: 3506 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3507 case ISD::STEP_VECTOR: 3508 return lowerSTEP_VECTOR(Op, DAG); 3509 case ISD::VECTOR_REVERSE: 3510 return lowerVECTOR_REVERSE(Op, DAG); 3511 case ISD::VECTOR_SPLICE: 3512 return lowerVECTOR_SPLICE(Op, DAG); 3513 case ISD::BUILD_VECTOR: 3514 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3515 case ISD::SPLAT_VECTOR: 3516 if (Op.getValueType().getVectorElementType() == MVT::i1) 3517 return lowerVectorMaskSplat(Op, DAG); 3518 return SDValue(); 3519 case ISD::VECTOR_SHUFFLE: 3520 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3521 case ISD::CONCAT_VECTORS: { 3522 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3523 // better than going through the stack, as the default expansion does. 3524 SDLoc DL(Op); 3525 MVT VT = Op.getSimpleValueType(); 3526 unsigned NumOpElts = 3527 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3528 SDValue Vec = DAG.getUNDEF(VT); 3529 for (const auto &OpIdx : enumerate(Op->ops())) { 3530 SDValue SubVec = OpIdx.value(); 3531 // Don't insert undef subvectors. 3532 if (SubVec.isUndef()) 3533 continue; 3534 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3535 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3536 } 3537 return Vec; 3538 } 3539 case ISD::LOAD: 3540 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3541 return V; 3542 if (Op.getValueType().isFixedLengthVector()) 3543 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3544 return Op; 3545 case ISD::STORE: 3546 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3547 return V; 3548 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3549 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3550 return Op; 3551 case ISD::MLOAD: 3552 case ISD::VP_LOAD: 3553 return lowerMaskedLoad(Op, DAG); 3554 case ISD::MSTORE: 3555 case ISD::VP_STORE: 3556 return lowerMaskedStore(Op, DAG); 3557 case ISD::SETCC: 3558 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3559 case ISD::ADD: 3560 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3561 case ISD::SUB: 3562 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3563 case ISD::MUL: 3564 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3565 case ISD::MULHS: 3566 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3567 case ISD::MULHU: 3568 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3569 case ISD::AND: 3570 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3571 RISCVISD::AND_VL); 3572 case ISD::OR: 3573 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3574 RISCVISD::OR_VL); 3575 case ISD::XOR: 3576 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3577 RISCVISD::XOR_VL); 3578 case ISD::SDIV: 3579 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3580 case ISD::SREM: 3581 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3582 case ISD::UDIV: 3583 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3584 case ISD::UREM: 3585 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3586 case ISD::SHL: 3587 case ISD::SRA: 3588 case ISD::SRL: 3589 if (Op.getSimpleValueType().isFixedLengthVector()) 3590 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3591 // This can be called for an i32 shift amount that needs to be promoted. 3592 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3593 "Unexpected custom legalisation"); 3594 return SDValue(); 3595 case ISD::SADDSAT: 3596 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3597 case ISD::UADDSAT: 3598 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3599 case ISD::SSUBSAT: 3600 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3601 case ISD::USUBSAT: 3602 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3603 case ISD::FADD: 3604 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3605 case ISD::FSUB: 3606 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3607 case ISD::FMUL: 3608 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3609 case ISD::FDIV: 3610 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3611 case ISD::FNEG: 3612 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3613 case ISD::FABS: 3614 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3615 case ISD::FSQRT: 3616 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3617 case ISD::FMA: 3618 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3619 case ISD::SMIN: 3620 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3621 case ISD::SMAX: 3622 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3623 case ISD::UMIN: 3624 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3625 case ISD::UMAX: 3626 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3627 case ISD::FMINNUM: 3628 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3629 case ISD::FMAXNUM: 3630 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3631 case ISD::ABS: 3632 return lowerABS(Op, DAG); 3633 case ISD::CTLZ_ZERO_UNDEF: 3634 case ISD::CTTZ_ZERO_UNDEF: 3635 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3636 case ISD::VSELECT: 3637 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3638 case ISD::FCOPYSIGN: 3639 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3640 case ISD::MGATHER: 3641 case ISD::VP_GATHER: 3642 return lowerMaskedGather(Op, DAG); 3643 case ISD::MSCATTER: 3644 case ISD::VP_SCATTER: 3645 return lowerMaskedScatter(Op, DAG); 3646 case ISD::FLT_ROUNDS_: 3647 return lowerGET_ROUNDING(Op, DAG); 3648 case ISD::SET_ROUNDING: 3649 return lowerSET_ROUNDING(Op, DAG); 3650 case ISD::VP_SELECT: 3651 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3652 case ISD::VP_MERGE: 3653 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3654 case ISD::VP_ADD: 3655 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3656 case ISD::VP_SUB: 3657 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3658 case ISD::VP_MUL: 3659 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3660 case ISD::VP_SDIV: 3661 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3662 case ISD::VP_UDIV: 3663 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3664 case ISD::VP_SREM: 3665 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3666 case ISD::VP_UREM: 3667 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3668 case ISD::VP_AND: 3669 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3670 case ISD::VP_OR: 3671 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3672 case ISD::VP_XOR: 3673 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3674 case ISD::VP_ASHR: 3675 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3676 case ISD::VP_LSHR: 3677 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3678 case ISD::VP_SHL: 3679 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3680 case ISD::VP_FADD: 3681 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3682 case ISD::VP_FSUB: 3683 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3684 case ISD::VP_FMUL: 3685 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3686 case ISD::VP_FDIV: 3687 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3688 case ISD::VP_FNEG: 3689 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3690 case ISD::VP_FMA: 3691 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3692 case ISD::VP_FPTOSI: 3693 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3694 case ISD::VP_FPTOUI: 3695 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3696 case ISD::VP_SITOFP: 3697 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3698 case ISD::VP_UITOFP: 3699 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3700 } 3701 } 3702 3703 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3704 SelectionDAG &DAG, unsigned Flags) { 3705 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3706 } 3707 3708 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3709 SelectionDAG &DAG, unsigned Flags) { 3710 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3711 Flags); 3712 } 3713 3714 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3715 SelectionDAG &DAG, unsigned Flags) { 3716 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3717 N->getOffset(), Flags); 3718 } 3719 3720 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3721 SelectionDAG &DAG, unsigned Flags) { 3722 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3723 } 3724 3725 template <class NodeTy> 3726 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3727 bool IsLocal) const { 3728 SDLoc DL(N); 3729 EVT Ty = getPointerTy(DAG.getDataLayout()); 3730 3731 if (isPositionIndependent()) { 3732 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3733 if (IsLocal) 3734 // Use PC-relative addressing to access the symbol. This generates the 3735 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3736 // %pcrel_lo(auipc)). 3737 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3738 3739 // Use PC-relative addressing to access the GOT for this symbol, then load 3740 // the address from the GOT. This generates the pattern (PseudoLA sym), 3741 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3742 SDValue Load = 3743 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3744 MachineFunction &MF = DAG.getMachineFunction(); 3745 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3746 MachinePointerInfo::getGOT(MF), 3747 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3748 MachineMemOperand::MOInvariant, 3749 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3750 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3751 return Load; 3752 } 3753 3754 switch (getTargetMachine().getCodeModel()) { 3755 default: 3756 report_fatal_error("Unsupported code model for lowering"); 3757 case CodeModel::Small: { 3758 // Generate a sequence for accessing addresses within the first 2 GiB of 3759 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3760 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3761 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3762 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3763 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3764 } 3765 case CodeModel::Medium: { 3766 // Generate a sequence for accessing addresses within any 2GiB range within 3767 // the address space. This generates the pattern (PseudoLLA sym), which 3768 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3769 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3770 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3771 } 3772 } 3773 } 3774 3775 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3776 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3777 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3778 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3779 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3780 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3781 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3782 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3783 3784 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3785 SelectionDAG &DAG) const { 3786 SDLoc DL(Op); 3787 EVT Ty = Op.getValueType(); 3788 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3789 int64_t Offset = N->getOffset(); 3790 MVT XLenVT = Subtarget.getXLenVT(); 3791 3792 const GlobalValue *GV = N->getGlobal(); 3793 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3794 SDValue Addr = getAddr(N, DAG, IsLocal); 3795 3796 // In order to maximise the opportunity for common subexpression elimination, 3797 // emit a separate ADD node for the global address offset instead of folding 3798 // it in the global address node. Later peephole optimisations may choose to 3799 // fold it back in when profitable. 3800 if (Offset != 0) 3801 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3802 DAG.getConstant(Offset, DL, XLenVT)); 3803 return Addr; 3804 } 3805 3806 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3807 SelectionDAG &DAG) const { 3808 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3809 3810 return getAddr(N, DAG); 3811 } 3812 3813 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3814 SelectionDAG &DAG) const { 3815 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3816 3817 return getAddr(N, DAG); 3818 } 3819 3820 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3821 SelectionDAG &DAG) const { 3822 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3823 3824 return getAddr(N, DAG); 3825 } 3826 3827 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3828 SelectionDAG &DAG, 3829 bool UseGOT) const { 3830 SDLoc DL(N); 3831 EVT Ty = getPointerTy(DAG.getDataLayout()); 3832 const GlobalValue *GV = N->getGlobal(); 3833 MVT XLenVT = Subtarget.getXLenVT(); 3834 3835 if (UseGOT) { 3836 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3837 // load the address from the GOT and add the thread pointer. This generates 3838 // the pattern (PseudoLA_TLS_IE sym), which expands to 3839 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3840 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3841 SDValue Load = 3842 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3843 MachineFunction &MF = DAG.getMachineFunction(); 3844 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3845 MachinePointerInfo::getGOT(MF), 3846 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3847 MachineMemOperand::MOInvariant, 3848 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3849 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3850 3851 // Add the thread pointer. 3852 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3853 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3854 } 3855 3856 // Generate a sequence for accessing the address relative to the thread 3857 // pointer, with the appropriate adjustment for the thread pointer offset. 3858 // This generates the pattern 3859 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3860 SDValue AddrHi = 3861 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3862 SDValue AddrAdd = 3863 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3864 SDValue AddrLo = 3865 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3866 3867 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3868 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3869 SDValue MNAdd = SDValue( 3870 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3871 0); 3872 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3873 } 3874 3875 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3876 SelectionDAG &DAG) const { 3877 SDLoc DL(N); 3878 EVT Ty = getPointerTy(DAG.getDataLayout()); 3879 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3880 const GlobalValue *GV = N->getGlobal(); 3881 3882 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3883 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3884 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3885 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3886 SDValue Load = 3887 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3888 3889 // Prepare argument list to generate call. 3890 ArgListTy Args; 3891 ArgListEntry Entry; 3892 Entry.Node = Load; 3893 Entry.Ty = CallTy; 3894 Args.push_back(Entry); 3895 3896 // Setup call to __tls_get_addr. 3897 TargetLowering::CallLoweringInfo CLI(DAG); 3898 CLI.setDebugLoc(DL) 3899 .setChain(DAG.getEntryNode()) 3900 .setLibCallee(CallingConv::C, CallTy, 3901 DAG.getExternalSymbol("__tls_get_addr", Ty), 3902 std::move(Args)); 3903 3904 return LowerCallTo(CLI).first; 3905 } 3906 3907 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3908 SelectionDAG &DAG) const { 3909 SDLoc DL(Op); 3910 EVT Ty = Op.getValueType(); 3911 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3912 int64_t Offset = N->getOffset(); 3913 MVT XLenVT = Subtarget.getXLenVT(); 3914 3915 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3916 3917 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3918 CallingConv::GHC) 3919 report_fatal_error("In GHC calling convention TLS is not supported"); 3920 3921 SDValue Addr; 3922 switch (Model) { 3923 case TLSModel::LocalExec: 3924 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3925 break; 3926 case TLSModel::InitialExec: 3927 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3928 break; 3929 case TLSModel::LocalDynamic: 3930 case TLSModel::GeneralDynamic: 3931 Addr = getDynamicTLSAddr(N, DAG); 3932 break; 3933 } 3934 3935 // In order to maximise the opportunity for common subexpression elimination, 3936 // emit a separate ADD node for the global address offset instead of folding 3937 // it in the global address node. Later peephole optimisations may choose to 3938 // fold it back in when profitable. 3939 if (Offset != 0) 3940 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3941 DAG.getConstant(Offset, DL, XLenVT)); 3942 return Addr; 3943 } 3944 3945 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3946 SDValue CondV = Op.getOperand(0); 3947 SDValue TrueV = Op.getOperand(1); 3948 SDValue FalseV = Op.getOperand(2); 3949 SDLoc DL(Op); 3950 MVT VT = Op.getSimpleValueType(); 3951 MVT XLenVT = Subtarget.getXLenVT(); 3952 3953 // Lower vector SELECTs to VSELECTs by splatting the condition. 3954 if (VT.isVector()) { 3955 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3956 SDValue CondSplat = VT.isScalableVector() 3957 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3958 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3959 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3960 } 3961 3962 // If the result type is XLenVT and CondV is the output of a SETCC node 3963 // which also operated on XLenVT inputs, then merge the SETCC node into the 3964 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3965 // compare+branch instructions. i.e.: 3966 // (select (setcc lhs, rhs, cc), truev, falsev) 3967 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3968 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3969 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3970 SDValue LHS = CondV.getOperand(0); 3971 SDValue RHS = CondV.getOperand(1); 3972 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3973 ISD::CondCode CCVal = CC->get(); 3974 3975 // Special case for a select of 2 constants that have a diffence of 1. 3976 // Normally this is done by DAGCombine, but if the select is introduced by 3977 // type legalization or op legalization, we miss it. Restricting to SETLT 3978 // case for now because that is what signed saturating add/sub need. 3979 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3980 // but we would probably want to swap the true/false values if the condition 3981 // is SETGE/SETLE to avoid an XORI. 3982 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3983 CCVal == ISD::SETLT) { 3984 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3985 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3986 if (TrueVal - 1 == FalseVal) 3987 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3988 if (TrueVal + 1 == FalseVal) 3989 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3990 } 3991 3992 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3993 3994 SDValue TargetCC = DAG.getCondCode(CCVal); 3995 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3996 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3997 } 3998 3999 // Otherwise: 4000 // (select condv, truev, falsev) 4001 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 4002 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4003 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 4004 4005 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 4006 4007 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 4008 } 4009 4010 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4011 SDValue CondV = Op.getOperand(1); 4012 SDLoc DL(Op); 4013 MVT XLenVT = Subtarget.getXLenVT(); 4014 4015 if (CondV.getOpcode() == ISD::SETCC && 4016 CondV.getOperand(0).getValueType() == XLenVT) { 4017 SDValue LHS = CondV.getOperand(0); 4018 SDValue RHS = CondV.getOperand(1); 4019 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4020 4021 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4022 4023 SDValue TargetCC = DAG.getCondCode(CCVal); 4024 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4025 LHS, RHS, TargetCC, Op.getOperand(2)); 4026 } 4027 4028 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4029 CondV, DAG.getConstant(0, DL, XLenVT), 4030 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4031 } 4032 4033 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4034 MachineFunction &MF = DAG.getMachineFunction(); 4035 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4036 4037 SDLoc DL(Op); 4038 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4039 getPointerTy(MF.getDataLayout())); 4040 4041 // vastart just stores the address of the VarArgsFrameIndex slot into the 4042 // memory location argument. 4043 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4044 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4045 MachinePointerInfo(SV)); 4046 } 4047 4048 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4049 SelectionDAG &DAG) const { 4050 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4051 MachineFunction &MF = DAG.getMachineFunction(); 4052 MachineFrameInfo &MFI = MF.getFrameInfo(); 4053 MFI.setFrameAddressIsTaken(true); 4054 Register FrameReg = RI.getFrameRegister(MF); 4055 int XLenInBytes = Subtarget.getXLen() / 8; 4056 4057 EVT VT = Op.getValueType(); 4058 SDLoc DL(Op); 4059 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4060 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4061 while (Depth--) { 4062 int Offset = -(XLenInBytes * 2); 4063 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4064 DAG.getIntPtrConstant(Offset, DL)); 4065 FrameAddr = 4066 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4067 } 4068 return FrameAddr; 4069 } 4070 4071 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4072 SelectionDAG &DAG) const { 4073 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4074 MachineFunction &MF = DAG.getMachineFunction(); 4075 MachineFrameInfo &MFI = MF.getFrameInfo(); 4076 MFI.setReturnAddressIsTaken(true); 4077 MVT XLenVT = Subtarget.getXLenVT(); 4078 int XLenInBytes = Subtarget.getXLen() / 8; 4079 4080 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4081 return SDValue(); 4082 4083 EVT VT = Op.getValueType(); 4084 SDLoc DL(Op); 4085 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4086 if (Depth) { 4087 int Off = -XLenInBytes; 4088 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4089 SDValue Offset = DAG.getConstant(Off, DL, VT); 4090 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4091 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4092 MachinePointerInfo()); 4093 } 4094 4095 // Return the value of the return address register, marking it an implicit 4096 // live-in. 4097 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4098 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4099 } 4100 4101 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4102 SelectionDAG &DAG) const { 4103 SDLoc DL(Op); 4104 SDValue Lo = Op.getOperand(0); 4105 SDValue Hi = Op.getOperand(1); 4106 SDValue Shamt = Op.getOperand(2); 4107 EVT VT = Lo.getValueType(); 4108 4109 // if Shamt-XLEN < 0: // Shamt < XLEN 4110 // Lo = Lo << Shamt 4111 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4112 // else: 4113 // Lo = 0 4114 // Hi = Lo << (Shamt-XLEN) 4115 4116 SDValue Zero = DAG.getConstant(0, DL, VT); 4117 SDValue One = DAG.getConstant(1, DL, VT); 4118 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4119 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4120 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4121 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4122 4123 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4124 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4125 SDValue ShiftRightLo = 4126 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4127 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4128 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4129 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4130 4131 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4132 4133 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4134 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4135 4136 SDValue Parts[2] = {Lo, Hi}; 4137 return DAG.getMergeValues(Parts, DL); 4138 } 4139 4140 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4141 bool IsSRA) const { 4142 SDLoc DL(Op); 4143 SDValue Lo = Op.getOperand(0); 4144 SDValue Hi = Op.getOperand(1); 4145 SDValue Shamt = Op.getOperand(2); 4146 EVT VT = Lo.getValueType(); 4147 4148 // SRA expansion: 4149 // if Shamt-XLEN < 0: // Shamt < XLEN 4150 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4151 // Hi = Hi >>s Shamt 4152 // else: 4153 // Lo = Hi >>s (Shamt-XLEN); 4154 // Hi = Hi >>s (XLEN-1) 4155 // 4156 // SRL expansion: 4157 // if Shamt-XLEN < 0: // Shamt < XLEN 4158 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4159 // Hi = Hi >>u Shamt 4160 // else: 4161 // Lo = Hi >>u (Shamt-XLEN); 4162 // Hi = 0; 4163 4164 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4165 4166 SDValue Zero = DAG.getConstant(0, DL, VT); 4167 SDValue One = DAG.getConstant(1, DL, VT); 4168 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4169 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4170 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4171 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4172 4173 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4174 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4175 SDValue ShiftLeftHi = 4176 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4177 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4178 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4179 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4180 SDValue HiFalse = 4181 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4182 4183 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4184 4185 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4186 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4187 4188 SDValue Parts[2] = {Lo, Hi}; 4189 return DAG.getMergeValues(Parts, DL); 4190 } 4191 4192 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4193 // legal equivalently-sized i8 type, so we can use that as a go-between. 4194 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4195 SelectionDAG &DAG) const { 4196 SDLoc DL(Op); 4197 MVT VT = Op.getSimpleValueType(); 4198 SDValue SplatVal = Op.getOperand(0); 4199 // All-zeros or all-ones splats are handled specially. 4200 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4201 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4202 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4203 } 4204 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4205 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4206 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4207 } 4208 MVT XLenVT = Subtarget.getXLenVT(); 4209 assert(SplatVal.getValueType() == XLenVT && 4210 "Unexpected type for i1 splat value"); 4211 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4212 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4213 DAG.getConstant(1, DL, XLenVT)); 4214 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4215 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4216 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4217 } 4218 4219 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4220 // illegal (currently only vXi64 RV32). 4221 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4222 // them to VMV_V_X_VL. 4223 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4224 SelectionDAG &DAG) const { 4225 SDLoc DL(Op); 4226 MVT VecVT = Op.getSimpleValueType(); 4227 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4228 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4229 4230 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4231 SDValue Lo = Op.getOperand(0); 4232 SDValue Hi = Op.getOperand(1); 4233 4234 if (VecVT.isFixedLengthVector()) { 4235 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4236 SDLoc DL(Op); 4237 SDValue Mask, VL; 4238 std::tie(Mask, VL) = 4239 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4240 4241 SDValue Res = 4242 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4243 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4244 } 4245 4246 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4247 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4248 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4249 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4250 // node in order to try and match RVV vector/scalar instructions. 4251 if ((LoC >> 31) == HiC) 4252 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4253 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4254 } 4255 4256 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4257 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4258 isa<ConstantSDNode>(Hi.getOperand(1)) && 4259 Hi.getConstantOperandVal(1) == 31) 4260 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4261 DAG.getRegister(RISCV::X0, MVT::i32)); 4262 4263 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4264 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4265 DAG.getUNDEF(VecVT), Lo, Hi, 4266 DAG.getRegister(RISCV::X0, MVT::i32)); 4267 } 4268 4269 // Custom-lower extensions from mask vectors by using a vselect either with 1 4270 // for zero/any-extension or -1 for sign-extension: 4271 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4272 // Note that any-extension is lowered identically to zero-extension. 4273 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4274 int64_t ExtTrueVal) const { 4275 SDLoc DL(Op); 4276 MVT VecVT = Op.getSimpleValueType(); 4277 SDValue Src = Op.getOperand(0); 4278 // Only custom-lower extensions from mask types 4279 assert(Src.getValueType().isVector() && 4280 Src.getValueType().getVectorElementType() == MVT::i1); 4281 4282 if (VecVT.isScalableVector()) { 4283 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4284 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4285 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4286 } 4287 4288 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4289 MVT I1ContainerVT = 4290 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4291 4292 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4293 4294 SDValue Mask, VL; 4295 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4296 4297 MVT XLenVT = Subtarget.getXLenVT(); 4298 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4299 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4300 4301 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4302 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4303 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4304 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4305 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4306 SplatTrueVal, SplatZero, VL); 4307 4308 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4309 } 4310 4311 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4312 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4313 MVT ExtVT = Op.getSimpleValueType(); 4314 // Only custom-lower extensions from fixed-length vector types. 4315 if (!ExtVT.isFixedLengthVector()) 4316 return Op; 4317 MVT VT = Op.getOperand(0).getSimpleValueType(); 4318 // Grab the canonical container type for the extended type. Infer the smaller 4319 // type from that to ensure the same number of vector elements, as we know 4320 // the LMUL will be sufficient to hold the smaller type. 4321 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4322 // Get the extended container type manually to ensure the same number of 4323 // vector elements between source and dest. 4324 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4325 ContainerExtVT.getVectorElementCount()); 4326 4327 SDValue Op1 = 4328 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4329 4330 SDLoc DL(Op); 4331 SDValue Mask, VL; 4332 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4333 4334 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4335 4336 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4337 } 4338 4339 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4340 // setcc operation: 4341 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4342 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4343 SelectionDAG &DAG) const { 4344 SDLoc DL(Op); 4345 EVT MaskVT = Op.getValueType(); 4346 // Only expect to custom-lower truncations to mask types 4347 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4348 "Unexpected type for vector mask lowering"); 4349 SDValue Src = Op.getOperand(0); 4350 MVT VecVT = Src.getSimpleValueType(); 4351 4352 // If this is a fixed vector, we need to convert it to a scalable vector. 4353 MVT ContainerVT = VecVT; 4354 if (VecVT.isFixedLengthVector()) { 4355 ContainerVT = getContainerForFixedLengthVector(VecVT); 4356 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4357 } 4358 4359 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4360 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4361 4362 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4363 DAG.getUNDEF(ContainerVT), SplatOne); 4364 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4365 DAG.getUNDEF(ContainerVT), SplatZero); 4366 4367 if (VecVT.isScalableVector()) { 4368 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4369 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4370 } 4371 4372 SDValue Mask, VL; 4373 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4374 4375 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4376 SDValue Trunc = 4377 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4378 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4379 DAG.getCondCode(ISD::SETNE), Mask, VL); 4380 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4381 } 4382 4383 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4384 // first position of a vector, and that vector is slid up to the insert index. 4385 // By limiting the active vector length to index+1 and merging with the 4386 // original vector (with an undisturbed tail policy for elements >= VL), we 4387 // achieve the desired result of leaving all elements untouched except the one 4388 // at VL-1, which is replaced with the desired value. 4389 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4390 SelectionDAG &DAG) const { 4391 SDLoc DL(Op); 4392 MVT VecVT = Op.getSimpleValueType(); 4393 SDValue Vec = Op.getOperand(0); 4394 SDValue Val = Op.getOperand(1); 4395 SDValue Idx = Op.getOperand(2); 4396 4397 if (VecVT.getVectorElementType() == MVT::i1) { 4398 // FIXME: For now we just promote to an i8 vector and insert into that, 4399 // but this is probably not optimal. 4400 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4401 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4402 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4403 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4404 } 4405 4406 MVT ContainerVT = VecVT; 4407 // If the operand is a fixed-length vector, convert to a scalable one. 4408 if (VecVT.isFixedLengthVector()) { 4409 ContainerVT = getContainerForFixedLengthVector(VecVT); 4410 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4411 } 4412 4413 MVT XLenVT = Subtarget.getXLenVT(); 4414 4415 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4416 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4417 // Even i64-element vectors on RV32 can be lowered without scalar 4418 // legalization if the most-significant 32 bits of the value are not affected 4419 // by the sign-extension of the lower 32 bits. 4420 // TODO: We could also catch sign extensions of a 32-bit value. 4421 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4422 const auto *CVal = cast<ConstantSDNode>(Val); 4423 if (isInt<32>(CVal->getSExtValue())) { 4424 IsLegalInsert = true; 4425 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4426 } 4427 } 4428 4429 SDValue Mask, VL; 4430 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4431 4432 SDValue ValInVec; 4433 4434 if (IsLegalInsert) { 4435 unsigned Opc = 4436 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4437 if (isNullConstant(Idx)) { 4438 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4439 if (!VecVT.isFixedLengthVector()) 4440 return Vec; 4441 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4442 } 4443 ValInVec = 4444 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4445 } else { 4446 // On RV32, i64-element vectors must be specially handled to place the 4447 // value at element 0, by using two vslide1up instructions in sequence on 4448 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4449 // this. 4450 SDValue One = DAG.getConstant(1, DL, XLenVT); 4451 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4452 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4453 MVT I32ContainerVT = 4454 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4455 SDValue I32Mask = 4456 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4457 // Limit the active VL to two. 4458 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4459 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4460 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4461 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4462 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4463 // First slide in the hi value, then the lo in underneath it. 4464 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4465 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4466 I32Mask, InsertI64VL); 4467 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4468 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4469 I32Mask, InsertI64VL); 4470 // Bitcast back to the right container type. 4471 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4472 } 4473 4474 // Now that the value is in a vector, slide it into position. 4475 SDValue InsertVL = 4476 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4477 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4478 ValInVec, Idx, Mask, InsertVL); 4479 if (!VecVT.isFixedLengthVector()) 4480 return Slideup; 4481 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4482 } 4483 4484 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4485 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4486 // types this is done using VMV_X_S to allow us to glean information about the 4487 // sign bits of the result. 4488 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4489 SelectionDAG &DAG) const { 4490 SDLoc DL(Op); 4491 SDValue Idx = Op.getOperand(1); 4492 SDValue Vec = Op.getOperand(0); 4493 EVT EltVT = Op.getValueType(); 4494 MVT VecVT = Vec.getSimpleValueType(); 4495 MVT XLenVT = Subtarget.getXLenVT(); 4496 4497 if (VecVT.getVectorElementType() == MVT::i1) { 4498 if (VecVT.isFixedLengthVector()) { 4499 unsigned NumElts = VecVT.getVectorNumElements(); 4500 if (NumElts >= 8) { 4501 MVT WideEltVT; 4502 unsigned WidenVecLen; 4503 SDValue ExtractElementIdx; 4504 SDValue ExtractBitIdx; 4505 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4506 MVT LargestEltVT = MVT::getIntegerVT( 4507 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4508 if (NumElts <= LargestEltVT.getSizeInBits()) { 4509 assert(isPowerOf2_32(NumElts) && 4510 "the number of elements should be power of 2"); 4511 WideEltVT = MVT::getIntegerVT(NumElts); 4512 WidenVecLen = 1; 4513 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4514 ExtractBitIdx = Idx; 4515 } else { 4516 WideEltVT = LargestEltVT; 4517 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4518 // extract element index = index / element width 4519 ExtractElementIdx = DAG.getNode( 4520 ISD::SRL, DL, XLenVT, Idx, 4521 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4522 // mask bit index = index % element width 4523 ExtractBitIdx = DAG.getNode( 4524 ISD::AND, DL, XLenVT, Idx, 4525 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4526 } 4527 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4528 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4529 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4530 Vec, ExtractElementIdx); 4531 // Extract the bit from GPR. 4532 SDValue ShiftRight = 4533 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4534 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4535 DAG.getConstant(1, DL, XLenVT)); 4536 } 4537 } 4538 // Otherwise, promote to an i8 vector and extract from that. 4539 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4540 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4541 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4542 } 4543 4544 // If this is a fixed vector, we need to convert it to a scalable vector. 4545 MVT ContainerVT = VecVT; 4546 if (VecVT.isFixedLengthVector()) { 4547 ContainerVT = getContainerForFixedLengthVector(VecVT); 4548 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4549 } 4550 4551 // If the index is 0, the vector is already in the right position. 4552 if (!isNullConstant(Idx)) { 4553 // Use a VL of 1 to avoid processing more elements than we need. 4554 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4555 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4556 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4557 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4558 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4559 } 4560 4561 if (!EltVT.isInteger()) { 4562 // Floating-point extracts are handled in TableGen. 4563 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4564 DAG.getConstant(0, DL, XLenVT)); 4565 } 4566 4567 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4568 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4569 } 4570 4571 // Some RVV intrinsics may claim that they want an integer operand to be 4572 // promoted or expanded. 4573 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4574 const RISCVSubtarget &Subtarget) { 4575 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4576 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4577 "Unexpected opcode"); 4578 4579 if (!Subtarget.hasVInstructions()) 4580 return SDValue(); 4581 4582 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4583 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4584 SDLoc DL(Op); 4585 4586 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4587 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4588 if (!II || !II->hasScalarOperand()) 4589 return SDValue(); 4590 4591 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4592 assert(SplatOp < Op.getNumOperands()); 4593 4594 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4595 SDValue &ScalarOp = Operands[SplatOp]; 4596 MVT OpVT = ScalarOp.getSimpleValueType(); 4597 MVT XLenVT = Subtarget.getXLenVT(); 4598 4599 // If this isn't a scalar, or its type is XLenVT we're done. 4600 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4601 return SDValue(); 4602 4603 // Simplest case is that the operand needs to be promoted to XLenVT. 4604 if (OpVT.bitsLT(XLenVT)) { 4605 // If the operand is a constant, sign extend to increase our chances 4606 // of being able to use a .vi instruction. ANY_EXTEND would become a 4607 // a zero extend and the simm5 check in isel would fail. 4608 // FIXME: Should we ignore the upper bits in isel instead? 4609 unsigned ExtOpc = 4610 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4611 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4612 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4613 } 4614 4615 // Use the previous operand to get the vXi64 VT. The result might be a mask 4616 // VT for compares. Using the previous operand assumes that the previous 4617 // operand will never have a smaller element size than a scalar operand and 4618 // that a widening operation never uses SEW=64. 4619 // NOTE: If this fails the below assert, we can probably just find the 4620 // element count from any operand or result and use it to construct the VT. 4621 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4622 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4623 4624 // The more complex case is when the scalar is larger than XLenVT. 4625 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4626 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4627 4628 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4629 // instruction to sign-extend since SEW>XLEN. 4630 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4631 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4632 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4633 } 4634 4635 switch (IntNo) { 4636 case Intrinsic::riscv_vslide1up: 4637 case Intrinsic::riscv_vslide1down: 4638 case Intrinsic::riscv_vslide1up_mask: 4639 case Intrinsic::riscv_vslide1down_mask: { 4640 // We need to special case these when the scalar is larger than XLen. 4641 unsigned NumOps = Op.getNumOperands(); 4642 bool IsMasked = NumOps == 7; 4643 4644 // Convert the vector source to the equivalent nxvXi32 vector. 4645 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4646 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4647 4648 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4649 DAG.getConstant(0, DL, XLenVT)); 4650 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4651 DAG.getConstant(1, DL, XLenVT)); 4652 4653 // Double the VL since we halved SEW. 4654 SDValue AVL = getVLOperand(Op); 4655 SDValue I32VL; 4656 4657 // Optimize for constant AVL 4658 if (isa<ConstantSDNode>(AVL)) { 4659 unsigned EltSize = VT.getScalarSizeInBits(); 4660 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4661 4662 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4663 unsigned MaxVLMAX = 4664 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4665 4666 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4667 unsigned MinVLMAX = 4668 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4669 4670 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4671 if (AVLInt <= MinVLMAX) { 4672 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4673 } else if (AVLInt >= 2 * MaxVLMAX) { 4674 // Just set vl to VLMAX in this situation 4675 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4676 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4677 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4678 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4679 SDValue SETVLMAX = DAG.getTargetConstant( 4680 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4681 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4682 LMUL); 4683 } else { 4684 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4685 // is related to the hardware implementation. 4686 // So let the following code handle 4687 } 4688 } 4689 if (!I32VL) { 4690 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4691 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4692 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4693 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4694 SDValue SETVL = 4695 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4696 // Using vsetvli instruction to get actually used length which related to 4697 // the hardware implementation 4698 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4699 SEW, LMUL); 4700 I32VL = 4701 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4702 } 4703 4704 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4705 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL); 4706 4707 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4708 // instructions. 4709 SDValue Passthru; 4710 if (IsMasked) 4711 Passthru = DAG.getUNDEF(I32VT); 4712 else 4713 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4714 4715 if (IntNo == Intrinsic::riscv_vslide1up || 4716 IntNo == Intrinsic::riscv_vslide1up_mask) { 4717 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4718 ScalarHi, I32Mask, I32VL); 4719 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4720 ScalarLo, I32Mask, I32VL); 4721 } else { 4722 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4723 ScalarLo, I32Mask, I32VL); 4724 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4725 ScalarHi, I32Mask, I32VL); 4726 } 4727 4728 // Convert back to nxvXi64. 4729 Vec = DAG.getBitcast(VT, Vec); 4730 4731 if (!IsMasked) 4732 return Vec; 4733 // Apply mask after the operation. 4734 SDValue Mask = Operands[NumOps - 3]; 4735 SDValue MaskedOff = Operands[1]; 4736 // Assume Policy operand is the last operand. 4737 uint64_t Policy = 4738 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4739 // We don't need to select maskedoff if it's undef. 4740 if (MaskedOff.isUndef()) 4741 return Vec; 4742 // TAMU 4743 if (Policy == RISCVII::TAIL_AGNOSTIC) 4744 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4745 AVL); 4746 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4747 // It's fine because vmerge does not care mask policy. 4748 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4749 AVL); 4750 } 4751 } 4752 4753 // We need to convert the scalar to a splat vector. 4754 SDValue VL = getVLOperand(Op); 4755 assert(VL.getValueType() == XLenVT); 4756 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4757 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4758 } 4759 4760 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4761 SelectionDAG &DAG) const { 4762 unsigned IntNo = Op.getConstantOperandVal(0); 4763 SDLoc DL(Op); 4764 MVT XLenVT = Subtarget.getXLenVT(); 4765 4766 switch (IntNo) { 4767 default: 4768 break; // Don't custom lower most intrinsics. 4769 case Intrinsic::thread_pointer: { 4770 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4771 return DAG.getRegister(RISCV::X4, PtrVT); 4772 } 4773 case Intrinsic::riscv_orc_b: 4774 case Intrinsic::riscv_brev8: { 4775 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4776 unsigned Opc = 4777 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4778 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4779 DAG.getConstant(7, DL, XLenVT)); 4780 } 4781 case Intrinsic::riscv_grev: 4782 case Intrinsic::riscv_gorc: { 4783 unsigned Opc = 4784 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4785 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4786 } 4787 case Intrinsic::riscv_zip: 4788 case Intrinsic::riscv_unzip: { 4789 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4790 // For i32 the immediate is 15. For i64 the immediate is 31. 4791 unsigned Opc = 4792 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4793 unsigned BitWidth = Op.getValueSizeInBits(); 4794 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4795 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4796 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4797 } 4798 case Intrinsic::riscv_shfl: 4799 case Intrinsic::riscv_unshfl: { 4800 unsigned Opc = 4801 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4802 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4803 } 4804 case Intrinsic::riscv_bcompress: 4805 case Intrinsic::riscv_bdecompress: { 4806 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4807 : RISCVISD::BDECOMPRESS; 4808 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4809 } 4810 case Intrinsic::riscv_bfp: 4811 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4812 Op.getOperand(2)); 4813 case Intrinsic::riscv_fsl: 4814 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4815 Op.getOperand(2), Op.getOperand(3)); 4816 case Intrinsic::riscv_fsr: 4817 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4818 Op.getOperand(2), Op.getOperand(3)); 4819 case Intrinsic::riscv_vmv_x_s: 4820 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4821 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4822 Op.getOperand(1)); 4823 case Intrinsic::riscv_vmv_v_x: 4824 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4825 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4826 Subtarget); 4827 case Intrinsic::riscv_vfmv_v_f: 4828 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4829 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4830 case Intrinsic::riscv_vmv_s_x: { 4831 SDValue Scalar = Op.getOperand(2); 4832 4833 if (Scalar.getValueType().bitsLE(XLenVT)) { 4834 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4835 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4836 Op.getOperand(1), Scalar, Op.getOperand(3)); 4837 } 4838 4839 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4840 4841 // This is an i64 value that lives in two scalar registers. We have to 4842 // insert this in a convoluted way. First we build vXi64 splat containing 4843 // the two values that we assemble using some bit math. Next we'll use 4844 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4845 // to merge element 0 from our splat into the source vector. 4846 // FIXME: This is probably not the best way to do this, but it is 4847 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4848 // point. 4849 // sw lo, (a0) 4850 // sw hi, 4(a0) 4851 // vlse vX, (a0) 4852 // 4853 // vid.v vVid 4854 // vmseq.vx mMask, vVid, 0 4855 // vmerge.vvm vDest, vSrc, vVal, mMask 4856 MVT VT = Op.getSimpleValueType(); 4857 SDValue Vec = Op.getOperand(1); 4858 SDValue VL = getVLOperand(Op); 4859 4860 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4861 if (Op.getOperand(1).isUndef()) 4862 return SplattedVal; 4863 SDValue SplattedIdx = 4864 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4865 DAG.getConstant(0, DL, MVT::i32), VL); 4866 4867 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4868 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4869 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4870 SDValue SelectCond = 4871 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4872 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4873 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4874 Vec, VL); 4875 } 4876 } 4877 4878 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4879 } 4880 4881 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4882 SelectionDAG &DAG) const { 4883 unsigned IntNo = Op.getConstantOperandVal(1); 4884 switch (IntNo) { 4885 default: 4886 break; 4887 case Intrinsic::riscv_masked_strided_load: { 4888 SDLoc DL(Op); 4889 MVT XLenVT = Subtarget.getXLenVT(); 4890 4891 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4892 // the selection of the masked intrinsics doesn't do this for us. 4893 SDValue Mask = Op.getOperand(5); 4894 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4895 4896 MVT VT = Op->getSimpleValueType(0); 4897 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4898 4899 SDValue PassThru = Op.getOperand(2); 4900 if (!IsUnmasked) { 4901 MVT MaskVT = 4902 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4903 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4904 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4905 } 4906 4907 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4908 4909 SDValue IntID = DAG.getTargetConstant( 4910 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4911 XLenVT); 4912 4913 auto *Load = cast<MemIntrinsicSDNode>(Op); 4914 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4915 if (IsUnmasked) 4916 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4917 else 4918 Ops.push_back(PassThru); 4919 Ops.push_back(Op.getOperand(3)); // Ptr 4920 Ops.push_back(Op.getOperand(4)); // Stride 4921 if (!IsUnmasked) 4922 Ops.push_back(Mask); 4923 Ops.push_back(VL); 4924 if (!IsUnmasked) { 4925 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4926 Ops.push_back(Policy); 4927 } 4928 4929 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4930 SDValue Result = 4931 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4932 Load->getMemoryVT(), Load->getMemOperand()); 4933 SDValue Chain = Result.getValue(1); 4934 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4935 return DAG.getMergeValues({Result, Chain}, DL); 4936 } 4937 case Intrinsic::riscv_seg2_load: 4938 case Intrinsic::riscv_seg3_load: 4939 case Intrinsic::riscv_seg4_load: 4940 case Intrinsic::riscv_seg5_load: 4941 case Intrinsic::riscv_seg6_load: 4942 case Intrinsic::riscv_seg7_load: 4943 case Intrinsic::riscv_seg8_load: { 4944 SDLoc DL(Op); 4945 static const Intrinsic::ID VlsegInts[7] = { 4946 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4947 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4948 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4949 Intrinsic::riscv_vlseg8}; 4950 unsigned NF = Op->getNumValues() - 1; 4951 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4952 MVT XLenVT = Subtarget.getXLenVT(); 4953 MVT VT = Op->getSimpleValueType(0); 4954 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4955 4956 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4957 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4958 auto *Load = cast<MemIntrinsicSDNode>(Op); 4959 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4960 ContainerVTs.push_back(MVT::Other); 4961 SDVTList VTs = DAG.getVTList(ContainerVTs); 4962 SDValue Result = 4963 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4964 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4965 Load->getMemoryVT(), Load->getMemOperand()); 4966 SmallVector<SDValue, 9> Results; 4967 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4968 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4969 DAG, Subtarget)); 4970 Results.push_back(Result.getValue(NF)); 4971 return DAG.getMergeValues(Results, DL); 4972 } 4973 } 4974 4975 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4976 } 4977 4978 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4979 SelectionDAG &DAG) const { 4980 unsigned IntNo = Op.getConstantOperandVal(1); 4981 switch (IntNo) { 4982 default: 4983 break; 4984 case Intrinsic::riscv_masked_strided_store: { 4985 SDLoc DL(Op); 4986 MVT XLenVT = Subtarget.getXLenVT(); 4987 4988 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4989 // the selection of the masked intrinsics doesn't do this for us. 4990 SDValue Mask = Op.getOperand(5); 4991 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4992 4993 SDValue Val = Op.getOperand(2); 4994 MVT VT = Val.getSimpleValueType(); 4995 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4996 4997 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4998 if (!IsUnmasked) { 4999 MVT MaskVT = 5000 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5001 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5002 } 5003 5004 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5005 5006 SDValue IntID = DAG.getTargetConstant( 5007 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5008 XLenVT); 5009 5010 auto *Store = cast<MemIntrinsicSDNode>(Op); 5011 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5012 Ops.push_back(Val); 5013 Ops.push_back(Op.getOperand(3)); // Ptr 5014 Ops.push_back(Op.getOperand(4)); // Stride 5015 if (!IsUnmasked) 5016 Ops.push_back(Mask); 5017 Ops.push_back(VL); 5018 5019 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5020 Ops, Store->getMemoryVT(), 5021 Store->getMemOperand()); 5022 } 5023 } 5024 5025 return SDValue(); 5026 } 5027 5028 static MVT getLMUL1VT(MVT VT) { 5029 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5030 "Unexpected vector MVT"); 5031 return MVT::getScalableVectorVT( 5032 VT.getVectorElementType(), 5033 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5034 } 5035 5036 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5037 switch (ISDOpcode) { 5038 default: 5039 llvm_unreachable("Unhandled reduction"); 5040 case ISD::VECREDUCE_ADD: 5041 return RISCVISD::VECREDUCE_ADD_VL; 5042 case ISD::VECREDUCE_UMAX: 5043 return RISCVISD::VECREDUCE_UMAX_VL; 5044 case ISD::VECREDUCE_SMAX: 5045 return RISCVISD::VECREDUCE_SMAX_VL; 5046 case ISD::VECREDUCE_UMIN: 5047 return RISCVISD::VECREDUCE_UMIN_VL; 5048 case ISD::VECREDUCE_SMIN: 5049 return RISCVISD::VECREDUCE_SMIN_VL; 5050 case ISD::VECREDUCE_AND: 5051 return RISCVISD::VECREDUCE_AND_VL; 5052 case ISD::VECREDUCE_OR: 5053 return RISCVISD::VECREDUCE_OR_VL; 5054 case ISD::VECREDUCE_XOR: 5055 return RISCVISD::VECREDUCE_XOR_VL; 5056 } 5057 } 5058 5059 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5060 SelectionDAG &DAG, 5061 bool IsVP) const { 5062 SDLoc DL(Op); 5063 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5064 MVT VecVT = Vec.getSimpleValueType(); 5065 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5066 Op.getOpcode() == ISD::VECREDUCE_OR || 5067 Op.getOpcode() == ISD::VECREDUCE_XOR || 5068 Op.getOpcode() == ISD::VP_REDUCE_AND || 5069 Op.getOpcode() == ISD::VP_REDUCE_OR || 5070 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5071 "Unexpected reduction lowering"); 5072 5073 MVT XLenVT = Subtarget.getXLenVT(); 5074 assert(Op.getValueType() == XLenVT && 5075 "Expected reduction output to be legalized to XLenVT"); 5076 5077 MVT ContainerVT = VecVT; 5078 if (VecVT.isFixedLengthVector()) { 5079 ContainerVT = getContainerForFixedLengthVector(VecVT); 5080 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5081 } 5082 5083 SDValue Mask, VL; 5084 if (IsVP) { 5085 Mask = Op.getOperand(2); 5086 VL = Op.getOperand(3); 5087 } else { 5088 std::tie(Mask, VL) = 5089 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5090 } 5091 5092 unsigned BaseOpc; 5093 ISD::CondCode CC; 5094 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5095 5096 switch (Op.getOpcode()) { 5097 default: 5098 llvm_unreachable("Unhandled reduction"); 5099 case ISD::VECREDUCE_AND: 5100 case ISD::VP_REDUCE_AND: { 5101 // vcpop ~x == 0 5102 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5103 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5104 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5105 CC = ISD::SETEQ; 5106 BaseOpc = ISD::AND; 5107 break; 5108 } 5109 case ISD::VECREDUCE_OR: 5110 case ISD::VP_REDUCE_OR: 5111 // vcpop x != 0 5112 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5113 CC = ISD::SETNE; 5114 BaseOpc = ISD::OR; 5115 break; 5116 case ISD::VECREDUCE_XOR: 5117 case ISD::VP_REDUCE_XOR: { 5118 // ((vcpop x) & 1) != 0 5119 SDValue One = DAG.getConstant(1, DL, XLenVT); 5120 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5121 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5122 CC = ISD::SETNE; 5123 BaseOpc = ISD::XOR; 5124 break; 5125 } 5126 } 5127 5128 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5129 5130 if (!IsVP) 5131 return SetCC; 5132 5133 // Now include the start value in the operation. 5134 // Note that we must return the start value when no elements are operated 5135 // upon. The vcpop instructions we've emitted in each case above will return 5136 // 0 for an inactive vector, and so we've already received the neutral value: 5137 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5138 // can simply include the start value. 5139 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5140 } 5141 5142 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5143 SelectionDAG &DAG) const { 5144 SDLoc DL(Op); 5145 SDValue Vec = Op.getOperand(0); 5146 EVT VecEVT = Vec.getValueType(); 5147 5148 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5149 5150 // Due to ordering in legalize types we may have a vector type that needs to 5151 // be split. Do that manually so we can get down to a legal type. 5152 while (getTypeAction(*DAG.getContext(), VecEVT) == 5153 TargetLowering::TypeSplitVector) { 5154 SDValue Lo, Hi; 5155 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5156 VecEVT = Lo.getValueType(); 5157 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5158 } 5159 5160 // TODO: The type may need to be widened rather than split. Or widened before 5161 // it can be split. 5162 if (!isTypeLegal(VecEVT)) 5163 return SDValue(); 5164 5165 MVT VecVT = VecEVT.getSimpleVT(); 5166 MVT VecEltVT = VecVT.getVectorElementType(); 5167 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5168 5169 MVT ContainerVT = VecVT; 5170 if (VecVT.isFixedLengthVector()) { 5171 ContainerVT = getContainerForFixedLengthVector(VecVT); 5172 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5173 } 5174 5175 MVT M1VT = getLMUL1VT(ContainerVT); 5176 MVT XLenVT = Subtarget.getXLenVT(); 5177 5178 SDValue Mask, VL; 5179 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5180 5181 SDValue NeutralElem = 5182 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5183 SDValue IdentitySplat = 5184 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5185 M1VT, DL, DAG, Subtarget); 5186 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5187 IdentitySplat, Mask, VL); 5188 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5189 DAG.getConstant(0, DL, XLenVT)); 5190 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5191 } 5192 5193 // Given a reduction op, this function returns the matching reduction opcode, 5194 // the vector SDValue and the scalar SDValue required to lower this to a 5195 // RISCVISD node. 5196 static std::tuple<unsigned, SDValue, SDValue> 5197 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5198 SDLoc DL(Op); 5199 auto Flags = Op->getFlags(); 5200 unsigned Opcode = Op.getOpcode(); 5201 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5202 switch (Opcode) { 5203 default: 5204 llvm_unreachable("Unhandled reduction"); 5205 case ISD::VECREDUCE_FADD: { 5206 // Use positive zero if we can. It is cheaper to materialize. 5207 SDValue Zero = 5208 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5209 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5210 } 5211 case ISD::VECREDUCE_SEQ_FADD: 5212 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5213 Op.getOperand(0)); 5214 case ISD::VECREDUCE_FMIN: 5215 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5216 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5217 case ISD::VECREDUCE_FMAX: 5218 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5219 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5220 } 5221 } 5222 5223 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5224 SelectionDAG &DAG) const { 5225 SDLoc DL(Op); 5226 MVT VecEltVT = Op.getSimpleValueType(); 5227 5228 unsigned RVVOpcode; 5229 SDValue VectorVal, ScalarVal; 5230 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5231 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5232 MVT VecVT = VectorVal.getSimpleValueType(); 5233 5234 MVT ContainerVT = VecVT; 5235 if (VecVT.isFixedLengthVector()) { 5236 ContainerVT = getContainerForFixedLengthVector(VecVT); 5237 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5238 } 5239 5240 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5241 MVT XLenVT = Subtarget.getXLenVT(); 5242 5243 SDValue Mask, VL; 5244 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5245 5246 SDValue ScalarSplat = 5247 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5248 M1VT, DL, DAG, Subtarget); 5249 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5250 VectorVal, ScalarSplat, Mask, VL); 5251 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5252 DAG.getConstant(0, DL, XLenVT)); 5253 } 5254 5255 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5256 switch (ISDOpcode) { 5257 default: 5258 llvm_unreachable("Unhandled reduction"); 5259 case ISD::VP_REDUCE_ADD: 5260 return RISCVISD::VECREDUCE_ADD_VL; 5261 case ISD::VP_REDUCE_UMAX: 5262 return RISCVISD::VECREDUCE_UMAX_VL; 5263 case ISD::VP_REDUCE_SMAX: 5264 return RISCVISD::VECREDUCE_SMAX_VL; 5265 case ISD::VP_REDUCE_UMIN: 5266 return RISCVISD::VECREDUCE_UMIN_VL; 5267 case ISD::VP_REDUCE_SMIN: 5268 return RISCVISD::VECREDUCE_SMIN_VL; 5269 case ISD::VP_REDUCE_AND: 5270 return RISCVISD::VECREDUCE_AND_VL; 5271 case ISD::VP_REDUCE_OR: 5272 return RISCVISD::VECREDUCE_OR_VL; 5273 case ISD::VP_REDUCE_XOR: 5274 return RISCVISD::VECREDUCE_XOR_VL; 5275 case ISD::VP_REDUCE_FADD: 5276 return RISCVISD::VECREDUCE_FADD_VL; 5277 case ISD::VP_REDUCE_SEQ_FADD: 5278 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5279 case ISD::VP_REDUCE_FMAX: 5280 return RISCVISD::VECREDUCE_FMAX_VL; 5281 case ISD::VP_REDUCE_FMIN: 5282 return RISCVISD::VECREDUCE_FMIN_VL; 5283 } 5284 } 5285 5286 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5287 SelectionDAG &DAG) const { 5288 SDLoc DL(Op); 5289 SDValue Vec = Op.getOperand(1); 5290 EVT VecEVT = Vec.getValueType(); 5291 5292 // TODO: The type may need to be widened rather than split. Or widened before 5293 // it can be split. 5294 if (!isTypeLegal(VecEVT)) 5295 return SDValue(); 5296 5297 MVT VecVT = VecEVT.getSimpleVT(); 5298 MVT VecEltVT = VecVT.getVectorElementType(); 5299 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5300 5301 MVT ContainerVT = VecVT; 5302 if (VecVT.isFixedLengthVector()) { 5303 ContainerVT = getContainerForFixedLengthVector(VecVT); 5304 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5305 } 5306 5307 SDValue VL = Op.getOperand(3); 5308 SDValue Mask = Op.getOperand(2); 5309 5310 MVT M1VT = getLMUL1VT(ContainerVT); 5311 MVT XLenVT = Subtarget.getXLenVT(); 5312 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5313 5314 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5315 DAG.getConstant(1, DL, XLenVT), M1VT, 5316 DL, DAG, Subtarget); 5317 SDValue Reduction = 5318 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5319 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5320 DAG.getConstant(0, DL, XLenVT)); 5321 if (!VecVT.isInteger()) 5322 return Elt0; 5323 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5324 } 5325 5326 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5327 SelectionDAG &DAG) const { 5328 SDValue Vec = Op.getOperand(0); 5329 SDValue SubVec = Op.getOperand(1); 5330 MVT VecVT = Vec.getSimpleValueType(); 5331 MVT SubVecVT = SubVec.getSimpleValueType(); 5332 5333 SDLoc DL(Op); 5334 MVT XLenVT = Subtarget.getXLenVT(); 5335 unsigned OrigIdx = Op.getConstantOperandVal(2); 5336 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5337 5338 // We don't have the ability to slide mask vectors up indexed by their i1 5339 // elements; the smallest we can do is i8. Often we are able to bitcast to 5340 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5341 // into a scalable one, we might not necessarily have enough scalable 5342 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5343 if (SubVecVT.getVectorElementType() == MVT::i1 && 5344 (OrigIdx != 0 || !Vec.isUndef())) { 5345 if (VecVT.getVectorMinNumElements() >= 8 && 5346 SubVecVT.getVectorMinNumElements() >= 8) { 5347 assert(OrigIdx % 8 == 0 && "Invalid index"); 5348 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5349 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5350 "Unexpected mask vector lowering"); 5351 OrigIdx /= 8; 5352 SubVecVT = 5353 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5354 SubVecVT.isScalableVector()); 5355 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5356 VecVT.isScalableVector()); 5357 Vec = DAG.getBitcast(VecVT, Vec); 5358 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5359 } else { 5360 // We can't slide this mask vector up indexed by its i1 elements. 5361 // This poses a problem when we wish to insert a scalable vector which 5362 // can't be re-expressed as a larger type. Just choose the slow path and 5363 // extend to a larger type, then truncate back down. 5364 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5365 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5366 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5367 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5368 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5369 Op.getOperand(2)); 5370 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5371 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5372 } 5373 } 5374 5375 // If the subvector vector is a fixed-length type, we cannot use subregister 5376 // manipulation to simplify the codegen; we don't know which register of a 5377 // LMUL group contains the specific subvector as we only know the minimum 5378 // register size. Therefore we must slide the vector group up the full 5379 // amount. 5380 if (SubVecVT.isFixedLengthVector()) { 5381 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5382 return Op; 5383 MVT ContainerVT = VecVT; 5384 if (VecVT.isFixedLengthVector()) { 5385 ContainerVT = getContainerForFixedLengthVector(VecVT); 5386 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5387 } 5388 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5389 DAG.getUNDEF(ContainerVT), SubVec, 5390 DAG.getConstant(0, DL, XLenVT)); 5391 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5392 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5393 return DAG.getBitcast(Op.getValueType(), SubVec); 5394 } 5395 SDValue Mask = 5396 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5397 // Set the vector length to only the number of elements we care about. Note 5398 // that for slideup this includes the offset. 5399 SDValue VL = 5400 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5401 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5402 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5403 SubVec, SlideupAmt, Mask, VL); 5404 if (VecVT.isFixedLengthVector()) 5405 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5406 return DAG.getBitcast(Op.getValueType(), Slideup); 5407 } 5408 5409 unsigned SubRegIdx, RemIdx; 5410 std::tie(SubRegIdx, RemIdx) = 5411 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5412 VecVT, SubVecVT, OrigIdx, TRI); 5413 5414 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5415 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5416 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5417 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5418 5419 // 1. If the Idx has been completely eliminated and this subvector's size is 5420 // a vector register or a multiple thereof, or the surrounding elements are 5421 // undef, then this is a subvector insert which naturally aligns to a vector 5422 // register. These can easily be handled using subregister manipulation. 5423 // 2. If the subvector is smaller than a vector register, then the insertion 5424 // must preserve the undisturbed elements of the register. We do this by 5425 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5426 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5427 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5428 // LMUL=1 type back into the larger vector (resolving to another subregister 5429 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5430 // to avoid allocating a large register group to hold our subvector. 5431 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5432 return Op; 5433 5434 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5435 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5436 // (in our case undisturbed). This means we can set up a subvector insertion 5437 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5438 // size of the subvector. 5439 MVT InterSubVT = VecVT; 5440 SDValue AlignedExtract = Vec; 5441 unsigned AlignedIdx = OrigIdx - RemIdx; 5442 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5443 InterSubVT = getLMUL1VT(VecVT); 5444 // Extract a subvector equal to the nearest full vector register type. This 5445 // should resolve to a EXTRACT_SUBREG instruction. 5446 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5447 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5448 } 5449 5450 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5451 // For scalable vectors this must be further multiplied by vscale. 5452 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5453 5454 SDValue Mask, VL; 5455 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5456 5457 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5458 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5459 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5460 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5461 5462 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5463 DAG.getUNDEF(InterSubVT), SubVec, 5464 DAG.getConstant(0, DL, XLenVT)); 5465 5466 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5467 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5468 5469 // If required, insert this subvector back into the correct vector register. 5470 // This should resolve to an INSERT_SUBREG instruction. 5471 if (VecVT.bitsGT(InterSubVT)) 5472 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5473 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5474 5475 // We might have bitcast from a mask type: cast back to the original type if 5476 // required. 5477 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5478 } 5479 5480 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5481 SelectionDAG &DAG) const { 5482 SDValue Vec = Op.getOperand(0); 5483 MVT SubVecVT = Op.getSimpleValueType(); 5484 MVT VecVT = Vec.getSimpleValueType(); 5485 5486 SDLoc DL(Op); 5487 MVT XLenVT = Subtarget.getXLenVT(); 5488 unsigned OrigIdx = Op.getConstantOperandVal(1); 5489 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5490 5491 // We don't have the ability to slide mask vectors down indexed by their i1 5492 // elements; the smallest we can do is i8. Often we are able to bitcast to 5493 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5494 // from a scalable one, we might not necessarily have enough scalable 5495 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5496 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5497 if (VecVT.getVectorMinNumElements() >= 8 && 5498 SubVecVT.getVectorMinNumElements() >= 8) { 5499 assert(OrigIdx % 8 == 0 && "Invalid index"); 5500 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5501 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5502 "Unexpected mask vector lowering"); 5503 OrigIdx /= 8; 5504 SubVecVT = 5505 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5506 SubVecVT.isScalableVector()); 5507 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5508 VecVT.isScalableVector()); 5509 Vec = DAG.getBitcast(VecVT, Vec); 5510 } else { 5511 // We can't slide this mask vector down, indexed by its i1 elements. 5512 // This poses a problem when we wish to extract a scalable vector which 5513 // can't be re-expressed as a larger type. Just choose the slow path and 5514 // extend to a larger type, then truncate back down. 5515 // TODO: We could probably improve this when extracting certain fixed 5516 // from fixed, where we can extract as i8 and shift the correct element 5517 // right to reach the desired subvector? 5518 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5519 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5520 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5521 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5522 Op.getOperand(1)); 5523 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5524 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5525 } 5526 } 5527 5528 // If the subvector vector is a fixed-length type, we cannot use subregister 5529 // manipulation to simplify the codegen; we don't know which register of a 5530 // LMUL group contains the specific subvector as we only know the minimum 5531 // register size. Therefore we must slide the vector group down the full 5532 // amount. 5533 if (SubVecVT.isFixedLengthVector()) { 5534 // With an index of 0 this is a cast-like subvector, which can be performed 5535 // with subregister operations. 5536 if (OrigIdx == 0) 5537 return Op; 5538 MVT ContainerVT = VecVT; 5539 if (VecVT.isFixedLengthVector()) { 5540 ContainerVT = getContainerForFixedLengthVector(VecVT); 5541 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5542 } 5543 SDValue Mask = 5544 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5545 // Set the vector length to only the number of elements we care about. This 5546 // avoids sliding down elements we're going to discard straight away. 5547 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5548 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5549 SDValue Slidedown = 5550 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5551 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5552 // Now we can use a cast-like subvector extract to get the result. 5553 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5554 DAG.getConstant(0, DL, XLenVT)); 5555 return DAG.getBitcast(Op.getValueType(), Slidedown); 5556 } 5557 5558 unsigned SubRegIdx, RemIdx; 5559 std::tie(SubRegIdx, RemIdx) = 5560 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5561 VecVT, SubVecVT, OrigIdx, TRI); 5562 5563 // If the Idx has been completely eliminated then this is a subvector extract 5564 // which naturally aligns to a vector register. These can easily be handled 5565 // using subregister manipulation. 5566 if (RemIdx == 0) 5567 return Op; 5568 5569 // Else we must shift our vector register directly to extract the subvector. 5570 // Do this using VSLIDEDOWN. 5571 5572 // If the vector type is an LMUL-group type, extract a subvector equal to the 5573 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5574 // instruction. 5575 MVT InterSubVT = VecVT; 5576 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5577 InterSubVT = getLMUL1VT(VecVT); 5578 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5579 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5580 } 5581 5582 // Slide this vector register down by the desired number of elements in order 5583 // to place the desired subvector starting at element 0. 5584 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5585 // For scalable vectors this must be further multiplied by vscale. 5586 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5587 5588 SDValue Mask, VL; 5589 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5590 SDValue Slidedown = 5591 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5592 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5593 5594 // Now the vector is in the right position, extract our final subvector. This 5595 // should resolve to a COPY. 5596 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5597 DAG.getConstant(0, DL, XLenVT)); 5598 5599 // We might have bitcast from a mask type: cast back to the original type if 5600 // required. 5601 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5602 } 5603 5604 // Lower step_vector to the vid instruction. Any non-identity step value must 5605 // be accounted for my manual expansion. 5606 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5607 SelectionDAG &DAG) const { 5608 SDLoc DL(Op); 5609 MVT VT = Op.getSimpleValueType(); 5610 MVT XLenVT = Subtarget.getXLenVT(); 5611 SDValue Mask, VL; 5612 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5613 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5614 uint64_t StepValImm = Op.getConstantOperandVal(0); 5615 if (StepValImm != 1) { 5616 if (isPowerOf2_64(StepValImm)) { 5617 SDValue StepVal = 5618 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5619 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5620 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5621 } else { 5622 SDValue StepVal = lowerScalarSplat( 5623 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5624 VL, VT, DL, DAG, Subtarget); 5625 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5626 } 5627 } 5628 return StepVec; 5629 } 5630 5631 // Implement vector_reverse using vrgather.vv with indices determined by 5632 // subtracting the id of each element from (VLMAX-1). This will convert 5633 // the indices like so: 5634 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5635 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5636 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5637 SelectionDAG &DAG) const { 5638 SDLoc DL(Op); 5639 MVT VecVT = Op.getSimpleValueType(); 5640 unsigned EltSize = VecVT.getScalarSizeInBits(); 5641 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5642 5643 unsigned MaxVLMAX = 0; 5644 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5645 if (VectorBitsMax != 0) 5646 MaxVLMAX = 5647 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5648 5649 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5650 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5651 5652 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5653 // to use vrgatherei16.vv. 5654 // TODO: It's also possible to use vrgatherei16.vv for other types to 5655 // decrease register width for the index calculation. 5656 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5657 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5658 // Reverse each half, then reassemble them in reverse order. 5659 // NOTE: It's also possible that after splitting that VLMAX no longer 5660 // requires vrgatherei16.vv. 5661 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5662 SDValue Lo, Hi; 5663 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5664 EVT LoVT, HiVT; 5665 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5666 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5667 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5668 // Reassemble the low and high pieces reversed. 5669 // FIXME: This is a CONCAT_VECTORS. 5670 SDValue Res = 5671 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5672 DAG.getIntPtrConstant(0, DL)); 5673 return DAG.getNode( 5674 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5675 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5676 } 5677 5678 // Just promote the int type to i16 which will double the LMUL. 5679 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5680 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5681 } 5682 5683 MVT XLenVT = Subtarget.getXLenVT(); 5684 SDValue Mask, VL; 5685 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5686 5687 // Calculate VLMAX-1 for the desired SEW. 5688 unsigned MinElts = VecVT.getVectorMinNumElements(); 5689 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5690 DAG.getConstant(MinElts, DL, XLenVT)); 5691 SDValue VLMinus1 = 5692 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5693 5694 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5695 bool IsRV32E64 = 5696 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5697 SDValue SplatVL; 5698 if (!IsRV32E64) 5699 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5700 else 5701 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5702 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5703 5704 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5705 SDValue Indices = 5706 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5707 5708 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5709 } 5710 5711 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5712 SelectionDAG &DAG) const { 5713 SDLoc DL(Op); 5714 SDValue V1 = Op.getOperand(0); 5715 SDValue V2 = Op.getOperand(1); 5716 MVT XLenVT = Subtarget.getXLenVT(); 5717 MVT VecVT = Op.getSimpleValueType(); 5718 5719 unsigned MinElts = VecVT.getVectorMinNumElements(); 5720 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5721 DAG.getConstant(MinElts, DL, XLenVT)); 5722 5723 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5724 SDValue DownOffset, UpOffset; 5725 if (ImmValue >= 0) { 5726 // The operand is a TargetConstant, we need to rebuild it as a regular 5727 // constant. 5728 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5729 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5730 } else { 5731 // The operand is a TargetConstant, we need to rebuild it as a regular 5732 // constant rather than negating the original operand. 5733 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5734 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5735 } 5736 5737 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5738 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5739 5740 SDValue SlideDown = 5741 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5742 DownOffset, TrueMask, UpOffset); 5743 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5744 TrueMask, 5745 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5746 } 5747 5748 SDValue 5749 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5750 SelectionDAG &DAG) const { 5751 SDLoc DL(Op); 5752 auto *Load = cast<LoadSDNode>(Op); 5753 5754 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5755 Load->getMemoryVT(), 5756 *Load->getMemOperand()) && 5757 "Expecting a correctly-aligned load"); 5758 5759 MVT VT = Op.getSimpleValueType(); 5760 MVT XLenVT = Subtarget.getXLenVT(); 5761 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5762 5763 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5764 5765 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5766 SDValue IntID = DAG.getTargetConstant( 5767 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5768 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5769 if (!IsMaskOp) 5770 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5771 Ops.push_back(Load->getBasePtr()); 5772 Ops.push_back(VL); 5773 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5774 SDValue NewLoad = 5775 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5776 Load->getMemoryVT(), Load->getMemOperand()); 5777 5778 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5779 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5780 } 5781 5782 SDValue 5783 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5784 SelectionDAG &DAG) const { 5785 SDLoc DL(Op); 5786 auto *Store = cast<StoreSDNode>(Op); 5787 5788 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5789 Store->getMemoryVT(), 5790 *Store->getMemOperand()) && 5791 "Expecting a correctly-aligned store"); 5792 5793 SDValue StoreVal = Store->getValue(); 5794 MVT VT = StoreVal.getSimpleValueType(); 5795 MVT XLenVT = Subtarget.getXLenVT(); 5796 5797 // If the size less than a byte, we need to pad with zeros to make a byte. 5798 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5799 VT = MVT::v8i1; 5800 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5801 DAG.getConstant(0, DL, VT), StoreVal, 5802 DAG.getIntPtrConstant(0, DL)); 5803 } 5804 5805 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5806 5807 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5808 5809 SDValue NewValue = 5810 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5811 5812 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5813 SDValue IntID = DAG.getTargetConstant( 5814 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5815 return DAG.getMemIntrinsicNode( 5816 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5817 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5818 Store->getMemoryVT(), Store->getMemOperand()); 5819 } 5820 5821 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5822 SelectionDAG &DAG) const { 5823 SDLoc DL(Op); 5824 MVT VT = Op.getSimpleValueType(); 5825 5826 const auto *MemSD = cast<MemSDNode>(Op); 5827 EVT MemVT = MemSD->getMemoryVT(); 5828 MachineMemOperand *MMO = MemSD->getMemOperand(); 5829 SDValue Chain = MemSD->getChain(); 5830 SDValue BasePtr = MemSD->getBasePtr(); 5831 5832 SDValue Mask, PassThru, VL; 5833 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5834 Mask = VPLoad->getMask(); 5835 PassThru = DAG.getUNDEF(VT); 5836 VL = VPLoad->getVectorLength(); 5837 } else { 5838 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5839 Mask = MLoad->getMask(); 5840 PassThru = MLoad->getPassThru(); 5841 } 5842 5843 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5844 5845 MVT XLenVT = Subtarget.getXLenVT(); 5846 5847 MVT ContainerVT = VT; 5848 if (VT.isFixedLengthVector()) { 5849 ContainerVT = getContainerForFixedLengthVector(VT); 5850 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5851 if (!IsUnmasked) { 5852 MVT MaskVT = 5853 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 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_vle : Intrinsic::riscv_vle_mask; 5863 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5864 if (IsUnmasked) 5865 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5866 else 5867 Ops.push_back(PassThru); 5868 Ops.push_back(BasePtr); 5869 if (!IsUnmasked) 5870 Ops.push_back(Mask); 5871 Ops.push_back(VL); 5872 if (!IsUnmasked) 5873 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5874 5875 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5876 5877 SDValue Result = 5878 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5879 Chain = Result.getValue(1); 5880 5881 if (VT.isFixedLengthVector()) 5882 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5883 5884 return DAG.getMergeValues({Result, Chain}, DL); 5885 } 5886 5887 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5888 SelectionDAG &DAG) const { 5889 SDLoc DL(Op); 5890 5891 const auto *MemSD = cast<MemSDNode>(Op); 5892 EVT MemVT = MemSD->getMemoryVT(); 5893 MachineMemOperand *MMO = MemSD->getMemOperand(); 5894 SDValue Chain = MemSD->getChain(); 5895 SDValue BasePtr = MemSD->getBasePtr(); 5896 SDValue Val, Mask, VL; 5897 5898 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5899 Val = VPStore->getValue(); 5900 Mask = VPStore->getMask(); 5901 VL = VPStore->getVectorLength(); 5902 } else { 5903 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5904 Val = MStore->getValue(); 5905 Mask = MStore->getMask(); 5906 } 5907 5908 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5909 5910 MVT VT = Val.getSimpleValueType(); 5911 MVT XLenVT = Subtarget.getXLenVT(); 5912 5913 MVT ContainerVT = VT; 5914 if (VT.isFixedLengthVector()) { 5915 ContainerVT = getContainerForFixedLengthVector(VT); 5916 5917 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5918 if (!IsUnmasked) { 5919 MVT MaskVT = 5920 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5921 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5922 } 5923 } 5924 5925 if (!VL) 5926 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5927 5928 unsigned IntID = 5929 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5930 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5931 Ops.push_back(Val); 5932 Ops.push_back(BasePtr); 5933 if (!IsUnmasked) 5934 Ops.push_back(Mask); 5935 Ops.push_back(VL); 5936 5937 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5938 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5939 } 5940 5941 SDValue 5942 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5943 SelectionDAG &DAG) const { 5944 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5945 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5946 5947 MVT VT = Op.getSimpleValueType(); 5948 5949 SDValue Op1 = 5950 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5951 SDValue Op2 = 5952 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5953 5954 SDLoc DL(Op); 5955 SDValue VL = 5956 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5957 5958 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5959 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5960 5961 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5962 Op.getOperand(2), Mask, VL); 5963 5964 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5965 } 5966 5967 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5968 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5969 MVT VT = Op.getSimpleValueType(); 5970 5971 if (VT.getVectorElementType() == MVT::i1) 5972 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5973 5974 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5975 } 5976 5977 SDValue 5978 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5979 SelectionDAG &DAG) const { 5980 unsigned Opc; 5981 switch (Op.getOpcode()) { 5982 default: llvm_unreachable("Unexpected opcode!"); 5983 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5984 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5985 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5986 } 5987 5988 return lowerToScalableOp(Op, DAG, Opc); 5989 } 5990 5991 // Lower vector ABS to smax(X, sub(0, X)). 5992 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5993 SDLoc DL(Op); 5994 MVT VT = Op.getSimpleValueType(); 5995 SDValue X = Op.getOperand(0); 5996 5997 assert(VT.isFixedLengthVector() && "Unexpected type"); 5998 5999 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6000 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6001 6002 SDValue Mask, VL; 6003 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6004 6005 SDValue SplatZero = DAG.getNode( 6006 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6007 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6008 SDValue NegX = 6009 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6010 SDValue Max = 6011 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6012 6013 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6014 } 6015 6016 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6017 SDValue Op, SelectionDAG &DAG) const { 6018 SDLoc DL(Op); 6019 MVT VT = Op.getSimpleValueType(); 6020 SDValue Mag = Op.getOperand(0); 6021 SDValue Sign = Op.getOperand(1); 6022 assert(Mag.getValueType() == Sign.getValueType() && 6023 "Can only handle COPYSIGN with matching types."); 6024 6025 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6026 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6027 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6028 6029 SDValue Mask, VL; 6030 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6031 6032 SDValue CopySign = 6033 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6034 6035 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6036 } 6037 6038 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6039 SDValue Op, SelectionDAG &DAG) const { 6040 MVT VT = Op.getSimpleValueType(); 6041 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6042 6043 MVT I1ContainerVT = 6044 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6045 6046 SDValue CC = 6047 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6048 SDValue Op1 = 6049 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6050 SDValue Op2 = 6051 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6052 6053 SDLoc DL(Op); 6054 SDValue Mask, VL; 6055 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6056 6057 SDValue Select = 6058 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6059 6060 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6061 } 6062 6063 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6064 unsigned NewOpc, 6065 bool HasMask) const { 6066 MVT VT = Op.getSimpleValueType(); 6067 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6068 6069 // Create list of operands by converting existing ones to scalable types. 6070 SmallVector<SDValue, 6> Ops; 6071 for (const SDValue &V : Op->op_values()) { 6072 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6073 6074 // Pass through non-vector operands. 6075 if (!V.getValueType().isVector()) { 6076 Ops.push_back(V); 6077 continue; 6078 } 6079 6080 // "cast" fixed length vector to a scalable vector. 6081 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6082 "Only fixed length vectors are supported!"); 6083 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6084 } 6085 6086 SDLoc DL(Op); 6087 SDValue Mask, VL; 6088 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6089 if (HasMask) 6090 Ops.push_back(Mask); 6091 Ops.push_back(VL); 6092 6093 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6094 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6095 } 6096 6097 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6098 // * Operands of each node are assumed to be in the same order. 6099 // * The EVL operand is promoted from i32 to i64 on RV64. 6100 // * Fixed-length vectors are converted to their scalable-vector container 6101 // types. 6102 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6103 unsigned RISCVISDOpc) const { 6104 SDLoc DL(Op); 6105 MVT VT = Op.getSimpleValueType(); 6106 SmallVector<SDValue, 4> Ops; 6107 6108 for (const auto &OpIdx : enumerate(Op->ops())) { 6109 SDValue V = OpIdx.value(); 6110 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6111 // Pass through operands which aren't fixed-length vectors. 6112 if (!V.getValueType().isFixedLengthVector()) { 6113 Ops.push_back(V); 6114 continue; 6115 } 6116 // "cast" fixed length vector to a scalable vector. 6117 MVT OpVT = V.getSimpleValueType(); 6118 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6119 assert(useRVVForFixedLengthVectorVT(OpVT) && 6120 "Only fixed length vectors are supported!"); 6121 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6122 } 6123 6124 if (!VT.isFixedLengthVector()) 6125 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6126 6127 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6128 6129 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6130 6131 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6132 } 6133 6134 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6135 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6136 unsigned RISCVISDOpc) const { 6137 SDLoc DL(Op); 6138 6139 SDValue Src = Op.getOperand(0); 6140 SDValue Mask = Op.getOperand(1); 6141 SDValue VL = Op.getOperand(2); 6142 6143 MVT DstVT = Op.getSimpleValueType(); 6144 MVT SrcVT = Src.getSimpleValueType(); 6145 if (DstVT.isFixedLengthVector()) { 6146 DstVT = getContainerForFixedLengthVector(DstVT); 6147 SrcVT = getContainerForFixedLengthVector(SrcVT); 6148 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6149 MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount()); 6150 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6151 } 6152 6153 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6154 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6155 ? RISCVISD::VSEXT_VL 6156 : RISCVISD::VZEXT_VL; 6157 6158 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6159 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6160 6161 SDValue Result; 6162 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6163 if (SrcVT.isInteger()) { 6164 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6165 6166 // Do we need to do any pre-widening before converting? 6167 if (SrcEltSize == 1) { 6168 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6169 MVT XLenVT = Subtarget.getXLenVT(); 6170 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6171 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6172 DAG.getUNDEF(IntVT), Zero, VL); 6173 SDValue One = DAG.getConstant( 6174 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6175 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6176 DAG.getUNDEF(IntVT), One, VL); 6177 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6178 ZeroSplat, VL); 6179 } else if (DstEltSize > (2 * SrcEltSize)) { 6180 // Widen before converting. 6181 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6182 DstVT.getVectorElementCount()); 6183 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6184 } 6185 6186 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6187 } else { 6188 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6189 "Wrong input/output vector types"); 6190 6191 // Convert f16 to f32 then convert f32 to i64. 6192 if (DstEltSize > (2 * SrcEltSize)) { 6193 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6194 MVT InterimFVT = 6195 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6196 Src = 6197 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6198 } 6199 6200 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6201 } 6202 } else { // Narrowing + Conversion 6203 if (SrcVT.isInteger()) { 6204 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6205 // First do a narrowing convert to an FP type half the size, then round 6206 // the FP type to a small FP type if needed. 6207 6208 MVT InterimFVT = DstVT; 6209 if (SrcEltSize > (2 * DstEltSize)) { 6210 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6211 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6212 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6213 } 6214 6215 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6216 6217 if (InterimFVT != DstVT) { 6218 Src = Result; 6219 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6220 } 6221 } else { 6222 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6223 "Wrong input/output vector types"); 6224 // First do a narrowing conversion to an integer half the size, then 6225 // truncate if needed. 6226 6227 if (DstEltSize == 1) { 6228 // First convert to the same size integer, then convert to mask using 6229 // setcc. 6230 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6231 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6232 DstVT.getVectorElementCount()); 6233 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6234 6235 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6236 // otherwise the conversion was undefined. 6237 MVT XLenVT = Subtarget.getXLenVT(); 6238 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6239 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6240 DAG.getUNDEF(InterimIVT), SplatZero); 6241 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6242 DAG.getCondCode(ISD::SETNE), Mask, VL); 6243 } else { 6244 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6245 DstVT.getVectorElementCount()); 6246 6247 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6248 6249 while (InterimIVT != DstVT) { 6250 SrcEltSize /= 2; 6251 Src = Result; 6252 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6253 DstVT.getVectorElementCount()); 6254 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6255 Src, Mask, VL); 6256 } 6257 } 6258 } 6259 } 6260 6261 MVT VT = Op.getSimpleValueType(); 6262 if (!VT.isFixedLengthVector()) 6263 return Result; 6264 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6265 } 6266 6267 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6268 unsigned MaskOpc, 6269 unsigned VecOpc) const { 6270 MVT VT = Op.getSimpleValueType(); 6271 if (VT.getVectorElementType() != MVT::i1) 6272 return lowerVPOp(Op, DAG, VecOpc); 6273 6274 // It is safe to drop mask parameter as masked-off elements are undef. 6275 SDValue Op1 = Op->getOperand(0); 6276 SDValue Op2 = Op->getOperand(1); 6277 SDValue VL = Op->getOperand(3); 6278 6279 MVT ContainerVT = VT; 6280 const bool IsFixed = VT.isFixedLengthVector(); 6281 if (IsFixed) { 6282 ContainerVT = getContainerForFixedLengthVector(VT); 6283 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6284 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6285 } 6286 6287 SDLoc DL(Op); 6288 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6289 if (!IsFixed) 6290 return Val; 6291 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6292 } 6293 6294 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6295 // matched to a RVV indexed load. The RVV indexed load instructions only 6296 // support the "unsigned unscaled" addressing mode; indices are implicitly 6297 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6298 // signed or scaled indexing is extended to the XLEN value type and scaled 6299 // accordingly. 6300 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6301 SelectionDAG &DAG) const { 6302 SDLoc DL(Op); 6303 MVT VT = Op.getSimpleValueType(); 6304 6305 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6306 EVT MemVT = MemSD->getMemoryVT(); 6307 MachineMemOperand *MMO = MemSD->getMemOperand(); 6308 SDValue Chain = MemSD->getChain(); 6309 SDValue BasePtr = MemSD->getBasePtr(); 6310 6311 ISD::LoadExtType LoadExtType; 6312 SDValue Index, Mask, PassThru, VL; 6313 6314 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6315 Index = VPGN->getIndex(); 6316 Mask = VPGN->getMask(); 6317 PassThru = DAG.getUNDEF(VT); 6318 VL = VPGN->getVectorLength(); 6319 // VP doesn't support extending loads. 6320 LoadExtType = ISD::NON_EXTLOAD; 6321 } else { 6322 // Else it must be a MGATHER. 6323 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6324 Index = MGN->getIndex(); 6325 Mask = MGN->getMask(); 6326 PassThru = MGN->getPassThru(); 6327 LoadExtType = MGN->getExtensionType(); 6328 } 6329 6330 MVT IndexVT = Index.getSimpleValueType(); 6331 MVT XLenVT = Subtarget.getXLenVT(); 6332 6333 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6334 "Unexpected VTs!"); 6335 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6336 // Targets have to explicitly opt-in for extending vector loads. 6337 assert(LoadExtType == ISD::NON_EXTLOAD && 6338 "Unexpected extending MGATHER/VP_GATHER"); 6339 (void)LoadExtType; 6340 6341 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6342 // the selection of the masked intrinsics doesn't do this for us. 6343 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6344 6345 MVT ContainerVT = VT; 6346 if (VT.isFixedLengthVector()) { 6347 // We need to use the larger of the result and index type to determine the 6348 // scalable type to use so we don't increase LMUL for any operand/result. 6349 if (VT.bitsGE(IndexVT)) { 6350 ContainerVT = getContainerForFixedLengthVector(VT); 6351 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6352 ContainerVT.getVectorElementCount()); 6353 } else { 6354 IndexVT = getContainerForFixedLengthVector(IndexVT); 6355 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6356 IndexVT.getVectorElementCount()); 6357 } 6358 6359 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6360 6361 if (!IsUnmasked) { 6362 MVT MaskVT = 6363 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6364 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6365 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6366 } 6367 } 6368 6369 if (!VL) 6370 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6371 6372 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6373 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6374 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6375 VL); 6376 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6377 TrueMask, VL); 6378 } 6379 6380 unsigned IntID = 6381 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6382 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6383 if (IsUnmasked) 6384 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6385 else 6386 Ops.push_back(PassThru); 6387 Ops.push_back(BasePtr); 6388 Ops.push_back(Index); 6389 if (!IsUnmasked) 6390 Ops.push_back(Mask); 6391 Ops.push_back(VL); 6392 if (!IsUnmasked) 6393 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6394 6395 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6396 SDValue Result = 6397 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6398 Chain = Result.getValue(1); 6399 6400 if (VT.isFixedLengthVector()) 6401 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6402 6403 return DAG.getMergeValues({Result, Chain}, DL); 6404 } 6405 6406 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6407 // matched to a RVV indexed store. The RVV indexed store instructions only 6408 // support the "unsigned unscaled" addressing mode; indices are implicitly 6409 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6410 // signed or scaled indexing is extended to the XLEN value type and scaled 6411 // accordingly. 6412 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6413 SelectionDAG &DAG) const { 6414 SDLoc DL(Op); 6415 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6416 EVT MemVT = MemSD->getMemoryVT(); 6417 MachineMemOperand *MMO = MemSD->getMemOperand(); 6418 SDValue Chain = MemSD->getChain(); 6419 SDValue BasePtr = MemSD->getBasePtr(); 6420 6421 bool IsTruncatingStore = false; 6422 SDValue Index, Mask, Val, VL; 6423 6424 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6425 Index = VPSN->getIndex(); 6426 Mask = VPSN->getMask(); 6427 Val = VPSN->getValue(); 6428 VL = VPSN->getVectorLength(); 6429 // VP doesn't support truncating stores. 6430 IsTruncatingStore = false; 6431 } else { 6432 // Else it must be a MSCATTER. 6433 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6434 Index = MSN->getIndex(); 6435 Mask = MSN->getMask(); 6436 Val = MSN->getValue(); 6437 IsTruncatingStore = MSN->isTruncatingStore(); 6438 } 6439 6440 MVT VT = Val.getSimpleValueType(); 6441 MVT IndexVT = Index.getSimpleValueType(); 6442 MVT XLenVT = Subtarget.getXLenVT(); 6443 6444 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6445 "Unexpected VTs!"); 6446 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6447 // Targets have to explicitly opt-in for extending vector loads and 6448 // truncating vector stores. 6449 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6450 (void)IsTruncatingStore; 6451 6452 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6453 // the selection of the masked intrinsics doesn't do this for us. 6454 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6455 6456 MVT ContainerVT = VT; 6457 if (VT.isFixedLengthVector()) { 6458 // We need to use the larger of the value and index type to determine the 6459 // scalable type to use so we don't increase LMUL for any operand/result. 6460 if (VT.bitsGE(IndexVT)) { 6461 ContainerVT = getContainerForFixedLengthVector(VT); 6462 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6463 ContainerVT.getVectorElementCount()); 6464 } else { 6465 IndexVT = getContainerForFixedLengthVector(IndexVT); 6466 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6467 IndexVT.getVectorElementCount()); 6468 } 6469 6470 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6471 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6472 6473 if (!IsUnmasked) { 6474 MVT MaskVT = 6475 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6476 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6477 } 6478 } 6479 6480 if (!VL) 6481 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6482 6483 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6484 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6485 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6486 VL); 6487 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6488 TrueMask, VL); 6489 } 6490 6491 unsigned IntID = 6492 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6493 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6494 Ops.push_back(Val); 6495 Ops.push_back(BasePtr); 6496 Ops.push_back(Index); 6497 if (!IsUnmasked) 6498 Ops.push_back(Mask); 6499 Ops.push_back(VL); 6500 6501 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6502 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6503 } 6504 6505 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6506 SelectionDAG &DAG) const { 6507 const MVT XLenVT = Subtarget.getXLenVT(); 6508 SDLoc DL(Op); 6509 SDValue Chain = Op->getOperand(0); 6510 SDValue SysRegNo = DAG.getTargetConstant( 6511 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6512 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6513 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6514 6515 // Encoding used for rounding mode in RISCV differs from that used in 6516 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6517 // table, which consists of a sequence of 4-bit fields, each representing 6518 // corresponding FLT_ROUNDS mode. 6519 static const int Table = 6520 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6521 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6522 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6523 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6524 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6525 6526 SDValue Shift = 6527 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6528 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6529 DAG.getConstant(Table, DL, XLenVT), Shift); 6530 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6531 DAG.getConstant(7, DL, XLenVT)); 6532 6533 return DAG.getMergeValues({Masked, Chain}, DL); 6534 } 6535 6536 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6537 SelectionDAG &DAG) const { 6538 const MVT XLenVT = Subtarget.getXLenVT(); 6539 SDLoc DL(Op); 6540 SDValue Chain = Op->getOperand(0); 6541 SDValue RMValue = Op->getOperand(1); 6542 SDValue SysRegNo = DAG.getTargetConstant( 6543 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6544 6545 // Encoding used for rounding mode in RISCV differs from that used in 6546 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6547 // a table, which consists of a sequence of 4-bit fields, each representing 6548 // corresponding RISCV mode. 6549 static const unsigned Table = 6550 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6551 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6552 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6553 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6554 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6555 6556 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6557 DAG.getConstant(2, DL, XLenVT)); 6558 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6559 DAG.getConstant(Table, DL, XLenVT), Shift); 6560 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6561 DAG.getConstant(0x7, DL, XLenVT)); 6562 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6563 RMValue); 6564 } 6565 6566 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6567 switch (IntNo) { 6568 default: 6569 llvm_unreachable("Unexpected Intrinsic"); 6570 case Intrinsic::riscv_bcompress: 6571 return RISCVISD::BCOMPRESSW; 6572 case Intrinsic::riscv_bdecompress: 6573 return RISCVISD::BDECOMPRESSW; 6574 case Intrinsic::riscv_bfp: 6575 return RISCVISD::BFPW; 6576 case Intrinsic::riscv_fsl: 6577 return RISCVISD::FSLW; 6578 case Intrinsic::riscv_fsr: 6579 return RISCVISD::FSRW; 6580 } 6581 } 6582 6583 // Converts the given intrinsic to a i64 operation with any extension. 6584 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6585 unsigned IntNo) { 6586 SDLoc DL(N); 6587 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6588 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6589 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6590 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6591 // ReplaceNodeResults requires we maintain the same type for the return value. 6592 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6593 } 6594 6595 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6596 // form of the given Opcode. 6597 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6598 switch (Opcode) { 6599 default: 6600 llvm_unreachable("Unexpected opcode"); 6601 case ISD::SHL: 6602 return RISCVISD::SLLW; 6603 case ISD::SRA: 6604 return RISCVISD::SRAW; 6605 case ISD::SRL: 6606 return RISCVISD::SRLW; 6607 case ISD::SDIV: 6608 return RISCVISD::DIVW; 6609 case ISD::UDIV: 6610 return RISCVISD::DIVUW; 6611 case ISD::UREM: 6612 return RISCVISD::REMUW; 6613 case ISD::ROTL: 6614 return RISCVISD::ROLW; 6615 case ISD::ROTR: 6616 return RISCVISD::RORW; 6617 } 6618 } 6619 6620 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6621 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6622 // otherwise be promoted to i64, making it difficult to select the 6623 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6624 // type i8/i16/i32 is lost. 6625 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6626 unsigned ExtOpc = ISD::ANY_EXTEND) { 6627 SDLoc DL(N); 6628 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6629 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6630 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6631 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6632 // ReplaceNodeResults requires we maintain the same type for the return value. 6633 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6634 } 6635 6636 // Converts the given 32-bit operation to a i64 operation with signed extension 6637 // semantic to reduce the signed extension instructions. 6638 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6639 SDLoc DL(N); 6640 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6641 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6642 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6643 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6644 DAG.getValueType(MVT::i32)); 6645 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6646 } 6647 6648 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6649 SmallVectorImpl<SDValue> &Results, 6650 SelectionDAG &DAG) const { 6651 SDLoc DL(N); 6652 switch (N->getOpcode()) { 6653 default: 6654 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6655 case ISD::STRICT_FP_TO_SINT: 6656 case ISD::STRICT_FP_TO_UINT: 6657 case ISD::FP_TO_SINT: 6658 case ISD::FP_TO_UINT: { 6659 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6660 "Unexpected custom legalisation"); 6661 bool IsStrict = N->isStrictFPOpcode(); 6662 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6663 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6664 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6665 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6666 TargetLowering::TypeSoftenFloat) { 6667 if (!isTypeLegal(Op0.getValueType())) 6668 return; 6669 if (IsStrict) { 6670 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6671 : RISCVISD::STRICT_FCVT_WU_RV64; 6672 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6673 SDValue Res = DAG.getNode( 6674 Opc, DL, VTs, N->getOperand(0), Op0, 6675 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6676 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6677 Results.push_back(Res.getValue(1)); 6678 return; 6679 } 6680 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6681 SDValue Res = 6682 DAG.getNode(Opc, DL, MVT::i64, Op0, 6683 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6684 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6685 return; 6686 } 6687 // If the FP type needs to be softened, emit a library call using the 'si' 6688 // version. If we left it to default legalization we'd end up with 'di'. If 6689 // the FP type doesn't need to be softened just let generic type 6690 // legalization promote the result type. 6691 RTLIB::Libcall LC; 6692 if (IsSigned) 6693 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6694 else 6695 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6696 MakeLibCallOptions CallOptions; 6697 EVT OpVT = Op0.getValueType(); 6698 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6699 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6700 SDValue Result; 6701 std::tie(Result, Chain) = 6702 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6703 Results.push_back(Result); 6704 if (IsStrict) 6705 Results.push_back(Chain); 6706 break; 6707 } 6708 case ISD::READCYCLECOUNTER: { 6709 assert(!Subtarget.is64Bit() && 6710 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6711 6712 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6713 SDValue RCW = 6714 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6715 6716 Results.push_back( 6717 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6718 Results.push_back(RCW.getValue(2)); 6719 break; 6720 } 6721 case ISD::MUL: { 6722 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6723 unsigned XLen = Subtarget.getXLen(); 6724 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6725 if (Size > XLen) { 6726 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6727 SDValue LHS = N->getOperand(0); 6728 SDValue RHS = N->getOperand(1); 6729 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6730 6731 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6732 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6733 // We need exactly one side to be unsigned. 6734 if (LHSIsU == RHSIsU) 6735 return; 6736 6737 auto MakeMULPair = [&](SDValue S, SDValue U) { 6738 MVT XLenVT = Subtarget.getXLenVT(); 6739 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6740 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6741 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6742 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6743 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6744 }; 6745 6746 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6747 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6748 6749 // The other operand should be signed, but still prefer MULH when 6750 // possible. 6751 if (RHSIsU && LHSIsS && !RHSIsS) 6752 Results.push_back(MakeMULPair(LHS, RHS)); 6753 else if (LHSIsU && RHSIsS && !LHSIsS) 6754 Results.push_back(MakeMULPair(RHS, LHS)); 6755 6756 return; 6757 } 6758 LLVM_FALLTHROUGH; 6759 } 6760 case ISD::ADD: 6761 case ISD::SUB: 6762 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6763 "Unexpected custom legalisation"); 6764 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6765 break; 6766 case ISD::SHL: 6767 case ISD::SRA: 6768 case ISD::SRL: 6769 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6770 "Unexpected custom legalisation"); 6771 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6772 Results.push_back(customLegalizeToWOp(N, DAG)); 6773 break; 6774 } 6775 6776 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6777 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6778 // shift amount. 6779 if (N->getOpcode() == ISD::SHL) { 6780 SDLoc DL(N); 6781 SDValue NewOp0 = 6782 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6783 SDValue NewOp1 = 6784 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6785 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6786 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6787 DAG.getValueType(MVT::i32)); 6788 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6789 } 6790 6791 break; 6792 case ISD::ROTL: 6793 case ISD::ROTR: 6794 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6795 "Unexpected custom legalisation"); 6796 Results.push_back(customLegalizeToWOp(N, DAG)); 6797 break; 6798 case ISD::CTTZ: 6799 case ISD::CTTZ_ZERO_UNDEF: 6800 case ISD::CTLZ: 6801 case ISD::CTLZ_ZERO_UNDEF: { 6802 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6803 "Unexpected custom legalisation"); 6804 6805 SDValue NewOp0 = 6806 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6807 bool IsCTZ = 6808 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6809 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6810 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6811 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6812 return; 6813 } 6814 case ISD::SDIV: 6815 case ISD::UDIV: 6816 case ISD::UREM: { 6817 MVT VT = N->getSimpleValueType(0); 6818 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6819 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6820 "Unexpected custom legalisation"); 6821 // Don't promote division/remainder by constant since we should expand those 6822 // to multiply by magic constant. 6823 // FIXME: What if the expansion is disabled for minsize. 6824 if (N->getOperand(1).getOpcode() == ISD::Constant) 6825 return; 6826 6827 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6828 // the upper 32 bits. For other types we need to sign or zero extend 6829 // based on the opcode. 6830 unsigned ExtOpc = ISD::ANY_EXTEND; 6831 if (VT != MVT::i32) 6832 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6833 : ISD::ZERO_EXTEND; 6834 6835 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6836 break; 6837 } 6838 case ISD::UADDO: 6839 case ISD::USUBO: { 6840 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6841 "Unexpected custom legalisation"); 6842 bool IsAdd = N->getOpcode() == ISD::UADDO; 6843 // Create an ADDW or SUBW. 6844 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6845 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6846 SDValue Res = 6847 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6848 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6849 DAG.getValueType(MVT::i32)); 6850 6851 SDValue Overflow; 6852 if (IsAdd && isOneConstant(RHS)) { 6853 // Special case uaddo X, 1 overflowed if the addition result is 0. 6854 // FIXME: We can do this for any constant RHS by using (X + C) < C. 6855 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6856 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6857 } else { 6858 // Sign extend the LHS and perform an unsigned compare with the ADDW 6859 // result. Since the inputs are sign extended from i32, this is equivalent 6860 // to comparing the lower 32 bits. 6861 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6862 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6863 IsAdd ? ISD::SETULT : ISD::SETUGT); 6864 } 6865 6866 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6867 Results.push_back(Overflow); 6868 return; 6869 } 6870 case ISD::UADDSAT: 6871 case ISD::USUBSAT: { 6872 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6873 "Unexpected custom legalisation"); 6874 if (Subtarget.hasStdExtZbb()) { 6875 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6876 // sign extend allows overflow of the lower 32 bits to be detected on 6877 // the promoted size. 6878 SDValue LHS = 6879 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6880 SDValue RHS = 6881 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6882 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6883 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6884 return; 6885 } 6886 6887 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6888 // promotion for UADDO/USUBO. 6889 Results.push_back(expandAddSubSat(N, DAG)); 6890 return; 6891 } 6892 case ISD::ABS: { 6893 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6894 "Unexpected custom legalisation"); 6895 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6896 6897 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6898 6899 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6900 6901 // Freeze the source so we can increase it's use count. 6902 Src = DAG.getFreeze(Src); 6903 6904 // Copy sign bit to all bits using the sraiw pattern. 6905 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6906 DAG.getValueType(MVT::i32)); 6907 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6908 DAG.getConstant(31, DL, MVT::i64)); 6909 6910 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6911 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6912 6913 // NOTE: The result is only required to be anyextended, but sext is 6914 // consistent with type legalization of sub. 6915 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6916 DAG.getValueType(MVT::i32)); 6917 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6918 return; 6919 } 6920 case ISD::BITCAST: { 6921 EVT VT = N->getValueType(0); 6922 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6923 SDValue Op0 = N->getOperand(0); 6924 EVT Op0VT = Op0.getValueType(); 6925 MVT XLenVT = Subtarget.getXLenVT(); 6926 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6927 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6928 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6929 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6930 Subtarget.hasStdExtF()) { 6931 SDValue FPConv = 6932 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6933 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6934 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6935 isTypeLegal(Op0VT)) { 6936 // Custom-legalize bitcasts from fixed-length vector types to illegal 6937 // scalar types in order to improve codegen. Bitcast the vector to a 6938 // one-element vector type whose element type is the same as the result 6939 // type, and extract the first element. 6940 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6941 if (isTypeLegal(BVT)) { 6942 SDValue BVec = DAG.getBitcast(BVT, Op0); 6943 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6944 DAG.getConstant(0, DL, XLenVT))); 6945 } 6946 } 6947 break; 6948 } 6949 case RISCVISD::GREV: 6950 case RISCVISD::GORC: 6951 case RISCVISD::SHFL: { 6952 MVT VT = N->getSimpleValueType(0); 6953 MVT XLenVT = Subtarget.getXLenVT(); 6954 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 6955 "Unexpected custom legalisation"); 6956 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6957 assert((Subtarget.hasStdExtZbp() || 6958 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 6959 N->getConstantOperandVal(1) == 7)) && 6960 "Unexpected extension"); 6961 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6962 SDValue NewOp1 = 6963 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 6964 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 6965 // ReplaceNodeResults requires we maintain the same type for the return 6966 // value. 6967 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 6968 break; 6969 } 6970 case ISD::BSWAP: 6971 case ISD::BITREVERSE: { 6972 MVT VT = N->getSimpleValueType(0); 6973 MVT XLenVT = Subtarget.getXLenVT(); 6974 assert((VT == MVT::i8 || VT == MVT::i16 || 6975 (VT == MVT::i32 && Subtarget.is64Bit())) && 6976 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6977 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6978 unsigned Imm = VT.getSizeInBits() - 1; 6979 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6980 if (N->getOpcode() == ISD::BSWAP) 6981 Imm &= ~0x7U; 6982 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 6983 DAG.getConstant(Imm, DL, XLenVT)); 6984 // ReplaceNodeResults requires we maintain the same type for the return 6985 // value. 6986 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6987 break; 6988 } 6989 case ISD::FSHL: 6990 case ISD::FSHR: { 6991 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6992 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6993 SDValue NewOp0 = 6994 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6995 SDValue NewOp1 = 6996 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6997 SDValue NewShAmt = 6998 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6999 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7000 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7001 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7002 DAG.getConstant(0x1f, DL, MVT::i64)); 7003 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7004 // instruction use different orders. fshl will return its first operand for 7005 // shift of zero, fshr will return its second operand. fsl and fsr both 7006 // return rs1 so the ISD nodes need to have different operand orders. 7007 // Shift amount is in rs2. 7008 unsigned Opc = RISCVISD::FSLW; 7009 if (N->getOpcode() == ISD::FSHR) { 7010 std::swap(NewOp0, NewOp1); 7011 Opc = RISCVISD::FSRW; 7012 } 7013 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7014 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7015 break; 7016 } 7017 case ISD::EXTRACT_VECTOR_ELT: { 7018 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7019 // type is illegal (currently only vXi64 RV32). 7020 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7021 // transferred to the destination register. We issue two of these from the 7022 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7023 // first element. 7024 SDValue Vec = N->getOperand(0); 7025 SDValue Idx = N->getOperand(1); 7026 7027 // The vector type hasn't been legalized yet so we can't issue target 7028 // specific nodes if it needs legalization. 7029 // FIXME: We would manually legalize if it's important. 7030 if (!isTypeLegal(Vec.getValueType())) 7031 return; 7032 7033 MVT VecVT = Vec.getSimpleValueType(); 7034 7035 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7036 VecVT.getVectorElementType() == MVT::i64 && 7037 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7038 7039 // If this is a fixed vector, we need to convert it to a scalable vector. 7040 MVT ContainerVT = VecVT; 7041 if (VecVT.isFixedLengthVector()) { 7042 ContainerVT = getContainerForFixedLengthVector(VecVT); 7043 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7044 } 7045 7046 MVT XLenVT = Subtarget.getXLenVT(); 7047 7048 // Use a VL of 1 to avoid processing more elements than we need. 7049 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 7050 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7051 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7052 7053 // Unless the index is known to be 0, we must slide the vector down to get 7054 // the desired element into index 0. 7055 if (!isNullConstant(Idx)) { 7056 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7057 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7058 } 7059 7060 // Extract the lower XLEN bits of the correct vector element. 7061 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7062 7063 // To extract the upper XLEN bits of the vector element, shift the first 7064 // element right by 32 bits and re-extract the lower XLEN bits. 7065 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7066 DAG.getUNDEF(ContainerVT), 7067 DAG.getConstant(32, DL, XLenVT), VL); 7068 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7069 ThirtyTwoV, Mask, VL); 7070 7071 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7072 7073 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7074 break; 7075 } 7076 case ISD::INTRINSIC_WO_CHAIN: { 7077 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7078 switch (IntNo) { 7079 default: 7080 llvm_unreachable( 7081 "Don't know how to custom type legalize this intrinsic!"); 7082 case Intrinsic::riscv_grev: 7083 case Intrinsic::riscv_gorc: { 7084 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7085 "Unexpected custom legalisation"); 7086 SDValue NewOp1 = 7087 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7088 SDValue NewOp2 = 7089 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7090 unsigned Opc = 7091 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7092 // If the control is a constant, promote the node by clearing any extra 7093 // bits bits in the control. isel will form greviw/gorciw if the result is 7094 // sign extended. 7095 if (isa<ConstantSDNode>(NewOp2)) { 7096 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7097 DAG.getConstant(0x1f, DL, MVT::i64)); 7098 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7099 } 7100 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7101 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7102 break; 7103 } 7104 case Intrinsic::riscv_bcompress: 7105 case Intrinsic::riscv_bdecompress: 7106 case Intrinsic::riscv_bfp: { 7107 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7108 "Unexpected custom legalisation"); 7109 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7110 break; 7111 } 7112 case Intrinsic::riscv_fsl: 7113 case Intrinsic::riscv_fsr: { 7114 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7115 "Unexpected custom legalisation"); 7116 SDValue NewOp1 = 7117 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7118 SDValue NewOp2 = 7119 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7120 SDValue NewOp3 = 7121 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 7122 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 7123 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 7124 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7125 break; 7126 } 7127 case Intrinsic::riscv_orc_b: { 7128 // Lower to the GORCI encoding for orc.b with the operand extended. 7129 SDValue NewOp = 7130 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7131 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7132 DAG.getConstant(7, DL, MVT::i64)); 7133 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7134 return; 7135 } 7136 case Intrinsic::riscv_shfl: 7137 case Intrinsic::riscv_unshfl: { 7138 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7139 "Unexpected custom legalisation"); 7140 SDValue NewOp1 = 7141 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7142 SDValue NewOp2 = 7143 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7144 unsigned Opc = 7145 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7146 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7147 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7148 // will be shuffled the same way as the lower 32 bit half, but the two 7149 // halves won't cross. 7150 if (isa<ConstantSDNode>(NewOp2)) { 7151 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7152 DAG.getConstant(0xf, DL, MVT::i64)); 7153 Opc = 7154 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7155 } 7156 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7157 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7158 break; 7159 } 7160 case Intrinsic::riscv_vmv_x_s: { 7161 EVT VT = N->getValueType(0); 7162 MVT XLenVT = Subtarget.getXLenVT(); 7163 if (VT.bitsLT(XLenVT)) { 7164 // Simple case just extract using vmv.x.s and truncate. 7165 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7166 Subtarget.getXLenVT(), N->getOperand(1)); 7167 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7168 return; 7169 } 7170 7171 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7172 "Unexpected custom legalization"); 7173 7174 // We need to do the move in two steps. 7175 SDValue Vec = N->getOperand(1); 7176 MVT VecVT = Vec.getSimpleValueType(); 7177 7178 // First extract the lower XLEN bits of the element. 7179 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7180 7181 // To extract the upper XLEN bits of the vector element, shift the first 7182 // element right by 32 bits and re-extract the lower XLEN bits. 7183 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7184 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7185 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7186 SDValue ThirtyTwoV = 7187 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7188 DAG.getConstant(32, DL, XLenVT), VL); 7189 SDValue LShr32 = 7190 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7191 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7192 7193 Results.push_back( 7194 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7195 break; 7196 } 7197 } 7198 break; 7199 } 7200 case ISD::VECREDUCE_ADD: 7201 case ISD::VECREDUCE_AND: 7202 case ISD::VECREDUCE_OR: 7203 case ISD::VECREDUCE_XOR: 7204 case ISD::VECREDUCE_SMAX: 7205 case ISD::VECREDUCE_UMAX: 7206 case ISD::VECREDUCE_SMIN: 7207 case ISD::VECREDUCE_UMIN: 7208 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7209 Results.push_back(V); 7210 break; 7211 case ISD::VP_REDUCE_ADD: 7212 case ISD::VP_REDUCE_AND: 7213 case ISD::VP_REDUCE_OR: 7214 case ISD::VP_REDUCE_XOR: 7215 case ISD::VP_REDUCE_SMAX: 7216 case ISD::VP_REDUCE_UMAX: 7217 case ISD::VP_REDUCE_SMIN: 7218 case ISD::VP_REDUCE_UMIN: 7219 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7220 Results.push_back(V); 7221 break; 7222 case ISD::FLT_ROUNDS_: { 7223 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7224 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7225 Results.push_back(Res.getValue(0)); 7226 Results.push_back(Res.getValue(1)); 7227 break; 7228 } 7229 } 7230 } 7231 7232 // A structure to hold one of the bit-manipulation patterns below. Together, a 7233 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7234 // (or (and (shl x, 1), 0xAAAAAAAA), 7235 // (and (srl x, 1), 0x55555555)) 7236 struct RISCVBitmanipPat { 7237 SDValue Op; 7238 unsigned ShAmt; 7239 bool IsSHL; 7240 7241 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7242 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7243 } 7244 }; 7245 7246 // Matches patterns of the form 7247 // (and (shl x, C2), (C1 << C2)) 7248 // (and (srl x, C2), C1) 7249 // (shl (and x, C1), C2) 7250 // (srl (and x, (C1 << C2)), C2) 7251 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7252 // The expected masks for each shift amount are specified in BitmanipMasks where 7253 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7254 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7255 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7256 // XLen is 64. 7257 static Optional<RISCVBitmanipPat> 7258 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7259 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7260 "Unexpected number of masks"); 7261 Optional<uint64_t> Mask; 7262 // Optionally consume a mask around the shift operation. 7263 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7264 Mask = Op.getConstantOperandVal(1); 7265 Op = Op.getOperand(0); 7266 } 7267 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7268 return None; 7269 bool IsSHL = Op.getOpcode() == ISD::SHL; 7270 7271 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7272 return None; 7273 uint64_t ShAmt = Op.getConstantOperandVal(1); 7274 7275 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7276 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7277 return None; 7278 // If we don't have enough masks for 64 bit, then we must be trying to 7279 // match SHFL so we're only allowed to shift 1/4 of the width. 7280 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7281 return None; 7282 7283 SDValue Src = Op.getOperand(0); 7284 7285 // The expected mask is shifted left when the AND is found around SHL 7286 // patterns. 7287 // ((x >> 1) & 0x55555555) 7288 // ((x << 1) & 0xAAAAAAAA) 7289 bool SHLExpMask = IsSHL; 7290 7291 if (!Mask) { 7292 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7293 // the mask is all ones: consume that now. 7294 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7295 Mask = Src.getConstantOperandVal(1); 7296 Src = Src.getOperand(0); 7297 // The expected mask is now in fact shifted left for SRL, so reverse the 7298 // decision. 7299 // ((x & 0xAAAAAAAA) >> 1) 7300 // ((x & 0x55555555) << 1) 7301 SHLExpMask = !SHLExpMask; 7302 } else { 7303 // Use a default shifted mask of all-ones if there's no AND, truncated 7304 // down to the expected width. This simplifies the logic later on. 7305 Mask = maskTrailingOnes<uint64_t>(Width); 7306 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7307 } 7308 } 7309 7310 unsigned MaskIdx = Log2_32(ShAmt); 7311 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7312 7313 if (SHLExpMask) 7314 ExpMask <<= ShAmt; 7315 7316 if (Mask != ExpMask) 7317 return None; 7318 7319 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7320 } 7321 7322 // Matches any of the following bit-manipulation patterns: 7323 // (and (shl x, 1), (0x55555555 << 1)) 7324 // (and (srl x, 1), 0x55555555) 7325 // (shl (and x, 0x55555555), 1) 7326 // (srl (and x, (0x55555555 << 1)), 1) 7327 // where the shift amount and mask may vary thus: 7328 // [1] = 0x55555555 / 0xAAAAAAAA 7329 // [2] = 0x33333333 / 0xCCCCCCCC 7330 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7331 // [8] = 0x00FF00FF / 0xFF00FF00 7332 // [16] = 0x0000FFFF / 0xFFFFFFFF 7333 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7334 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7335 // These are the unshifted masks which we use to match bit-manipulation 7336 // patterns. They may be shifted left in certain circumstances. 7337 static const uint64_t BitmanipMasks[] = { 7338 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7339 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7340 7341 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7342 } 7343 7344 // Match the following pattern as a GREVI(W) operation 7345 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7346 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7347 const RISCVSubtarget &Subtarget) { 7348 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7349 EVT VT = Op.getValueType(); 7350 7351 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7352 auto LHS = matchGREVIPat(Op.getOperand(0)); 7353 auto RHS = matchGREVIPat(Op.getOperand(1)); 7354 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7355 SDLoc DL(Op); 7356 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7357 DAG.getConstant(LHS->ShAmt, DL, VT)); 7358 } 7359 } 7360 return SDValue(); 7361 } 7362 7363 // Matches any the following pattern as a GORCI(W) operation 7364 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7365 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7366 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7367 // Note that with the variant of 3., 7368 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7369 // the inner pattern will first be matched as GREVI and then the outer 7370 // pattern will be matched to GORC via the first rule above. 7371 // 4. (or (rotl/rotr x, bitwidth/2), x) 7372 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7373 const RISCVSubtarget &Subtarget) { 7374 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7375 EVT VT = Op.getValueType(); 7376 7377 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7378 SDLoc DL(Op); 7379 SDValue Op0 = Op.getOperand(0); 7380 SDValue Op1 = Op.getOperand(1); 7381 7382 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7383 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7384 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7385 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7386 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7387 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7388 if ((Reverse.getOpcode() == ISD::ROTL || 7389 Reverse.getOpcode() == ISD::ROTR) && 7390 Reverse.getOperand(0) == X && 7391 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7392 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7393 if (RotAmt == (VT.getSizeInBits() / 2)) 7394 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7395 DAG.getConstant(RotAmt, DL, VT)); 7396 } 7397 return SDValue(); 7398 }; 7399 7400 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7401 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7402 return V; 7403 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7404 return V; 7405 7406 // OR is commutable so canonicalize its OR operand to the left 7407 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7408 std::swap(Op0, Op1); 7409 if (Op0.getOpcode() != ISD::OR) 7410 return SDValue(); 7411 SDValue OrOp0 = Op0.getOperand(0); 7412 SDValue OrOp1 = Op0.getOperand(1); 7413 auto LHS = matchGREVIPat(OrOp0); 7414 // OR is commutable so swap the operands and try again: x might have been 7415 // on the left 7416 if (!LHS) { 7417 std::swap(OrOp0, OrOp1); 7418 LHS = matchGREVIPat(OrOp0); 7419 } 7420 auto RHS = matchGREVIPat(Op1); 7421 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7422 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7423 DAG.getConstant(LHS->ShAmt, DL, VT)); 7424 } 7425 } 7426 return SDValue(); 7427 } 7428 7429 // Matches any of the following bit-manipulation patterns: 7430 // (and (shl x, 1), (0x22222222 << 1)) 7431 // (and (srl x, 1), 0x22222222) 7432 // (shl (and x, 0x22222222), 1) 7433 // (srl (and x, (0x22222222 << 1)), 1) 7434 // where the shift amount and mask may vary thus: 7435 // [1] = 0x22222222 / 0x44444444 7436 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7437 // [4] = 0x00F000F0 / 0x0F000F00 7438 // [8] = 0x0000FF00 / 0x00FF0000 7439 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7440 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7441 // These are the unshifted masks which we use to match bit-manipulation 7442 // patterns. They may be shifted left in certain circumstances. 7443 static const uint64_t BitmanipMasks[] = { 7444 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7445 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7446 7447 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7448 } 7449 7450 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7451 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7452 const RISCVSubtarget &Subtarget) { 7453 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7454 EVT VT = Op.getValueType(); 7455 7456 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7457 return SDValue(); 7458 7459 SDValue Op0 = Op.getOperand(0); 7460 SDValue Op1 = Op.getOperand(1); 7461 7462 // Or is commutable so canonicalize the second OR to the LHS. 7463 if (Op0.getOpcode() != ISD::OR) 7464 std::swap(Op0, Op1); 7465 if (Op0.getOpcode() != ISD::OR) 7466 return SDValue(); 7467 7468 // We found an inner OR, so our operands are the operands of the inner OR 7469 // and the other operand of the outer OR. 7470 SDValue A = Op0.getOperand(0); 7471 SDValue B = Op0.getOperand(1); 7472 SDValue C = Op1; 7473 7474 auto Match1 = matchSHFLPat(A); 7475 auto Match2 = matchSHFLPat(B); 7476 7477 // If neither matched, we failed. 7478 if (!Match1 && !Match2) 7479 return SDValue(); 7480 7481 // We had at least one match. if one failed, try the remaining C operand. 7482 if (!Match1) { 7483 std::swap(A, C); 7484 Match1 = matchSHFLPat(A); 7485 if (!Match1) 7486 return SDValue(); 7487 } else if (!Match2) { 7488 std::swap(B, C); 7489 Match2 = matchSHFLPat(B); 7490 if (!Match2) 7491 return SDValue(); 7492 } 7493 assert(Match1 && Match2); 7494 7495 // Make sure our matches pair up. 7496 if (!Match1->formsPairWith(*Match2)) 7497 return SDValue(); 7498 7499 // All the remains is to make sure C is an AND with the same input, that masks 7500 // out the bits that are being shuffled. 7501 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7502 C.getOperand(0) != Match1->Op) 7503 return SDValue(); 7504 7505 uint64_t Mask = C.getConstantOperandVal(1); 7506 7507 static const uint64_t BitmanipMasks[] = { 7508 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7509 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7510 }; 7511 7512 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7513 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7514 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7515 7516 if (Mask != ExpMask) 7517 return SDValue(); 7518 7519 SDLoc DL(Op); 7520 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7521 DAG.getConstant(Match1->ShAmt, DL, VT)); 7522 } 7523 7524 // Optimize (add (shl x, c0), (shl y, c1)) -> 7525 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7526 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7527 const RISCVSubtarget &Subtarget) { 7528 // Perform this optimization only in the zba extension. 7529 if (!Subtarget.hasStdExtZba()) 7530 return SDValue(); 7531 7532 // Skip for vector types and larger types. 7533 EVT VT = N->getValueType(0); 7534 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7535 return SDValue(); 7536 7537 // The two operand nodes must be SHL and have no other use. 7538 SDValue N0 = N->getOperand(0); 7539 SDValue N1 = N->getOperand(1); 7540 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7541 !N0->hasOneUse() || !N1->hasOneUse()) 7542 return SDValue(); 7543 7544 // Check c0 and c1. 7545 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7546 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7547 if (!N0C || !N1C) 7548 return SDValue(); 7549 int64_t C0 = N0C->getSExtValue(); 7550 int64_t C1 = N1C->getSExtValue(); 7551 if (C0 <= 0 || C1 <= 0) 7552 return SDValue(); 7553 7554 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7555 int64_t Bits = std::min(C0, C1); 7556 int64_t Diff = std::abs(C0 - C1); 7557 if (Diff != 1 && Diff != 2 && Diff != 3) 7558 return SDValue(); 7559 7560 // Build nodes. 7561 SDLoc DL(N); 7562 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7563 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7564 SDValue NA0 = 7565 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7566 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7567 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7568 } 7569 7570 // Combine 7571 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7572 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7573 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7574 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7575 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7576 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7577 // The grev patterns represents BSWAP. 7578 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7579 // off the grev. 7580 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7581 const RISCVSubtarget &Subtarget) { 7582 bool IsWInstruction = 7583 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7584 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7585 IsWInstruction) && 7586 "Unexpected opcode!"); 7587 SDValue Src = N->getOperand(0); 7588 EVT VT = N->getValueType(0); 7589 SDLoc DL(N); 7590 7591 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7592 return SDValue(); 7593 7594 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7595 !isa<ConstantSDNode>(Src.getOperand(1))) 7596 return SDValue(); 7597 7598 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7599 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7600 7601 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7602 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7603 unsigned ShAmt1 = N->getConstantOperandVal(1); 7604 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7605 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7606 return SDValue(); 7607 7608 Src = Src.getOperand(0); 7609 7610 // Toggle bit the MSB of the shift. 7611 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7612 if (CombinedShAmt == 0) 7613 return Src; 7614 7615 SDValue Res = DAG.getNode( 7616 RISCVISD::GREV, DL, VT, Src, 7617 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7618 if (!IsWInstruction) 7619 return Res; 7620 7621 // Sign extend the result to match the behavior of the rotate. This will be 7622 // selected to GREVIW in isel. 7623 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7624 DAG.getValueType(MVT::i32)); 7625 } 7626 7627 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7628 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7629 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7630 // not undo itself, but they are redundant. 7631 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7632 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7633 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7634 SDValue Src = N->getOperand(0); 7635 7636 if (Src.getOpcode() != N->getOpcode()) 7637 return SDValue(); 7638 7639 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7640 !isa<ConstantSDNode>(Src.getOperand(1))) 7641 return SDValue(); 7642 7643 unsigned ShAmt1 = N->getConstantOperandVal(1); 7644 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7645 Src = Src.getOperand(0); 7646 7647 unsigned CombinedShAmt; 7648 if (IsGORC) 7649 CombinedShAmt = ShAmt1 | ShAmt2; 7650 else 7651 CombinedShAmt = ShAmt1 ^ ShAmt2; 7652 7653 if (CombinedShAmt == 0) 7654 return Src; 7655 7656 SDLoc DL(N); 7657 return DAG.getNode( 7658 N->getOpcode(), DL, N->getValueType(0), Src, 7659 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7660 } 7661 7662 // Combine a constant select operand into its use: 7663 // 7664 // (and (select cond, -1, c), x) 7665 // -> (select cond, x, (and x, c)) [AllOnes=1] 7666 // (or (select cond, 0, c), x) 7667 // -> (select cond, x, (or x, c)) [AllOnes=0] 7668 // (xor (select cond, 0, c), x) 7669 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7670 // (add (select cond, 0, c), x) 7671 // -> (select cond, x, (add x, c)) [AllOnes=0] 7672 // (sub x, (select cond, 0, c)) 7673 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7674 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7675 SelectionDAG &DAG, bool AllOnes) { 7676 EVT VT = N->getValueType(0); 7677 7678 // Skip vectors. 7679 if (VT.isVector()) 7680 return SDValue(); 7681 7682 if ((Slct.getOpcode() != ISD::SELECT && 7683 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7684 !Slct.hasOneUse()) 7685 return SDValue(); 7686 7687 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7688 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7689 }; 7690 7691 bool SwapSelectOps; 7692 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7693 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7694 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7695 SDValue NonConstantVal; 7696 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7697 SwapSelectOps = false; 7698 NonConstantVal = FalseVal; 7699 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7700 SwapSelectOps = true; 7701 NonConstantVal = TrueVal; 7702 } else 7703 return SDValue(); 7704 7705 // Slct is now know to be the desired identity constant when CC is true. 7706 TrueVal = OtherOp; 7707 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7708 // Unless SwapSelectOps says the condition should be false. 7709 if (SwapSelectOps) 7710 std::swap(TrueVal, FalseVal); 7711 7712 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7713 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7714 {Slct.getOperand(0), Slct.getOperand(1), 7715 Slct.getOperand(2), TrueVal, FalseVal}); 7716 7717 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7718 {Slct.getOperand(0), TrueVal, FalseVal}); 7719 } 7720 7721 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7722 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7723 bool AllOnes) { 7724 SDValue N0 = N->getOperand(0); 7725 SDValue N1 = N->getOperand(1); 7726 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7727 return Result; 7728 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7729 return Result; 7730 return SDValue(); 7731 } 7732 7733 // Transform (add (mul x, c0), c1) -> 7734 // (add (mul (add x, c1/c0), c0), c1%c0). 7735 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7736 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7737 // to an infinite loop in DAGCombine if transformed. 7738 // Or transform (add (mul x, c0), c1) -> 7739 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7740 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7741 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7742 // lead to an infinite loop in DAGCombine if transformed. 7743 // Or transform (add (mul x, c0), c1) -> 7744 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7745 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7746 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7747 // lead to an infinite loop in DAGCombine if transformed. 7748 // Or transform (add (mul x, c0), c1) -> 7749 // (mul (add x, c1/c0), c0). 7750 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7751 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7752 const RISCVSubtarget &Subtarget) { 7753 // Skip for vector types and larger types. 7754 EVT VT = N->getValueType(0); 7755 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7756 return SDValue(); 7757 // The first operand node must be a MUL and has no other use. 7758 SDValue N0 = N->getOperand(0); 7759 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7760 return SDValue(); 7761 // Check if c0 and c1 match above conditions. 7762 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7763 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7764 if (!N0C || !N1C) 7765 return SDValue(); 7766 // If N0C has multiple uses it's possible one of the cases in 7767 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7768 // in an infinite loop. 7769 if (!N0C->hasOneUse()) 7770 return SDValue(); 7771 int64_t C0 = N0C->getSExtValue(); 7772 int64_t C1 = N1C->getSExtValue(); 7773 int64_t CA, CB; 7774 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7775 return SDValue(); 7776 // Search for proper CA (non-zero) and CB that both are simm12. 7777 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7778 !isInt<12>(C0 * (C1 / C0))) { 7779 CA = C1 / C0; 7780 CB = C1 % C0; 7781 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7782 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7783 CA = C1 / C0 + 1; 7784 CB = C1 % C0 - C0; 7785 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7786 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7787 CA = C1 / C0 - 1; 7788 CB = C1 % C0 + C0; 7789 } else 7790 return SDValue(); 7791 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7792 SDLoc DL(N); 7793 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7794 DAG.getConstant(CA, DL, VT)); 7795 SDValue New1 = 7796 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7797 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7798 } 7799 7800 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7801 const RISCVSubtarget &Subtarget) { 7802 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7803 return V; 7804 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7805 return V; 7806 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7807 // (select lhs, rhs, cc, x, (add x, y)) 7808 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7809 } 7810 7811 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7812 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7813 // (select lhs, rhs, cc, x, (sub x, y)) 7814 SDValue N0 = N->getOperand(0); 7815 SDValue N1 = N->getOperand(1); 7816 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7817 } 7818 7819 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7820 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7821 // (select lhs, rhs, cc, x, (and x, y)) 7822 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7823 } 7824 7825 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7826 const RISCVSubtarget &Subtarget) { 7827 if (Subtarget.hasStdExtZbp()) { 7828 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7829 return GREV; 7830 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7831 return GORC; 7832 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7833 return SHFL; 7834 } 7835 7836 // fold (or (select cond, 0, y), x) -> 7837 // (select cond, x, (or x, y)) 7838 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7839 } 7840 7841 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7842 // fold (xor (select cond, 0, y), x) -> 7843 // (select cond, x, (xor x, y)) 7844 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7845 } 7846 7847 static SDValue 7848 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7849 const RISCVSubtarget &Subtarget) { 7850 SDValue Src = N->getOperand(0); 7851 EVT VT = N->getValueType(0); 7852 7853 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7854 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7855 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7856 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7857 Src.getOperand(0)); 7858 7859 // Fold (i64 (sext_inreg (abs X), i32)) -> 7860 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7861 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7862 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7863 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7864 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7865 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7866 // may get combined into an earlier operation so we need to use 7867 // ComputeNumSignBits. 7868 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7869 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7870 // we can't assume that X has 33 sign bits. We must check. 7871 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7872 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7873 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7874 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7875 SDLoc DL(N); 7876 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7877 SDValue Neg = 7878 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7879 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7880 DAG.getValueType(MVT::i32)); 7881 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7882 } 7883 7884 return SDValue(); 7885 } 7886 7887 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7888 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7889 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7890 bool Commute = false) { 7891 assert((N->getOpcode() == RISCVISD::ADD_VL || 7892 N->getOpcode() == RISCVISD::SUB_VL) && 7893 "Unexpected opcode"); 7894 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7895 SDValue Op0 = N->getOperand(0); 7896 SDValue Op1 = N->getOperand(1); 7897 if (Commute) 7898 std::swap(Op0, Op1); 7899 7900 MVT VT = N->getSimpleValueType(0); 7901 7902 // Determine the narrow size for a widening add/sub. 7903 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7904 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7905 VT.getVectorElementCount()); 7906 7907 SDValue Mask = N->getOperand(2); 7908 SDValue VL = N->getOperand(3); 7909 7910 SDLoc DL(N); 7911 7912 // If the RHS is a sext or zext, we can form a widening op. 7913 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7914 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7915 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7916 unsigned ExtOpc = Op1.getOpcode(); 7917 Op1 = Op1.getOperand(0); 7918 // Re-introduce narrower extends if needed. 7919 if (Op1.getValueType() != NarrowVT) 7920 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7921 7922 unsigned WOpc; 7923 if (ExtOpc == RISCVISD::VSEXT_VL) 7924 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7925 else 7926 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7927 7928 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7929 } 7930 7931 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7932 // sext/zext? 7933 7934 return SDValue(); 7935 } 7936 7937 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7938 // vwsub(u).vv/vx. 7939 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7940 SDValue Op0 = N->getOperand(0); 7941 SDValue Op1 = N->getOperand(1); 7942 SDValue Mask = N->getOperand(2); 7943 SDValue VL = N->getOperand(3); 7944 7945 MVT VT = N->getSimpleValueType(0); 7946 MVT NarrowVT = Op1.getSimpleValueType(); 7947 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7948 7949 unsigned VOpc; 7950 switch (N->getOpcode()) { 7951 default: llvm_unreachable("Unexpected opcode"); 7952 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7953 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7954 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7955 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7956 } 7957 7958 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7959 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7960 7961 SDLoc DL(N); 7962 7963 // If the LHS is a sext or zext, we can narrow this op to the same size as 7964 // the RHS. 7965 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7966 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7967 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7968 unsigned ExtOpc = Op0.getOpcode(); 7969 Op0 = Op0.getOperand(0); 7970 // Re-introduce narrower extends if needed. 7971 if (Op0.getValueType() != NarrowVT) 7972 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7973 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7974 } 7975 7976 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7977 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7978 7979 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7980 // to commute and use a vwadd(u).vx instead. 7981 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7982 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7983 Op0 = Op0.getOperand(1); 7984 7985 // See if have enough sign bits or zero bits in the scalar to use a 7986 // widening add/sub by splatting to smaller element size. 7987 unsigned EltBits = VT.getScalarSizeInBits(); 7988 unsigned ScalarBits = Op0.getValueSizeInBits(); 7989 // Make sure we're getting all element bits from the scalar register. 7990 // FIXME: Support implicit sign extension of vmv.v.x? 7991 if (ScalarBits < EltBits) 7992 return SDValue(); 7993 7994 if (IsSigned) { 7995 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7996 return SDValue(); 7997 } else { 7998 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7999 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8000 return SDValue(); 8001 } 8002 8003 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8004 DAG.getUNDEF(NarrowVT), Op0, VL); 8005 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8006 } 8007 8008 return SDValue(); 8009 } 8010 8011 // Try to form VWMUL, VWMULU or VWMULSU. 8012 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8013 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8014 bool Commute) { 8015 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8016 SDValue Op0 = N->getOperand(0); 8017 SDValue Op1 = N->getOperand(1); 8018 if (Commute) 8019 std::swap(Op0, Op1); 8020 8021 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8022 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8023 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8024 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8025 return SDValue(); 8026 8027 SDValue Mask = N->getOperand(2); 8028 SDValue VL = N->getOperand(3); 8029 8030 // Make sure the mask and VL match. 8031 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8032 return SDValue(); 8033 8034 MVT VT = N->getSimpleValueType(0); 8035 8036 // Determine the narrow size for a widening multiply. 8037 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8038 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8039 VT.getVectorElementCount()); 8040 8041 SDLoc DL(N); 8042 8043 // See if the other operand is the same opcode. 8044 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8045 if (!Op1.hasOneUse()) 8046 return SDValue(); 8047 8048 // Make sure the mask and VL match. 8049 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8050 return SDValue(); 8051 8052 Op1 = Op1.getOperand(0); 8053 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8054 // The operand is a splat of a scalar. 8055 8056 // The pasthru must be undef for tail agnostic 8057 if (!Op1.getOperand(0).isUndef()) 8058 return SDValue(); 8059 // The VL must be the same. 8060 if (Op1.getOperand(2) != VL) 8061 return SDValue(); 8062 8063 // Get the scalar value. 8064 Op1 = Op1.getOperand(1); 8065 8066 // See if have enough sign bits or zero bits in the scalar to use a 8067 // widening multiply by splatting to smaller element size. 8068 unsigned EltBits = VT.getScalarSizeInBits(); 8069 unsigned ScalarBits = Op1.getValueSizeInBits(); 8070 // Make sure we're getting all element bits from the scalar register. 8071 // FIXME: Support implicit sign extension of vmv.v.x? 8072 if (ScalarBits < EltBits) 8073 return SDValue(); 8074 8075 // If the LHS is a sign extend, try to use vwmul. 8076 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8077 // Can use vwmul. 8078 } else { 8079 // Otherwise try to use vwmulu or vwmulsu. 8080 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8081 if (DAG.MaskedValueIsZero(Op1, Mask)) 8082 IsVWMULSU = IsSignExt; 8083 else 8084 return SDValue(); 8085 } 8086 8087 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8088 DAG.getUNDEF(NarrowVT), Op1, VL); 8089 } else 8090 return SDValue(); 8091 8092 Op0 = Op0.getOperand(0); 8093 8094 // Re-introduce narrower extends if needed. 8095 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8096 if (Op0.getValueType() != NarrowVT) 8097 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8098 // vwmulsu requires second operand to be zero extended. 8099 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8100 if (Op1.getValueType() != NarrowVT) 8101 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8102 8103 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8104 if (!IsVWMULSU) 8105 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8106 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8107 } 8108 8109 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8110 switch (Op.getOpcode()) { 8111 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8112 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8113 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8114 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8115 case ISD::FROUND: return RISCVFPRndMode::RMM; 8116 } 8117 8118 return RISCVFPRndMode::Invalid; 8119 } 8120 8121 // Fold 8122 // (fp_to_int (froundeven X)) -> fcvt X, rne 8123 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8124 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8125 // (fp_to_int (fceil X)) -> fcvt X, rup 8126 // (fp_to_int (fround X)) -> fcvt X, rmm 8127 static SDValue performFP_TO_INTCombine(SDNode *N, 8128 TargetLowering::DAGCombinerInfo &DCI, 8129 const RISCVSubtarget &Subtarget) { 8130 SelectionDAG &DAG = DCI.DAG; 8131 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8132 MVT XLenVT = Subtarget.getXLenVT(); 8133 8134 // Only handle XLen or i32 types. Other types narrower than XLen will 8135 // eventually be legalized to XLenVT. 8136 EVT VT = N->getValueType(0); 8137 if (VT != MVT::i32 && VT != XLenVT) 8138 return SDValue(); 8139 8140 SDValue Src = N->getOperand(0); 8141 8142 // Ensure the FP type is also legal. 8143 if (!TLI.isTypeLegal(Src.getValueType())) 8144 return SDValue(); 8145 8146 // Don't do this for f16 with Zfhmin and not Zfh. 8147 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8148 return SDValue(); 8149 8150 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8151 if (FRM == RISCVFPRndMode::Invalid) 8152 return SDValue(); 8153 8154 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8155 8156 unsigned Opc; 8157 if (VT == XLenVT) 8158 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8159 else 8160 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8161 8162 SDLoc DL(N); 8163 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8164 DAG.getTargetConstant(FRM, DL, XLenVT)); 8165 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8166 } 8167 8168 // Fold 8169 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8170 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8171 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8172 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8173 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8174 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8175 TargetLowering::DAGCombinerInfo &DCI, 8176 const RISCVSubtarget &Subtarget) { 8177 SelectionDAG &DAG = DCI.DAG; 8178 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8179 MVT XLenVT = Subtarget.getXLenVT(); 8180 8181 // Only handle XLen types. Other types narrower than XLen will eventually be 8182 // legalized to XLenVT. 8183 EVT DstVT = N->getValueType(0); 8184 if (DstVT != XLenVT) 8185 return SDValue(); 8186 8187 SDValue Src = N->getOperand(0); 8188 8189 // Ensure the FP type is also legal. 8190 if (!TLI.isTypeLegal(Src.getValueType())) 8191 return SDValue(); 8192 8193 // Don't do this for f16 with Zfhmin and not Zfh. 8194 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8195 return SDValue(); 8196 8197 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8198 8199 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8200 if (FRM == RISCVFPRndMode::Invalid) 8201 return SDValue(); 8202 8203 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8204 8205 unsigned Opc; 8206 if (SatVT == DstVT) 8207 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8208 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8209 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8210 else 8211 return SDValue(); 8212 // FIXME: Support other SatVTs by clamping before or after the conversion. 8213 8214 Src = Src.getOperand(0); 8215 8216 SDLoc DL(N); 8217 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8218 DAG.getTargetConstant(FRM, DL, XLenVT)); 8219 8220 // RISCV FP-to-int conversions saturate to the destination register size, but 8221 // don't produce 0 for nan. 8222 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8223 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8224 } 8225 8226 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8227 // smaller than XLenVT. 8228 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8229 const RISCVSubtarget &Subtarget) { 8230 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8231 8232 SDValue Src = N->getOperand(0); 8233 if (Src.getOpcode() != ISD::BSWAP) 8234 return SDValue(); 8235 8236 EVT VT = N->getValueType(0); 8237 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8238 !isPowerOf2_32(VT.getSizeInBits())) 8239 return SDValue(); 8240 8241 SDLoc DL(N); 8242 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8243 DAG.getConstant(7, DL, VT)); 8244 } 8245 8246 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8247 DAGCombinerInfo &DCI) const { 8248 SelectionDAG &DAG = DCI.DAG; 8249 8250 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8251 // bits are demanded. N will be added to the Worklist if it was not deleted. 8252 // Caller should return SDValue(N, 0) if this returns true. 8253 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8254 SDValue Op = N->getOperand(OpNo); 8255 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8256 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8257 return false; 8258 8259 if (N->getOpcode() != ISD::DELETED_NODE) 8260 DCI.AddToWorklist(N); 8261 return true; 8262 }; 8263 8264 switch (N->getOpcode()) { 8265 default: 8266 break; 8267 case RISCVISD::SplitF64: { 8268 SDValue Op0 = N->getOperand(0); 8269 // If the input to SplitF64 is just BuildPairF64 then the operation is 8270 // redundant. Instead, use BuildPairF64's operands directly. 8271 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8272 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8273 8274 if (Op0->isUndef()) { 8275 SDValue Lo = DAG.getUNDEF(MVT::i32); 8276 SDValue Hi = DAG.getUNDEF(MVT::i32); 8277 return DCI.CombineTo(N, Lo, Hi); 8278 } 8279 8280 SDLoc DL(N); 8281 8282 // It's cheaper to materialise two 32-bit integers than to load a double 8283 // from the constant pool and transfer it to integer registers through the 8284 // stack. 8285 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8286 APInt V = C->getValueAPF().bitcastToAPInt(); 8287 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8288 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8289 return DCI.CombineTo(N, Lo, Hi); 8290 } 8291 8292 // This is a target-specific version of a DAGCombine performed in 8293 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8294 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8295 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8296 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8297 !Op0.getNode()->hasOneUse()) 8298 break; 8299 SDValue NewSplitF64 = 8300 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8301 Op0.getOperand(0)); 8302 SDValue Lo = NewSplitF64.getValue(0); 8303 SDValue Hi = NewSplitF64.getValue(1); 8304 APInt SignBit = APInt::getSignMask(32); 8305 if (Op0.getOpcode() == ISD::FNEG) { 8306 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8307 DAG.getConstant(SignBit, DL, MVT::i32)); 8308 return DCI.CombineTo(N, Lo, NewHi); 8309 } 8310 assert(Op0.getOpcode() == ISD::FABS); 8311 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8312 DAG.getConstant(~SignBit, DL, MVT::i32)); 8313 return DCI.CombineTo(N, Lo, NewHi); 8314 } 8315 case RISCVISD::SLLW: 8316 case RISCVISD::SRAW: 8317 case RISCVISD::SRLW: { 8318 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8319 if (SimplifyDemandedLowBitsHelper(0, 32) || 8320 SimplifyDemandedLowBitsHelper(1, 5)) 8321 return SDValue(N, 0); 8322 8323 break; 8324 } 8325 case ISD::ROTR: 8326 case ISD::ROTL: 8327 case RISCVISD::RORW: 8328 case RISCVISD::ROLW: { 8329 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8330 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8331 if (SimplifyDemandedLowBitsHelper(0, 32) || 8332 SimplifyDemandedLowBitsHelper(1, 5)) 8333 return SDValue(N, 0); 8334 } 8335 8336 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8337 } 8338 case RISCVISD::CLZW: 8339 case RISCVISD::CTZW: { 8340 // Only the lower 32 bits of the first operand are read 8341 if (SimplifyDemandedLowBitsHelper(0, 32)) 8342 return SDValue(N, 0); 8343 break; 8344 } 8345 case RISCVISD::GREV: 8346 case RISCVISD::GORC: { 8347 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8348 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8349 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8350 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8351 return SDValue(N, 0); 8352 8353 return combineGREVI_GORCI(N, DAG); 8354 } 8355 case RISCVISD::GREVW: 8356 case RISCVISD::GORCW: { 8357 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8358 if (SimplifyDemandedLowBitsHelper(0, 32) || 8359 SimplifyDemandedLowBitsHelper(1, 5)) 8360 return SDValue(N, 0); 8361 8362 break; 8363 } 8364 case RISCVISD::SHFL: 8365 case RISCVISD::UNSHFL: { 8366 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8367 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8368 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8369 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8370 return SDValue(N, 0); 8371 8372 break; 8373 } 8374 case RISCVISD::SHFLW: 8375 case RISCVISD::UNSHFLW: { 8376 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8377 if (SimplifyDemandedLowBitsHelper(0, 32) || 8378 SimplifyDemandedLowBitsHelper(1, 4)) 8379 return SDValue(N, 0); 8380 8381 break; 8382 } 8383 case RISCVISD::BCOMPRESSW: 8384 case RISCVISD::BDECOMPRESSW: { 8385 // Only the lower 32 bits of LHS and RHS are read. 8386 if (SimplifyDemandedLowBitsHelper(0, 32) || 8387 SimplifyDemandedLowBitsHelper(1, 32)) 8388 return SDValue(N, 0); 8389 8390 break; 8391 } 8392 case RISCVISD::FSR: 8393 case RISCVISD::FSL: 8394 case RISCVISD::FSRW: 8395 case RISCVISD::FSLW: { 8396 bool IsWInstruction = 8397 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8398 unsigned BitWidth = 8399 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8400 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8401 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8402 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8403 return SDValue(N, 0); 8404 8405 break; 8406 } 8407 case RISCVISD::FMV_X_ANYEXTH: 8408 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8409 SDLoc DL(N); 8410 SDValue Op0 = N->getOperand(0); 8411 MVT VT = N->getSimpleValueType(0); 8412 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8413 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8414 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8415 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8416 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8417 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8418 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8419 assert(Op0.getOperand(0).getValueType() == VT && 8420 "Unexpected value type!"); 8421 return Op0.getOperand(0); 8422 } 8423 8424 // This is a target-specific version of a DAGCombine performed in 8425 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8426 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8427 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8428 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8429 !Op0.getNode()->hasOneUse()) 8430 break; 8431 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8432 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8433 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8434 if (Op0.getOpcode() == ISD::FNEG) 8435 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8436 DAG.getConstant(SignBit, DL, VT)); 8437 8438 assert(Op0.getOpcode() == ISD::FABS); 8439 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8440 DAG.getConstant(~SignBit, DL, VT)); 8441 } 8442 case ISD::ADD: 8443 return performADDCombine(N, DAG, Subtarget); 8444 case ISD::SUB: 8445 return performSUBCombine(N, DAG); 8446 case ISD::AND: 8447 return performANDCombine(N, DAG); 8448 case ISD::OR: 8449 return performORCombine(N, DAG, Subtarget); 8450 case ISD::XOR: 8451 return performXORCombine(N, DAG); 8452 case ISD::SIGN_EXTEND_INREG: 8453 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8454 case ISD::ZERO_EXTEND: 8455 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8456 // type legalization. This is safe because fp_to_uint produces poison if 8457 // it overflows. 8458 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8459 SDValue Src = N->getOperand(0); 8460 if (Src.getOpcode() == ISD::FP_TO_UINT && 8461 isTypeLegal(Src.getOperand(0).getValueType())) 8462 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8463 Src.getOperand(0)); 8464 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8465 isTypeLegal(Src.getOperand(1).getValueType())) { 8466 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8467 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8468 Src.getOperand(0), Src.getOperand(1)); 8469 DCI.CombineTo(N, Res); 8470 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8471 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8472 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8473 } 8474 } 8475 return SDValue(); 8476 case RISCVISD::SELECT_CC: { 8477 // Transform 8478 SDValue LHS = N->getOperand(0); 8479 SDValue RHS = N->getOperand(1); 8480 SDValue TrueV = N->getOperand(3); 8481 SDValue FalseV = N->getOperand(4); 8482 8483 // If the True and False values are the same, we don't need a select_cc. 8484 if (TrueV == FalseV) 8485 return TrueV; 8486 8487 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8488 if (!ISD::isIntEqualitySetCC(CCVal)) 8489 break; 8490 8491 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8492 // (select_cc X, Y, lt, trueV, falseV) 8493 // Sometimes the setcc is introduced after select_cc has been formed. 8494 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8495 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8496 // If we're looking for eq 0 instead of ne 0, we need to invert the 8497 // condition. 8498 bool Invert = CCVal == ISD::SETEQ; 8499 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8500 if (Invert) 8501 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8502 8503 SDLoc DL(N); 8504 RHS = LHS.getOperand(1); 8505 LHS = LHS.getOperand(0); 8506 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8507 8508 SDValue TargetCC = DAG.getCondCode(CCVal); 8509 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8510 {LHS, RHS, TargetCC, TrueV, FalseV}); 8511 } 8512 8513 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8514 // (select_cc X, Y, eq/ne, trueV, falseV) 8515 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8516 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8517 {LHS.getOperand(0), LHS.getOperand(1), 8518 N->getOperand(2), TrueV, FalseV}); 8519 // (select_cc X, 1, setne, trueV, falseV) -> 8520 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8521 // This can occur when legalizing some floating point comparisons. 8522 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8523 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8524 SDLoc DL(N); 8525 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8526 SDValue TargetCC = DAG.getCondCode(CCVal); 8527 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8528 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8529 {LHS, RHS, TargetCC, TrueV, FalseV}); 8530 } 8531 8532 break; 8533 } 8534 case RISCVISD::BR_CC: { 8535 SDValue LHS = N->getOperand(1); 8536 SDValue RHS = N->getOperand(2); 8537 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8538 if (!ISD::isIntEqualitySetCC(CCVal)) 8539 break; 8540 8541 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8542 // (br_cc X, Y, lt, dest) 8543 // Sometimes the setcc is introduced after br_cc has been formed. 8544 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8545 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8546 // If we're looking for eq 0 instead of ne 0, we need to invert the 8547 // condition. 8548 bool Invert = CCVal == ISD::SETEQ; 8549 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8550 if (Invert) 8551 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8552 8553 SDLoc DL(N); 8554 RHS = LHS.getOperand(1); 8555 LHS = LHS.getOperand(0); 8556 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8557 8558 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8559 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8560 N->getOperand(4)); 8561 } 8562 8563 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8564 // (br_cc X, Y, eq/ne, trueV, falseV) 8565 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8566 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8567 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8568 N->getOperand(3), N->getOperand(4)); 8569 8570 // (br_cc X, 1, setne, br_cc) -> 8571 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8572 // This can occur when legalizing some floating point comparisons. 8573 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8574 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8575 SDLoc DL(N); 8576 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8577 SDValue TargetCC = DAG.getCondCode(CCVal); 8578 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8579 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8580 N->getOperand(0), LHS, RHS, TargetCC, 8581 N->getOperand(4)); 8582 } 8583 break; 8584 } 8585 case ISD::BITREVERSE: 8586 return performBITREVERSECombine(N, DAG, Subtarget); 8587 case ISD::FP_TO_SINT: 8588 case ISD::FP_TO_UINT: 8589 return performFP_TO_INTCombine(N, DCI, Subtarget); 8590 case ISD::FP_TO_SINT_SAT: 8591 case ISD::FP_TO_UINT_SAT: 8592 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8593 case ISD::FCOPYSIGN: { 8594 EVT VT = N->getValueType(0); 8595 if (!VT.isVector()) 8596 break; 8597 // There is a form of VFSGNJ which injects the negated sign of its second 8598 // operand. Try and bubble any FNEG up after the extend/round to produce 8599 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8600 // TRUNC=1. 8601 SDValue In2 = N->getOperand(1); 8602 // Avoid cases where the extend/round has multiple uses, as duplicating 8603 // those is typically more expensive than removing a fneg. 8604 if (!In2.hasOneUse()) 8605 break; 8606 if (In2.getOpcode() != ISD::FP_EXTEND && 8607 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8608 break; 8609 In2 = In2.getOperand(0); 8610 if (In2.getOpcode() != ISD::FNEG) 8611 break; 8612 SDLoc DL(N); 8613 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8614 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8615 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8616 } 8617 case ISD::MGATHER: 8618 case ISD::MSCATTER: 8619 case ISD::VP_GATHER: 8620 case ISD::VP_SCATTER: { 8621 if (!DCI.isBeforeLegalize()) 8622 break; 8623 SDValue Index, ScaleOp; 8624 bool IsIndexScaled = false; 8625 bool IsIndexSigned = false; 8626 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8627 Index = VPGSN->getIndex(); 8628 ScaleOp = VPGSN->getScale(); 8629 IsIndexScaled = VPGSN->isIndexScaled(); 8630 IsIndexSigned = VPGSN->isIndexSigned(); 8631 } else { 8632 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8633 Index = MGSN->getIndex(); 8634 ScaleOp = MGSN->getScale(); 8635 IsIndexScaled = MGSN->isIndexScaled(); 8636 IsIndexSigned = MGSN->isIndexSigned(); 8637 } 8638 EVT IndexVT = Index.getValueType(); 8639 MVT XLenVT = Subtarget.getXLenVT(); 8640 // RISCV indexed loads only support the "unsigned unscaled" addressing 8641 // mode, so anything else must be manually legalized. 8642 bool NeedsIdxLegalization = 8643 IsIndexScaled || 8644 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8645 if (!NeedsIdxLegalization) 8646 break; 8647 8648 SDLoc DL(N); 8649 8650 // Any index legalization should first promote to XLenVT, so we don't lose 8651 // bits when scaling. This may create an illegal index type so we let 8652 // LLVM's legalization take care of the splitting. 8653 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8654 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8655 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8656 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8657 DL, IndexVT, Index); 8658 } 8659 8660 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8661 if (IsIndexScaled && Scale != 1) { 8662 // Manually scale the indices by the element size. 8663 // TODO: Sanitize the scale operand here? 8664 // TODO: For VP nodes, should we use VP_SHL here? 8665 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8666 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8667 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8668 } 8669 8670 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8671 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8672 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8673 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8674 VPGN->getScale(), VPGN->getMask(), 8675 VPGN->getVectorLength()}, 8676 VPGN->getMemOperand(), NewIndexTy); 8677 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8678 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8679 {VPSN->getChain(), VPSN->getValue(), 8680 VPSN->getBasePtr(), Index, VPSN->getScale(), 8681 VPSN->getMask(), VPSN->getVectorLength()}, 8682 VPSN->getMemOperand(), NewIndexTy); 8683 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8684 return DAG.getMaskedGather( 8685 N->getVTList(), MGN->getMemoryVT(), DL, 8686 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8687 MGN->getBasePtr(), Index, MGN->getScale()}, 8688 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8689 const auto *MSN = cast<MaskedScatterSDNode>(N); 8690 return DAG.getMaskedScatter( 8691 N->getVTList(), MSN->getMemoryVT(), DL, 8692 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8693 Index, MSN->getScale()}, 8694 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8695 } 8696 case RISCVISD::SRA_VL: 8697 case RISCVISD::SRL_VL: 8698 case RISCVISD::SHL_VL: { 8699 SDValue ShAmt = N->getOperand(1); 8700 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8701 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8702 SDLoc DL(N); 8703 SDValue VL = N->getOperand(3); 8704 EVT VT = N->getValueType(0); 8705 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8706 ShAmt.getOperand(1), VL); 8707 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8708 N->getOperand(2), N->getOperand(3)); 8709 } 8710 break; 8711 } 8712 case ISD::SRA: 8713 case ISD::SRL: 8714 case ISD::SHL: { 8715 SDValue ShAmt = N->getOperand(1); 8716 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8717 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8718 SDLoc DL(N); 8719 EVT VT = N->getValueType(0); 8720 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8721 ShAmt.getOperand(1), 8722 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8723 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8724 } 8725 break; 8726 } 8727 case RISCVISD::ADD_VL: 8728 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8729 return V; 8730 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8731 case RISCVISD::SUB_VL: 8732 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8733 case RISCVISD::VWADD_W_VL: 8734 case RISCVISD::VWADDU_W_VL: 8735 case RISCVISD::VWSUB_W_VL: 8736 case RISCVISD::VWSUBU_W_VL: 8737 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8738 case RISCVISD::MUL_VL: 8739 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8740 return V; 8741 // Mul is commutative. 8742 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8743 case ISD::STORE: { 8744 auto *Store = cast<StoreSDNode>(N); 8745 SDValue Val = Store->getValue(); 8746 // Combine store of vmv.x.s to vse with VL of 1. 8747 // FIXME: Support FP. 8748 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8749 SDValue Src = Val.getOperand(0); 8750 EVT VecVT = Src.getValueType(); 8751 EVT MemVT = Store->getMemoryVT(); 8752 // The memory VT and the element type must match. 8753 if (VecVT.getVectorElementType() == MemVT) { 8754 SDLoc DL(N); 8755 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8756 return DAG.getStoreVP( 8757 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8758 DAG.getConstant(1, DL, MaskVT), 8759 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8760 Store->getMemOperand(), Store->getAddressingMode(), 8761 Store->isTruncatingStore(), /*IsCompress*/ false); 8762 } 8763 } 8764 8765 break; 8766 } 8767 case ISD::SPLAT_VECTOR: { 8768 EVT VT = N->getValueType(0); 8769 // Only perform this combine on legal MVT types. 8770 if (!isTypeLegal(VT)) 8771 break; 8772 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8773 DAG, Subtarget)) 8774 return Gather; 8775 break; 8776 } 8777 case RISCVISD::VMV_V_X_VL: { 8778 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8779 // scalar input. 8780 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8781 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8782 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8783 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8784 return SDValue(N, 0); 8785 8786 break; 8787 } 8788 case ISD::INTRINSIC_WO_CHAIN: { 8789 unsigned IntNo = N->getConstantOperandVal(0); 8790 switch (IntNo) { 8791 // By default we do not combine any intrinsic. 8792 default: 8793 return SDValue(); 8794 case Intrinsic::riscv_vcpop: 8795 case Intrinsic::riscv_vcpop_mask: 8796 case Intrinsic::riscv_vfirst: 8797 case Intrinsic::riscv_vfirst_mask: { 8798 SDValue VL = N->getOperand(2); 8799 if (IntNo == Intrinsic::riscv_vcpop_mask || 8800 IntNo == Intrinsic::riscv_vfirst_mask) 8801 VL = N->getOperand(3); 8802 if (!isNullConstant(VL)) 8803 return SDValue(); 8804 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8805 SDLoc DL(N); 8806 EVT VT = N->getValueType(0); 8807 if (IntNo == Intrinsic::riscv_vfirst || 8808 IntNo == Intrinsic::riscv_vfirst_mask) 8809 return DAG.getConstant(-1, DL, VT); 8810 return DAG.getConstant(0, DL, VT); 8811 } 8812 } 8813 } 8814 } 8815 8816 return SDValue(); 8817 } 8818 8819 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8820 const SDNode *N, CombineLevel Level) const { 8821 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8822 // materialised in fewer instructions than `(OP _, c1)`: 8823 // 8824 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8825 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8826 SDValue N0 = N->getOperand(0); 8827 EVT Ty = N0.getValueType(); 8828 if (Ty.isScalarInteger() && 8829 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8830 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8831 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8832 if (C1 && C2) { 8833 const APInt &C1Int = C1->getAPIntValue(); 8834 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8835 8836 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8837 // and the combine should happen, to potentially allow further combines 8838 // later. 8839 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8840 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8841 return true; 8842 8843 // We can materialise `c1` in an add immediate, so it's "free", and the 8844 // combine should be prevented. 8845 if (C1Int.getMinSignedBits() <= 64 && 8846 isLegalAddImmediate(C1Int.getSExtValue())) 8847 return false; 8848 8849 // Neither constant will fit into an immediate, so find materialisation 8850 // costs. 8851 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8852 Subtarget.getFeatureBits(), 8853 /*CompressionCost*/true); 8854 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8855 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8856 /*CompressionCost*/true); 8857 8858 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8859 // combine should be prevented. 8860 if (C1Cost < ShiftedC1Cost) 8861 return false; 8862 } 8863 } 8864 return true; 8865 } 8866 8867 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8868 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8869 TargetLoweringOpt &TLO) const { 8870 // Delay this optimization as late as possible. 8871 if (!TLO.LegalOps) 8872 return false; 8873 8874 EVT VT = Op.getValueType(); 8875 if (VT.isVector()) 8876 return false; 8877 8878 // Only handle AND for now. 8879 if (Op.getOpcode() != ISD::AND) 8880 return false; 8881 8882 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8883 if (!C) 8884 return false; 8885 8886 const APInt &Mask = C->getAPIntValue(); 8887 8888 // Clear all non-demanded bits initially. 8889 APInt ShrunkMask = Mask & DemandedBits; 8890 8891 // Try to make a smaller immediate by setting undemanded bits. 8892 8893 APInt ExpandedMask = Mask | ~DemandedBits; 8894 8895 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8896 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8897 }; 8898 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8899 if (NewMask == Mask) 8900 return true; 8901 SDLoc DL(Op); 8902 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8903 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8904 return TLO.CombineTo(Op, NewOp); 8905 }; 8906 8907 // If the shrunk mask fits in sign extended 12 bits, let the target 8908 // independent code apply it. 8909 if (ShrunkMask.isSignedIntN(12)) 8910 return false; 8911 8912 // Preserve (and X, 0xffff) when zext.h is supported. 8913 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8914 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8915 if (IsLegalMask(NewMask)) 8916 return UseMask(NewMask); 8917 } 8918 8919 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8920 if (VT == MVT::i64) { 8921 APInt NewMask = APInt(64, 0xffffffff); 8922 if (IsLegalMask(NewMask)) 8923 return UseMask(NewMask); 8924 } 8925 8926 // For the remaining optimizations, we need to be able to make a negative 8927 // number through a combination of mask and undemanded bits. 8928 if (!ExpandedMask.isNegative()) 8929 return false; 8930 8931 // What is the fewest number of bits we need to represent the negative number. 8932 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8933 8934 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8935 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8936 APInt NewMask = ShrunkMask; 8937 if (MinSignedBits <= 12) 8938 NewMask.setBitsFrom(11); 8939 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8940 NewMask.setBitsFrom(31); 8941 else 8942 return false; 8943 8944 // Check that our new mask is a subset of the demanded mask. 8945 assert(IsLegalMask(NewMask)); 8946 return UseMask(NewMask); 8947 } 8948 8949 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 8950 static const uint64_t GREVMasks[] = { 8951 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 8952 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 8953 8954 for (unsigned Stage = 0; Stage != 6; ++Stage) { 8955 unsigned Shift = 1 << Stage; 8956 if (ShAmt & Shift) { 8957 uint64_t Mask = GREVMasks[Stage]; 8958 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 8959 if (IsGORC) 8960 Res |= x; 8961 x = Res; 8962 } 8963 } 8964 8965 return x; 8966 } 8967 8968 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8969 KnownBits &Known, 8970 const APInt &DemandedElts, 8971 const SelectionDAG &DAG, 8972 unsigned Depth) const { 8973 unsigned BitWidth = Known.getBitWidth(); 8974 unsigned Opc = Op.getOpcode(); 8975 assert((Opc >= ISD::BUILTIN_OP_END || 8976 Opc == ISD::INTRINSIC_WO_CHAIN || 8977 Opc == ISD::INTRINSIC_W_CHAIN || 8978 Opc == ISD::INTRINSIC_VOID) && 8979 "Should use MaskedValueIsZero if you don't know whether Op" 8980 " is a target node!"); 8981 8982 Known.resetAll(); 8983 switch (Opc) { 8984 default: break; 8985 case RISCVISD::SELECT_CC: { 8986 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8987 // If we don't know any bits, early out. 8988 if (Known.isUnknown()) 8989 break; 8990 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8991 8992 // Only known if known in both the LHS and RHS. 8993 Known = KnownBits::commonBits(Known, Known2); 8994 break; 8995 } 8996 case RISCVISD::REMUW: { 8997 KnownBits Known2; 8998 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8999 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9000 // We only care about the lower 32 bits. 9001 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9002 // Restore the original width by sign extending. 9003 Known = Known.sext(BitWidth); 9004 break; 9005 } 9006 case RISCVISD::DIVUW: { 9007 KnownBits Known2; 9008 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9009 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9010 // We only care about the lower 32 bits. 9011 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9012 // Restore the original width by sign extending. 9013 Known = Known.sext(BitWidth); 9014 break; 9015 } 9016 case RISCVISD::CTZW: { 9017 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9018 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9019 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9020 Known.Zero.setBitsFrom(LowBits); 9021 break; 9022 } 9023 case RISCVISD::CLZW: { 9024 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9025 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9026 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9027 Known.Zero.setBitsFrom(LowBits); 9028 break; 9029 } 9030 case RISCVISD::GREV: 9031 case RISCVISD::GORC: { 9032 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9033 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9034 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9035 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9036 // To compute zeros, we need to invert the value and invert it back after. 9037 Known.Zero = 9038 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9039 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9040 } 9041 break; 9042 } 9043 case RISCVISD::READ_VLENB: { 9044 // If we know the minimum VLen from Zvl extensions, we can use that to 9045 // determine the trailing zeros of VLENB. 9046 // FIXME: Limit to 128 bit vectors until we have more testing. 9047 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9048 if (MinVLenB > 0) 9049 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9050 // We assume VLENB is no more than 65536 / 8 bytes. 9051 Known.Zero.setBitsFrom(14); 9052 break; 9053 } 9054 case ISD::INTRINSIC_W_CHAIN: 9055 case ISD::INTRINSIC_WO_CHAIN: { 9056 unsigned IntNo = 9057 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9058 switch (IntNo) { 9059 default: 9060 // We can't do anything for most intrinsics. 9061 break; 9062 case Intrinsic::riscv_vsetvli: 9063 case Intrinsic::riscv_vsetvlimax: 9064 case Intrinsic::riscv_vsetvli_opt: 9065 case Intrinsic::riscv_vsetvlimax_opt: 9066 // Assume that VL output is positive and would fit in an int32_t. 9067 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9068 if (BitWidth >= 32) 9069 Known.Zero.setBitsFrom(31); 9070 break; 9071 } 9072 break; 9073 } 9074 } 9075 } 9076 9077 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9078 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9079 unsigned Depth) const { 9080 switch (Op.getOpcode()) { 9081 default: 9082 break; 9083 case RISCVISD::SELECT_CC: { 9084 unsigned Tmp = 9085 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9086 if (Tmp == 1) return 1; // Early out. 9087 unsigned Tmp2 = 9088 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9089 return std::min(Tmp, Tmp2); 9090 } 9091 case RISCVISD::SLLW: 9092 case RISCVISD::SRAW: 9093 case RISCVISD::SRLW: 9094 case RISCVISD::DIVW: 9095 case RISCVISD::DIVUW: 9096 case RISCVISD::REMUW: 9097 case RISCVISD::ROLW: 9098 case RISCVISD::RORW: 9099 case RISCVISD::GREVW: 9100 case RISCVISD::GORCW: 9101 case RISCVISD::FSLW: 9102 case RISCVISD::FSRW: 9103 case RISCVISD::SHFLW: 9104 case RISCVISD::UNSHFLW: 9105 case RISCVISD::BCOMPRESSW: 9106 case RISCVISD::BDECOMPRESSW: 9107 case RISCVISD::BFPW: 9108 case RISCVISD::FCVT_W_RV64: 9109 case RISCVISD::FCVT_WU_RV64: 9110 case RISCVISD::STRICT_FCVT_W_RV64: 9111 case RISCVISD::STRICT_FCVT_WU_RV64: 9112 // TODO: As the result is sign-extended, this is conservatively correct. A 9113 // more precise answer could be calculated for SRAW depending on known 9114 // bits in the shift amount. 9115 return 33; 9116 case RISCVISD::SHFL: 9117 case RISCVISD::UNSHFL: { 9118 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9119 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9120 // will stay within the upper 32 bits. If there were more than 32 sign bits 9121 // before there will be at least 33 sign bits after. 9122 if (Op.getValueType() == MVT::i64 && 9123 isa<ConstantSDNode>(Op.getOperand(1)) && 9124 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9125 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9126 if (Tmp > 32) 9127 return 33; 9128 } 9129 break; 9130 } 9131 case RISCVISD::VMV_X_S: { 9132 // The number of sign bits of the scalar result is computed by obtaining the 9133 // element type of the input vector operand, subtracting its width from the 9134 // XLEN, and then adding one (sign bit within the element type). If the 9135 // element type is wider than XLen, the least-significant XLEN bits are 9136 // taken. 9137 unsigned XLen = Subtarget.getXLen(); 9138 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9139 if (EltBits <= XLen) 9140 return XLen - EltBits + 1; 9141 break; 9142 } 9143 } 9144 9145 return 1; 9146 } 9147 9148 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9149 MachineBasicBlock *BB) { 9150 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9151 9152 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9153 // Should the count have wrapped while it was being read, we need to try 9154 // again. 9155 // ... 9156 // read: 9157 // rdcycleh x3 # load high word of cycle 9158 // rdcycle x2 # load low word of cycle 9159 // rdcycleh x4 # load high word of cycle 9160 // bne x3, x4, read # check if high word reads match, otherwise try again 9161 // ... 9162 9163 MachineFunction &MF = *BB->getParent(); 9164 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9165 MachineFunction::iterator It = ++BB->getIterator(); 9166 9167 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9168 MF.insert(It, LoopMBB); 9169 9170 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9171 MF.insert(It, DoneMBB); 9172 9173 // Transfer the remainder of BB and its successor edges to DoneMBB. 9174 DoneMBB->splice(DoneMBB->begin(), BB, 9175 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9176 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9177 9178 BB->addSuccessor(LoopMBB); 9179 9180 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9181 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9182 Register LoReg = MI.getOperand(0).getReg(); 9183 Register HiReg = MI.getOperand(1).getReg(); 9184 DebugLoc DL = MI.getDebugLoc(); 9185 9186 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9187 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9188 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9189 .addReg(RISCV::X0); 9190 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9191 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9192 .addReg(RISCV::X0); 9193 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9194 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9195 .addReg(RISCV::X0); 9196 9197 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9198 .addReg(HiReg) 9199 .addReg(ReadAgainReg) 9200 .addMBB(LoopMBB); 9201 9202 LoopMBB->addSuccessor(LoopMBB); 9203 LoopMBB->addSuccessor(DoneMBB); 9204 9205 MI.eraseFromParent(); 9206 9207 return DoneMBB; 9208 } 9209 9210 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9211 MachineBasicBlock *BB) { 9212 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9213 9214 MachineFunction &MF = *BB->getParent(); 9215 DebugLoc DL = MI.getDebugLoc(); 9216 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9217 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9218 Register LoReg = MI.getOperand(0).getReg(); 9219 Register HiReg = MI.getOperand(1).getReg(); 9220 Register SrcReg = MI.getOperand(2).getReg(); 9221 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9222 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9223 9224 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9225 RI); 9226 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9227 MachineMemOperand *MMOLo = 9228 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9229 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9230 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9231 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9232 .addFrameIndex(FI) 9233 .addImm(0) 9234 .addMemOperand(MMOLo); 9235 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9236 .addFrameIndex(FI) 9237 .addImm(4) 9238 .addMemOperand(MMOHi); 9239 MI.eraseFromParent(); // The pseudo instruction is gone now. 9240 return BB; 9241 } 9242 9243 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9244 MachineBasicBlock *BB) { 9245 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9246 "Unexpected instruction"); 9247 9248 MachineFunction &MF = *BB->getParent(); 9249 DebugLoc DL = MI.getDebugLoc(); 9250 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9251 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9252 Register DstReg = MI.getOperand(0).getReg(); 9253 Register LoReg = MI.getOperand(1).getReg(); 9254 Register HiReg = MI.getOperand(2).getReg(); 9255 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9256 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9257 9258 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9259 MachineMemOperand *MMOLo = 9260 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9261 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9262 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9263 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9264 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9265 .addFrameIndex(FI) 9266 .addImm(0) 9267 .addMemOperand(MMOLo); 9268 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9269 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9270 .addFrameIndex(FI) 9271 .addImm(4) 9272 .addMemOperand(MMOHi); 9273 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9274 MI.eraseFromParent(); // The pseudo instruction is gone now. 9275 return BB; 9276 } 9277 9278 static bool isSelectPseudo(MachineInstr &MI) { 9279 switch (MI.getOpcode()) { 9280 default: 9281 return false; 9282 case RISCV::Select_GPR_Using_CC_GPR: 9283 case RISCV::Select_FPR16_Using_CC_GPR: 9284 case RISCV::Select_FPR32_Using_CC_GPR: 9285 case RISCV::Select_FPR64_Using_CC_GPR: 9286 return true; 9287 } 9288 } 9289 9290 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9291 unsigned RelOpcode, unsigned EqOpcode, 9292 const RISCVSubtarget &Subtarget) { 9293 DebugLoc DL = MI.getDebugLoc(); 9294 Register DstReg = MI.getOperand(0).getReg(); 9295 Register Src1Reg = MI.getOperand(1).getReg(); 9296 Register Src2Reg = MI.getOperand(2).getReg(); 9297 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9298 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9299 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9300 9301 // Save the current FFLAGS. 9302 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9303 9304 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9305 .addReg(Src1Reg) 9306 .addReg(Src2Reg); 9307 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9308 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9309 9310 // Restore the FFLAGS. 9311 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9312 .addReg(SavedFFlags, RegState::Kill); 9313 9314 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9315 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9316 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9317 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9318 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9319 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9320 9321 // Erase the pseudoinstruction. 9322 MI.eraseFromParent(); 9323 return BB; 9324 } 9325 9326 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9327 MachineBasicBlock *BB, 9328 const RISCVSubtarget &Subtarget) { 9329 // To "insert" Select_* instructions, we actually have to insert the triangle 9330 // control-flow pattern. The incoming instructions know the destination vreg 9331 // to set, the condition code register to branch on, the true/false values to 9332 // select between, and the condcode to use to select the appropriate branch. 9333 // 9334 // We produce the following control flow: 9335 // HeadMBB 9336 // | \ 9337 // | IfFalseMBB 9338 // | / 9339 // TailMBB 9340 // 9341 // When we find a sequence of selects we attempt to optimize their emission 9342 // by sharing the control flow. Currently we only handle cases where we have 9343 // multiple selects with the exact same condition (same LHS, RHS and CC). 9344 // The selects may be interleaved with other instructions if the other 9345 // instructions meet some requirements we deem safe: 9346 // - They are debug instructions. Otherwise, 9347 // - They do not have side-effects, do not access memory and their inputs do 9348 // not depend on the results of the select pseudo-instructions. 9349 // The TrueV/FalseV operands of the selects cannot depend on the result of 9350 // previous selects in the sequence. 9351 // These conditions could be further relaxed. See the X86 target for a 9352 // related approach and more information. 9353 Register LHS = MI.getOperand(1).getReg(); 9354 Register RHS = MI.getOperand(2).getReg(); 9355 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9356 9357 SmallVector<MachineInstr *, 4> SelectDebugValues; 9358 SmallSet<Register, 4> SelectDests; 9359 SelectDests.insert(MI.getOperand(0).getReg()); 9360 9361 MachineInstr *LastSelectPseudo = &MI; 9362 9363 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9364 SequenceMBBI != E; ++SequenceMBBI) { 9365 if (SequenceMBBI->isDebugInstr()) 9366 continue; 9367 else if (isSelectPseudo(*SequenceMBBI)) { 9368 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9369 SequenceMBBI->getOperand(2).getReg() != RHS || 9370 SequenceMBBI->getOperand(3).getImm() != CC || 9371 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9372 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9373 break; 9374 LastSelectPseudo = &*SequenceMBBI; 9375 SequenceMBBI->collectDebugValues(SelectDebugValues); 9376 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9377 } else { 9378 if (SequenceMBBI->hasUnmodeledSideEffects() || 9379 SequenceMBBI->mayLoadOrStore()) 9380 break; 9381 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9382 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9383 })) 9384 break; 9385 } 9386 } 9387 9388 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9389 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9390 DebugLoc DL = MI.getDebugLoc(); 9391 MachineFunction::iterator I = ++BB->getIterator(); 9392 9393 MachineBasicBlock *HeadMBB = BB; 9394 MachineFunction *F = BB->getParent(); 9395 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9396 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9397 9398 F->insert(I, IfFalseMBB); 9399 F->insert(I, TailMBB); 9400 9401 // Transfer debug instructions associated with the selects to TailMBB. 9402 for (MachineInstr *DebugInstr : SelectDebugValues) { 9403 TailMBB->push_back(DebugInstr->removeFromParent()); 9404 } 9405 9406 // Move all instructions after the sequence to TailMBB. 9407 TailMBB->splice(TailMBB->end(), HeadMBB, 9408 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9409 // Update machine-CFG edges by transferring all successors of the current 9410 // block to the new block which will contain the Phi nodes for the selects. 9411 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9412 // Set the successors for HeadMBB. 9413 HeadMBB->addSuccessor(IfFalseMBB); 9414 HeadMBB->addSuccessor(TailMBB); 9415 9416 // Insert appropriate branch. 9417 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9418 .addReg(LHS) 9419 .addReg(RHS) 9420 .addMBB(TailMBB); 9421 9422 // IfFalseMBB just falls through to TailMBB. 9423 IfFalseMBB->addSuccessor(TailMBB); 9424 9425 // Create PHIs for all of the select pseudo-instructions. 9426 auto SelectMBBI = MI.getIterator(); 9427 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9428 auto InsertionPoint = TailMBB->begin(); 9429 while (SelectMBBI != SelectEnd) { 9430 auto Next = std::next(SelectMBBI); 9431 if (isSelectPseudo(*SelectMBBI)) { 9432 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9433 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9434 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9435 .addReg(SelectMBBI->getOperand(4).getReg()) 9436 .addMBB(HeadMBB) 9437 .addReg(SelectMBBI->getOperand(5).getReg()) 9438 .addMBB(IfFalseMBB); 9439 SelectMBBI->eraseFromParent(); 9440 } 9441 SelectMBBI = Next; 9442 } 9443 9444 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9445 return TailMBB; 9446 } 9447 9448 MachineBasicBlock * 9449 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9450 MachineBasicBlock *BB) const { 9451 switch (MI.getOpcode()) { 9452 default: 9453 llvm_unreachable("Unexpected instr type to insert"); 9454 case RISCV::ReadCycleWide: 9455 assert(!Subtarget.is64Bit() && 9456 "ReadCycleWrite is only to be used on riscv32"); 9457 return emitReadCycleWidePseudo(MI, BB); 9458 case RISCV::Select_GPR_Using_CC_GPR: 9459 case RISCV::Select_FPR16_Using_CC_GPR: 9460 case RISCV::Select_FPR32_Using_CC_GPR: 9461 case RISCV::Select_FPR64_Using_CC_GPR: 9462 return emitSelectPseudo(MI, BB, Subtarget); 9463 case RISCV::BuildPairF64Pseudo: 9464 return emitBuildPairF64Pseudo(MI, BB); 9465 case RISCV::SplitF64Pseudo: 9466 return emitSplitF64Pseudo(MI, BB); 9467 case RISCV::PseudoQuietFLE_H: 9468 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9469 case RISCV::PseudoQuietFLT_H: 9470 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9471 case RISCV::PseudoQuietFLE_S: 9472 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9473 case RISCV::PseudoQuietFLT_S: 9474 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9475 case RISCV::PseudoQuietFLE_D: 9476 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9477 case RISCV::PseudoQuietFLT_D: 9478 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9479 } 9480 } 9481 9482 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9483 SDNode *Node) const { 9484 // Add FRM dependency to any instructions with dynamic rounding mode. 9485 unsigned Opc = MI.getOpcode(); 9486 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9487 if (Idx < 0) 9488 return; 9489 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9490 return; 9491 // If the instruction already reads FRM, don't add another read. 9492 if (MI.readsRegister(RISCV::FRM)) 9493 return; 9494 MI.addOperand( 9495 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9496 } 9497 9498 // Calling Convention Implementation. 9499 // The expectations for frontend ABI lowering vary from target to target. 9500 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9501 // details, but this is a longer term goal. For now, we simply try to keep the 9502 // role of the frontend as simple and well-defined as possible. The rules can 9503 // be summarised as: 9504 // * Never split up large scalar arguments. We handle them here. 9505 // * If a hardfloat calling convention is being used, and the struct may be 9506 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9507 // available, then pass as two separate arguments. If either the GPRs or FPRs 9508 // are exhausted, then pass according to the rule below. 9509 // * If a struct could never be passed in registers or directly in a stack 9510 // slot (as it is larger than 2*XLEN and the floating point rules don't 9511 // apply), then pass it using a pointer with the byval attribute. 9512 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9513 // word-sized array or a 2*XLEN scalar (depending on alignment). 9514 // * The frontend can determine whether a struct is returned by reference or 9515 // not based on its size and fields. If it will be returned by reference, the 9516 // frontend must modify the prototype so a pointer with the sret annotation is 9517 // passed as the first argument. This is not necessary for large scalar 9518 // returns. 9519 // * Struct return values and varargs should be coerced to structs containing 9520 // register-size fields in the same situations they would be for fixed 9521 // arguments. 9522 9523 static const MCPhysReg ArgGPRs[] = { 9524 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9525 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9526 }; 9527 static const MCPhysReg ArgFPR16s[] = { 9528 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9529 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9530 }; 9531 static const MCPhysReg ArgFPR32s[] = { 9532 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9533 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9534 }; 9535 static const MCPhysReg ArgFPR64s[] = { 9536 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9537 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9538 }; 9539 // This is an interim calling convention and it may be changed in the future. 9540 static const MCPhysReg ArgVRs[] = { 9541 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9542 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9543 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9544 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9545 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9546 RISCV::V20M2, RISCV::V22M2}; 9547 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9548 RISCV::V20M4}; 9549 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9550 9551 // Pass a 2*XLEN argument that has been split into two XLEN values through 9552 // registers or the stack as necessary. 9553 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9554 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9555 MVT ValVT2, MVT LocVT2, 9556 ISD::ArgFlagsTy ArgFlags2) { 9557 unsigned XLenInBytes = XLen / 8; 9558 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9559 // At least one half can be passed via register. 9560 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9561 VA1.getLocVT(), CCValAssign::Full)); 9562 } else { 9563 // Both halves must be passed on the stack, with proper alignment. 9564 Align StackAlign = 9565 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9566 State.addLoc( 9567 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9568 State.AllocateStack(XLenInBytes, StackAlign), 9569 VA1.getLocVT(), CCValAssign::Full)); 9570 State.addLoc(CCValAssign::getMem( 9571 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9572 LocVT2, CCValAssign::Full)); 9573 return false; 9574 } 9575 9576 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9577 // The second half can also be passed via register. 9578 State.addLoc( 9579 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9580 } else { 9581 // The second half is passed via the stack, without additional alignment. 9582 State.addLoc(CCValAssign::getMem( 9583 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9584 LocVT2, CCValAssign::Full)); 9585 } 9586 9587 return false; 9588 } 9589 9590 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9591 Optional<unsigned> FirstMaskArgument, 9592 CCState &State, const RISCVTargetLowering &TLI) { 9593 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9594 if (RC == &RISCV::VRRegClass) { 9595 // Assign the first mask argument to V0. 9596 // This is an interim calling convention and it may be changed in the 9597 // future. 9598 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9599 return State.AllocateReg(RISCV::V0); 9600 return State.AllocateReg(ArgVRs); 9601 } 9602 if (RC == &RISCV::VRM2RegClass) 9603 return State.AllocateReg(ArgVRM2s); 9604 if (RC == &RISCV::VRM4RegClass) 9605 return State.AllocateReg(ArgVRM4s); 9606 if (RC == &RISCV::VRM8RegClass) 9607 return State.AllocateReg(ArgVRM8s); 9608 llvm_unreachable("Unhandled register class for ValueType"); 9609 } 9610 9611 // Implements the RISC-V calling convention. Returns true upon failure. 9612 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9613 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9614 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9615 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9616 Optional<unsigned> FirstMaskArgument) { 9617 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9618 assert(XLen == 32 || XLen == 64); 9619 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9620 9621 // Any return value split in to more than two values can't be returned 9622 // directly. Vectors are returned via the available vector registers. 9623 if (!LocVT.isVector() && IsRet && ValNo > 1) 9624 return true; 9625 9626 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9627 // variadic argument, or if no F16/F32 argument registers are available. 9628 bool UseGPRForF16_F32 = true; 9629 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9630 // variadic argument, or if no F64 argument registers are available. 9631 bool UseGPRForF64 = true; 9632 9633 switch (ABI) { 9634 default: 9635 llvm_unreachable("Unexpected ABI"); 9636 case RISCVABI::ABI_ILP32: 9637 case RISCVABI::ABI_LP64: 9638 break; 9639 case RISCVABI::ABI_ILP32F: 9640 case RISCVABI::ABI_LP64F: 9641 UseGPRForF16_F32 = !IsFixed; 9642 break; 9643 case RISCVABI::ABI_ILP32D: 9644 case RISCVABI::ABI_LP64D: 9645 UseGPRForF16_F32 = !IsFixed; 9646 UseGPRForF64 = !IsFixed; 9647 break; 9648 } 9649 9650 // FPR16, FPR32, and FPR64 alias each other. 9651 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9652 UseGPRForF16_F32 = true; 9653 UseGPRForF64 = true; 9654 } 9655 9656 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9657 // similar local variables rather than directly checking against the target 9658 // ABI. 9659 9660 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9661 LocVT = XLenVT; 9662 LocInfo = CCValAssign::BCvt; 9663 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9664 LocVT = MVT::i64; 9665 LocInfo = CCValAssign::BCvt; 9666 } 9667 9668 // If this is a variadic argument, the RISC-V calling convention requires 9669 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9670 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9671 // be used regardless of whether the original argument was split during 9672 // legalisation or not. The argument will not be passed by registers if the 9673 // original type is larger than 2*XLEN, so the register alignment rule does 9674 // not apply. 9675 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9676 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9677 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9678 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9679 // Skip 'odd' register if necessary. 9680 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9681 State.AllocateReg(ArgGPRs); 9682 } 9683 9684 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9685 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9686 State.getPendingArgFlags(); 9687 9688 assert(PendingLocs.size() == PendingArgFlags.size() && 9689 "PendingLocs and PendingArgFlags out of sync"); 9690 9691 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9692 // registers are exhausted. 9693 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9694 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9695 "Can't lower f64 if it is split"); 9696 // Depending on available argument GPRS, f64 may be passed in a pair of 9697 // GPRs, split between a GPR and the stack, or passed completely on the 9698 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9699 // cases. 9700 Register Reg = State.AllocateReg(ArgGPRs); 9701 LocVT = MVT::i32; 9702 if (!Reg) { 9703 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9704 State.addLoc( 9705 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9706 return false; 9707 } 9708 if (!State.AllocateReg(ArgGPRs)) 9709 State.AllocateStack(4, Align(4)); 9710 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9711 return false; 9712 } 9713 9714 // Fixed-length vectors are located in the corresponding scalable-vector 9715 // container types. 9716 if (ValVT.isFixedLengthVector()) 9717 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9718 9719 // Split arguments might be passed indirectly, so keep track of the pending 9720 // values. Split vectors are passed via a mix of registers and indirectly, so 9721 // treat them as we would any other argument. 9722 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9723 LocVT = XLenVT; 9724 LocInfo = CCValAssign::Indirect; 9725 PendingLocs.push_back( 9726 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9727 PendingArgFlags.push_back(ArgFlags); 9728 if (!ArgFlags.isSplitEnd()) { 9729 return false; 9730 } 9731 } 9732 9733 // If the split argument only had two elements, it should be passed directly 9734 // in registers or on the stack. 9735 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9736 PendingLocs.size() <= 2) { 9737 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9738 // Apply the normal calling convention rules to the first half of the 9739 // split argument. 9740 CCValAssign VA = PendingLocs[0]; 9741 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9742 PendingLocs.clear(); 9743 PendingArgFlags.clear(); 9744 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9745 ArgFlags); 9746 } 9747 9748 // Allocate to a register if possible, or else a stack slot. 9749 Register Reg; 9750 unsigned StoreSizeBytes = XLen / 8; 9751 Align StackAlign = Align(XLen / 8); 9752 9753 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9754 Reg = State.AllocateReg(ArgFPR16s); 9755 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9756 Reg = State.AllocateReg(ArgFPR32s); 9757 else if (ValVT == MVT::f64 && !UseGPRForF64) 9758 Reg = State.AllocateReg(ArgFPR64s); 9759 else if (ValVT.isVector()) { 9760 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9761 if (!Reg) { 9762 // For return values, the vector must be passed fully via registers or 9763 // via the stack. 9764 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9765 // but we're using all of them. 9766 if (IsRet) 9767 return true; 9768 // Try using a GPR to pass the address 9769 if ((Reg = State.AllocateReg(ArgGPRs))) { 9770 LocVT = XLenVT; 9771 LocInfo = CCValAssign::Indirect; 9772 } else if (ValVT.isScalableVector()) { 9773 LocVT = XLenVT; 9774 LocInfo = CCValAssign::Indirect; 9775 } else { 9776 // Pass fixed-length vectors on the stack. 9777 LocVT = ValVT; 9778 StoreSizeBytes = ValVT.getStoreSize(); 9779 // Align vectors to their element sizes, being careful for vXi1 9780 // vectors. 9781 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9782 } 9783 } 9784 } else { 9785 Reg = State.AllocateReg(ArgGPRs); 9786 } 9787 9788 unsigned StackOffset = 9789 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9790 9791 // If we reach this point and PendingLocs is non-empty, we must be at the 9792 // end of a split argument that must be passed indirectly. 9793 if (!PendingLocs.empty()) { 9794 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9795 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9796 9797 for (auto &It : PendingLocs) { 9798 if (Reg) 9799 It.convertToReg(Reg); 9800 else 9801 It.convertToMem(StackOffset); 9802 State.addLoc(It); 9803 } 9804 PendingLocs.clear(); 9805 PendingArgFlags.clear(); 9806 return false; 9807 } 9808 9809 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9810 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9811 "Expected an XLenVT or vector types at this stage"); 9812 9813 if (Reg) { 9814 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9815 return false; 9816 } 9817 9818 // When a floating-point value is passed on the stack, no bit-conversion is 9819 // needed. 9820 if (ValVT.isFloatingPoint()) { 9821 LocVT = ValVT; 9822 LocInfo = CCValAssign::Full; 9823 } 9824 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9825 return false; 9826 } 9827 9828 template <typename ArgTy> 9829 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9830 for (const auto &ArgIdx : enumerate(Args)) { 9831 MVT ArgVT = ArgIdx.value().VT; 9832 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9833 return ArgIdx.index(); 9834 } 9835 return None; 9836 } 9837 9838 void RISCVTargetLowering::analyzeInputArgs( 9839 MachineFunction &MF, CCState &CCInfo, 9840 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9841 RISCVCCAssignFn Fn) const { 9842 unsigned NumArgs = Ins.size(); 9843 FunctionType *FType = MF.getFunction().getFunctionType(); 9844 9845 Optional<unsigned> FirstMaskArgument; 9846 if (Subtarget.hasVInstructions()) 9847 FirstMaskArgument = preAssignMask(Ins); 9848 9849 for (unsigned i = 0; i != NumArgs; ++i) { 9850 MVT ArgVT = Ins[i].VT; 9851 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9852 9853 Type *ArgTy = nullptr; 9854 if (IsRet) 9855 ArgTy = FType->getReturnType(); 9856 else if (Ins[i].isOrigArg()) 9857 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9858 9859 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9860 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9861 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9862 FirstMaskArgument)) { 9863 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9864 << EVT(ArgVT).getEVTString() << '\n'); 9865 llvm_unreachable(nullptr); 9866 } 9867 } 9868 } 9869 9870 void RISCVTargetLowering::analyzeOutputArgs( 9871 MachineFunction &MF, CCState &CCInfo, 9872 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9873 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9874 unsigned NumArgs = Outs.size(); 9875 9876 Optional<unsigned> FirstMaskArgument; 9877 if (Subtarget.hasVInstructions()) 9878 FirstMaskArgument = preAssignMask(Outs); 9879 9880 for (unsigned i = 0; i != NumArgs; i++) { 9881 MVT ArgVT = Outs[i].VT; 9882 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9883 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9884 9885 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9886 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9887 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9888 FirstMaskArgument)) { 9889 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9890 << EVT(ArgVT).getEVTString() << "\n"); 9891 llvm_unreachable(nullptr); 9892 } 9893 } 9894 } 9895 9896 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9897 // values. 9898 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9899 const CCValAssign &VA, const SDLoc &DL, 9900 const RISCVSubtarget &Subtarget) { 9901 switch (VA.getLocInfo()) { 9902 default: 9903 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9904 case CCValAssign::Full: 9905 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9906 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9907 break; 9908 case CCValAssign::BCvt: 9909 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9910 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9911 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9912 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9913 else 9914 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9915 break; 9916 } 9917 return Val; 9918 } 9919 9920 // The caller is responsible for loading the full value if the argument is 9921 // passed with CCValAssign::Indirect. 9922 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9923 const CCValAssign &VA, const SDLoc &DL, 9924 const RISCVTargetLowering &TLI) { 9925 MachineFunction &MF = DAG.getMachineFunction(); 9926 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9927 EVT LocVT = VA.getLocVT(); 9928 SDValue Val; 9929 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9930 Register VReg = RegInfo.createVirtualRegister(RC); 9931 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9932 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9933 9934 if (VA.getLocInfo() == CCValAssign::Indirect) 9935 return Val; 9936 9937 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9938 } 9939 9940 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9941 const CCValAssign &VA, const SDLoc &DL, 9942 const RISCVSubtarget &Subtarget) { 9943 EVT LocVT = VA.getLocVT(); 9944 9945 switch (VA.getLocInfo()) { 9946 default: 9947 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9948 case CCValAssign::Full: 9949 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9950 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9951 break; 9952 case CCValAssign::BCvt: 9953 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9954 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9955 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9956 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9957 else 9958 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9959 break; 9960 } 9961 return Val; 9962 } 9963 9964 // The caller is responsible for loading the full value if the argument is 9965 // passed with CCValAssign::Indirect. 9966 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9967 const CCValAssign &VA, const SDLoc &DL) { 9968 MachineFunction &MF = DAG.getMachineFunction(); 9969 MachineFrameInfo &MFI = MF.getFrameInfo(); 9970 EVT LocVT = VA.getLocVT(); 9971 EVT ValVT = VA.getValVT(); 9972 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9973 if (ValVT.isScalableVector()) { 9974 // When the value is a scalable vector, we save the pointer which points to 9975 // the scalable vector value in the stack. The ValVT will be the pointer 9976 // type, instead of the scalable vector type. 9977 ValVT = LocVT; 9978 } 9979 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9980 /*IsImmutable=*/true); 9981 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9982 SDValue Val; 9983 9984 ISD::LoadExtType ExtType; 9985 switch (VA.getLocInfo()) { 9986 default: 9987 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9988 case CCValAssign::Full: 9989 case CCValAssign::Indirect: 9990 case CCValAssign::BCvt: 9991 ExtType = ISD::NON_EXTLOAD; 9992 break; 9993 } 9994 Val = DAG.getExtLoad( 9995 ExtType, DL, LocVT, Chain, FIN, 9996 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9997 return Val; 9998 } 9999 10000 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10001 const CCValAssign &VA, const SDLoc &DL) { 10002 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10003 "Unexpected VA"); 10004 MachineFunction &MF = DAG.getMachineFunction(); 10005 MachineFrameInfo &MFI = MF.getFrameInfo(); 10006 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10007 10008 if (VA.isMemLoc()) { 10009 // f64 is passed on the stack. 10010 int FI = 10011 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10012 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10013 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10014 MachinePointerInfo::getFixedStack(MF, FI)); 10015 } 10016 10017 assert(VA.isRegLoc() && "Expected register VA assignment"); 10018 10019 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10020 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10021 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10022 SDValue Hi; 10023 if (VA.getLocReg() == RISCV::X17) { 10024 // Second half of f64 is passed on the stack. 10025 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10026 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10027 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10028 MachinePointerInfo::getFixedStack(MF, FI)); 10029 } else { 10030 // Second half of f64 is passed in another GPR. 10031 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10032 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10033 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10034 } 10035 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10036 } 10037 10038 // FastCC has less than 1% performance improvement for some particular 10039 // benchmark. But theoretically, it may has benenfit for some cases. 10040 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10041 unsigned ValNo, MVT ValVT, MVT LocVT, 10042 CCValAssign::LocInfo LocInfo, 10043 ISD::ArgFlagsTy ArgFlags, CCState &State, 10044 bool IsFixed, bool IsRet, Type *OrigTy, 10045 const RISCVTargetLowering &TLI, 10046 Optional<unsigned> FirstMaskArgument) { 10047 10048 // X5 and X6 might be used for save-restore libcall. 10049 static const MCPhysReg GPRList[] = { 10050 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10051 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10052 RISCV::X29, RISCV::X30, RISCV::X31}; 10053 10054 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10055 if (unsigned Reg = State.AllocateReg(GPRList)) { 10056 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10057 return false; 10058 } 10059 } 10060 10061 if (LocVT == MVT::f16) { 10062 static const MCPhysReg FPR16List[] = { 10063 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10064 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10065 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10066 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10067 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10068 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10069 return false; 10070 } 10071 } 10072 10073 if (LocVT == MVT::f32) { 10074 static const MCPhysReg FPR32List[] = { 10075 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10076 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10077 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10078 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10079 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10080 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10081 return false; 10082 } 10083 } 10084 10085 if (LocVT == MVT::f64) { 10086 static const MCPhysReg FPR64List[] = { 10087 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10088 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10089 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10090 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10091 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10092 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10093 return false; 10094 } 10095 } 10096 10097 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10098 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10099 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10100 return false; 10101 } 10102 10103 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10104 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10105 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10106 return false; 10107 } 10108 10109 if (LocVT.isVector()) { 10110 if (unsigned Reg = 10111 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10112 // Fixed-length vectors are located in the corresponding scalable-vector 10113 // container types. 10114 if (ValVT.isFixedLengthVector()) 10115 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10116 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10117 } else { 10118 // Try and pass the address via a "fast" GPR. 10119 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10120 LocInfo = CCValAssign::Indirect; 10121 LocVT = TLI.getSubtarget().getXLenVT(); 10122 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10123 } else if (ValVT.isFixedLengthVector()) { 10124 auto StackAlign = 10125 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10126 unsigned StackOffset = 10127 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10128 State.addLoc( 10129 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10130 } else { 10131 // Can't pass scalable vectors on the stack. 10132 return true; 10133 } 10134 } 10135 10136 return false; 10137 } 10138 10139 return true; // CC didn't match. 10140 } 10141 10142 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10143 CCValAssign::LocInfo LocInfo, 10144 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10145 10146 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10147 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10148 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10149 static const MCPhysReg GPRList[] = { 10150 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10151 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10152 if (unsigned Reg = State.AllocateReg(GPRList)) { 10153 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10154 return false; 10155 } 10156 } 10157 10158 if (LocVT == MVT::f32) { 10159 // Pass in STG registers: F1, ..., F6 10160 // fs0 ... fs5 10161 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10162 RISCV::F18_F, RISCV::F19_F, 10163 RISCV::F20_F, RISCV::F21_F}; 10164 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10165 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10166 return false; 10167 } 10168 } 10169 10170 if (LocVT == MVT::f64) { 10171 // Pass in STG registers: D1, ..., D6 10172 // fs6 ... fs11 10173 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10174 RISCV::F24_D, RISCV::F25_D, 10175 RISCV::F26_D, RISCV::F27_D}; 10176 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10177 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10178 return false; 10179 } 10180 } 10181 10182 report_fatal_error("No registers left in GHC calling convention"); 10183 return true; 10184 } 10185 10186 // Transform physical registers into virtual registers. 10187 SDValue RISCVTargetLowering::LowerFormalArguments( 10188 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10189 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10190 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10191 10192 MachineFunction &MF = DAG.getMachineFunction(); 10193 10194 switch (CallConv) { 10195 default: 10196 report_fatal_error("Unsupported calling convention"); 10197 case CallingConv::C: 10198 case CallingConv::Fast: 10199 break; 10200 case CallingConv::GHC: 10201 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10202 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10203 report_fatal_error( 10204 "GHC calling convention requires the F and D instruction set extensions"); 10205 } 10206 10207 const Function &Func = MF.getFunction(); 10208 if (Func.hasFnAttribute("interrupt")) { 10209 if (!Func.arg_empty()) 10210 report_fatal_error( 10211 "Functions with the interrupt attribute cannot have arguments!"); 10212 10213 StringRef Kind = 10214 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10215 10216 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10217 report_fatal_error( 10218 "Function interrupt attribute argument not supported!"); 10219 } 10220 10221 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10222 MVT XLenVT = Subtarget.getXLenVT(); 10223 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10224 // Used with vargs to acumulate store chains. 10225 std::vector<SDValue> OutChains; 10226 10227 // Assign locations to all of the incoming arguments. 10228 SmallVector<CCValAssign, 16> ArgLocs; 10229 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10230 10231 if (CallConv == CallingConv::GHC) 10232 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10233 else 10234 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10235 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10236 : CC_RISCV); 10237 10238 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10239 CCValAssign &VA = ArgLocs[i]; 10240 SDValue ArgValue; 10241 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10242 // case. 10243 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10244 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10245 else if (VA.isRegLoc()) 10246 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10247 else 10248 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10249 10250 if (VA.getLocInfo() == CCValAssign::Indirect) { 10251 // If the original argument was split and passed by reference (e.g. i128 10252 // on RV32), we need to load all parts of it here (using the same 10253 // address). Vectors may be partly split to registers and partly to the 10254 // stack, in which case the base address is partly offset and subsequent 10255 // stores are relative to that. 10256 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10257 MachinePointerInfo())); 10258 unsigned ArgIndex = Ins[i].OrigArgIndex; 10259 unsigned ArgPartOffset = Ins[i].PartOffset; 10260 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10261 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10262 CCValAssign &PartVA = ArgLocs[i + 1]; 10263 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10264 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10265 if (PartVA.getValVT().isScalableVector()) 10266 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10267 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10268 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10269 MachinePointerInfo())); 10270 ++i; 10271 } 10272 continue; 10273 } 10274 InVals.push_back(ArgValue); 10275 } 10276 10277 if (IsVarArg) { 10278 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10279 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10280 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10281 MachineFrameInfo &MFI = MF.getFrameInfo(); 10282 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10283 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10284 10285 // Offset of the first variable argument from stack pointer, and size of 10286 // the vararg save area. For now, the varargs save area is either zero or 10287 // large enough to hold a0-a7. 10288 int VaArgOffset, VarArgsSaveSize; 10289 10290 // If all registers are allocated, then all varargs must be passed on the 10291 // stack and we don't need to save any argregs. 10292 if (ArgRegs.size() == Idx) { 10293 VaArgOffset = CCInfo.getNextStackOffset(); 10294 VarArgsSaveSize = 0; 10295 } else { 10296 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10297 VaArgOffset = -VarArgsSaveSize; 10298 } 10299 10300 // Record the frame index of the first variable argument 10301 // which is a value necessary to VASTART. 10302 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10303 RVFI->setVarArgsFrameIndex(FI); 10304 10305 // If saving an odd number of registers then create an extra stack slot to 10306 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10307 // offsets to even-numbered registered remain 2*XLEN-aligned. 10308 if (Idx % 2) { 10309 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10310 VarArgsSaveSize += XLenInBytes; 10311 } 10312 10313 // Copy the integer registers that may have been used for passing varargs 10314 // to the vararg save area. 10315 for (unsigned I = Idx; I < ArgRegs.size(); 10316 ++I, VaArgOffset += XLenInBytes) { 10317 const Register Reg = RegInfo.createVirtualRegister(RC); 10318 RegInfo.addLiveIn(ArgRegs[I], Reg); 10319 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10320 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10321 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10322 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10323 MachinePointerInfo::getFixedStack(MF, FI)); 10324 cast<StoreSDNode>(Store.getNode()) 10325 ->getMemOperand() 10326 ->setValue((Value *)nullptr); 10327 OutChains.push_back(Store); 10328 } 10329 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10330 } 10331 10332 // All stores are grouped in one node to allow the matching between 10333 // the size of Ins and InVals. This only happens for vararg functions. 10334 if (!OutChains.empty()) { 10335 OutChains.push_back(Chain); 10336 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10337 } 10338 10339 return Chain; 10340 } 10341 10342 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10343 /// for tail call optimization. 10344 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10345 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10346 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10347 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10348 10349 auto &Callee = CLI.Callee; 10350 auto CalleeCC = CLI.CallConv; 10351 auto &Outs = CLI.Outs; 10352 auto &Caller = MF.getFunction(); 10353 auto CallerCC = Caller.getCallingConv(); 10354 10355 // Exception-handling functions need a special set of instructions to 10356 // indicate a return to the hardware. Tail-calling another function would 10357 // probably break this. 10358 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10359 // should be expanded as new function attributes are introduced. 10360 if (Caller.hasFnAttribute("interrupt")) 10361 return false; 10362 10363 // Do not tail call opt if the stack is used to pass parameters. 10364 if (CCInfo.getNextStackOffset() != 0) 10365 return false; 10366 10367 // Do not tail call opt if any parameters need to be passed indirectly. 10368 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10369 // passed indirectly. So the address of the value will be passed in a 10370 // register, or if not available, then the address is put on the stack. In 10371 // order to pass indirectly, space on the stack often needs to be allocated 10372 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10373 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10374 // are passed CCValAssign::Indirect. 10375 for (auto &VA : ArgLocs) 10376 if (VA.getLocInfo() == CCValAssign::Indirect) 10377 return false; 10378 10379 // Do not tail call opt if either caller or callee uses struct return 10380 // semantics. 10381 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10382 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10383 if (IsCallerStructRet || IsCalleeStructRet) 10384 return false; 10385 10386 // Externally-defined functions with weak linkage should not be 10387 // tail-called. The behaviour of branch instructions in this situation (as 10388 // used for tail calls) is implementation-defined, so we cannot rely on the 10389 // linker replacing the tail call with a return. 10390 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10391 const GlobalValue *GV = G->getGlobal(); 10392 if (GV->hasExternalWeakLinkage()) 10393 return false; 10394 } 10395 10396 // The callee has to preserve all registers the caller needs to preserve. 10397 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10398 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10399 if (CalleeCC != CallerCC) { 10400 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10401 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10402 return false; 10403 } 10404 10405 // Byval parameters hand the function a pointer directly into the stack area 10406 // we want to reuse during a tail call. Working around this *is* possible 10407 // but less efficient and uglier in LowerCall. 10408 for (auto &Arg : Outs) 10409 if (Arg.Flags.isByVal()) 10410 return false; 10411 10412 return true; 10413 } 10414 10415 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10416 return DAG.getDataLayout().getPrefTypeAlign( 10417 VT.getTypeForEVT(*DAG.getContext())); 10418 } 10419 10420 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10421 // and output parameter nodes. 10422 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10423 SmallVectorImpl<SDValue> &InVals) const { 10424 SelectionDAG &DAG = CLI.DAG; 10425 SDLoc &DL = CLI.DL; 10426 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10427 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10428 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10429 SDValue Chain = CLI.Chain; 10430 SDValue Callee = CLI.Callee; 10431 bool &IsTailCall = CLI.IsTailCall; 10432 CallingConv::ID CallConv = CLI.CallConv; 10433 bool IsVarArg = CLI.IsVarArg; 10434 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10435 MVT XLenVT = Subtarget.getXLenVT(); 10436 10437 MachineFunction &MF = DAG.getMachineFunction(); 10438 10439 // Analyze the operands of the call, assigning locations to each operand. 10440 SmallVector<CCValAssign, 16> ArgLocs; 10441 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10442 10443 if (CallConv == CallingConv::GHC) 10444 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10445 else 10446 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10447 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10448 : CC_RISCV); 10449 10450 // Check if it's really possible to do a tail call. 10451 if (IsTailCall) 10452 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10453 10454 if (IsTailCall) 10455 ++NumTailCalls; 10456 else if (CLI.CB && CLI.CB->isMustTailCall()) 10457 report_fatal_error("failed to perform tail call elimination on a call " 10458 "site marked musttail"); 10459 10460 // Get a count of how many bytes are to be pushed on the stack. 10461 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10462 10463 // Create local copies for byval args 10464 SmallVector<SDValue, 8> ByValArgs; 10465 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10466 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10467 if (!Flags.isByVal()) 10468 continue; 10469 10470 SDValue Arg = OutVals[i]; 10471 unsigned Size = Flags.getByValSize(); 10472 Align Alignment = Flags.getNonZeroByValAlign(); 10473 10474 int FI = 10475 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10476 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10477 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10478 10479 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10480 /*IsVolatile=*/false, 10481 /*AlwaysInline=*/false, IsTailCall, 10482 MachinePointerInfo(), MachinePointerInfo()); 10483 ByValArgs.push_back(FIPtr); 10484 } 10485 10486 if (!IsTailCall) 10487 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10488 10489 // Copy argument values to their designated locations. 10490 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10491 SmallVector<SDValue, 8> MemOpChains; 10492 SDValue StackPtr; 10493 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10494 CCValAssign &VA = ArgLocs[i]; 10495 SDValue ArgValue = OutVals[i]; 10496 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10497 10498 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10499 bool IsF64OnRV32DSoftABI = 10500 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10501 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10502 SDValue SplitF64 = DAG.getNode( 10503 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10504 SDValue Lo = SplitF64.getValue(0); 10505 SDValue Hi = SplitF64.getValue(1); 10506 10507 Register RegLo = VA.getLocReg(); 10508 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10509 10510 if (RegLo == RISCV::X17) { 10511 // Second half of f64 is passed on the stack. 10512 // Work out the address of the stack slot. 10513 if (!StackPtr.getNode()) 10514 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10515 // Emit the store. 10516 MemOpChains.push_back( 10517 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10518 } else { 10519 // Second half of f64 is passed in another GPR. 10520 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10521 Register RegHigh = RegLo + 1; 10522 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10523 } 10524 continue; 10525 } 10526 10527 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10528 // as any other MemLoc. 10529 10530 // Promote the value if needed. 10531 // For now, only handle fully promoted and indirect arguments. 10532 if (VA.getLocInfo() == CCValAssign::Indirect) { 10533 // Store the argument in a stack slot and pass its address. 10534 Align StackAlign = 10535 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10536 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10537 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10538 // If the original argument was split (e.g. i128), we need 10539 // to store the required parts of it here (and pass just one address). 10540 // Vectors may be partly split to registers and partly to the stack, in 10541 // which case the base address is partly offset and subsequent stores are 10542 // relative to that. 10543 unsigned ArgIndex = Outs[i].OrigArgIndex; 10544 unsigned ArgPartOffset = Outs[i].PartOffset; 10545 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10546 // Calculate the total size to store. We don't have access to what we're 10547 // actually storing other than performing the loop and collecting the 10548 // info. 10549 SmallVector<std::pair<SDValue, SDValue>> Parts; 10550 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10551 SDValue PartValue = OutVals[i + 1]; 10552 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10553 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10554 EVT PartVT = PartValue.getValueType(); 10555 if (PartVT.isScalableVector()) 10556 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10557 StoredSize += PartVT.getStoreSize(); 10558 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10559 Parts.push_back(std::make_pair(PartValue, Offset)); 10560 ++i; 10561 } 10562 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10563 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10564 MemOpChains.push_back( 10565 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10566 MachinePointerInfo::getFixedStack(MF, FI))); 10567 for (const auto &Part : Parts) { 10568 SDValue PartValue = Part.first; 10569 SDValue PartOffset = Part.second; 10570 SDValue Address = 10571 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10572 MemOpChains.push_back( 10573 DAG.getStore(Chain, DL, PartValue, Address, 10574 MachinePointerInfo::getFixedStack(MF, FI))); 10575 } 10576 ArgValue = SpillSlot; 10577 } else { 10578 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10579 } 10580 10581 // Use local copy if it is a byval arg. 10582 if (Flags.isByVal()) 10583 ArgValue = ByValArgs[j++]; 10584 10585 if (VA.isRegLoc()) { 10586 // Queue up the argument copies and emit them at the end. 10587 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10588 } else { 10589 assert(VA.isMemLoc() && "Argument not register or memory"); 10590 assert(!IsTailCall && "Tail call not allowed if stack is used " 10591 "for passing parameters"); 10592 10593 // Work out the address of the stack slot. 10594 if (!StackPtr.getNode()) 10595 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10596 SDValue Address = 10597 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10598 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10599 10600 // Emit the store. 10601 MemOpChains.push_back( 10602 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10603 } 10604 } 10605 10606 // Join the stores, which are independent of one another. 10607 if (!MemOpChains.empty()) 10608 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10609 10610 SDValue Glue; 10611 10612 // Build a sequence of copy-to-reg nodes, chained and glued together. 10613 for (auto &Reg : RegsToPass) { 10614 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10615 Glue = Chain.getValue(1); 10616 } 10617 10618 // Validate that none of the argument registers have been marked as 10619 // reserved, if so report an error. Do the same for the return address if this 10620 // is not a tailcall. 10621 validateCCReservedRegs(RegsToPass, MF); 10622 if (!IsTailCall && 10623 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10624 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10625 MF.getFunction(), 10626 "Return address register required, but has been reserved."}); 10627 10628 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10629 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10630 // split it and then direct call can be matched by PseudoCALL. 10631 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10632 const GlobalValue *GV = S->getGlobal(); 10633 10634 unsigned OpFlags = RISCVII::MO_CALL; 10635 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10636 OpFlags = RISCVII::MO_PLT; 10637 10638 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10639 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10640 unsigned OpFlags = RISCVII::MO_CALL; 10641 10642 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10643 nullptr)) 10644 OpFlags = RISCVII::MO_PLT; 10645 10646 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10647 } 10648 10649 // The first call operand is the chain and the second is the target address. 10650 SmallVector<SDValue, 8> Ops; 10651 Ops.push_back(Chain); 10652 Ops.push_back(Callee); 10653 10654 // Add argument registers to the end of the list so that they are 10655 // known live into the call. 10656 for (auto &Reg : RegsToPass) 10657 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10658 10659 if (!IsTailCall) { 10660 // Add a register mask operand representing the call-preserved registers. 10661 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10662 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10663 assert(Mask && "Missing call preserved mask for calling convention"); 10664 Ops.push_back(DAG.getRegisterMask(Mask)); 10665 } 10666 10667 // Glue the call to the argument copies, if any. 10668 if (Glue.getNode()) 10669 Ops.push_back(Glue); 10670 10671 // Emit the call. 10672 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10673 10674 if (IsTailCall) { 10675 MF.getFrameInfo().setHasTailCall(); 10676 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10677 } 10678 10679 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10680 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10681 Glue = Chain.getValue(1); 10682 10683 // Mark the end of the call, which is glued to the call itself. 10684 Chain = DAG.getCALLSEQ_END(Chain, 10685 DAG.getConstant(NumBytes, DL, PtrVT, true), 10686 DAG.getConstant(0, DL, PtrVT, true), 10687 Glue, DL); 10688 Glue = Chain.getValue(1); 10689 10690 // Assign locations to each value returned by this call. 10691 SmallVector<CCValAssign, 16> RVLocs; 10692 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10693 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10694 10695 // Copy all of the result registers out of their specified physreg. 10696 for (auto &VA : RVLocs) { 10697 // Copy the value out 10698 SDValue RetValue = 10699 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10700 // Glue the RetValue to the end of the call sequence 10701 Chain = RetValue.getValue(1); 10702 Glue = RetValue.getValue(2); 10703 10704 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10705 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10706 SDValue RetValue2 = 10707 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10708 Chain = RetValue2.getValue(1); 10709 Glue = RetValue2.getValue(2); 10710 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10711 RetValue2); 10712 } 10713 10714 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10715 10716 InVals.push_back(RetValue); 10717 } 10718 10719 return Chain; 10720 } 10721 10722 bool RISCVTargetLowering::CanLowerReturn( 10723 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10724 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10725 SmallVector<CCValAssign, 16> RVLocs; 10726 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10727 10728 Optional<unsigned> FirstMaskArgument; 10729 if (Subtarget.hasVInstructions()) 10730 FirstMaskArgument = preAssignMask(Outs); 10731 10732 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10733 MVT VT = Outs[i].VT; 10734 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10735 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10736 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10737 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10738 *this, FirstMaskArgument)) 10739 return false; 10740 } 10741 return true; 10742 } 10743 10744 SDValue 10745 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10746 bool IsVarArg, 10747 const SmallVectorImpl<ISD::OutputArg> &Outs, 10748 const SmallVectorImpl<SDValue> &OutVals, 10749 const SDLoc &DL, SelectionDAG &DAG) const { 10750 const MachineFunction &MF = DAG.getMachineFunction(); 10751 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10752 10753 // Stores the assignment of the return value to a location. 10754 SmallVector<CCValAssign, 16> RVLocs; 10755 10756 // Info about the registers and stack slot. 10757 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10758 *DAG.getContext()); 10759 10760 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10761 nullptr, CC_RISCV); 10762 10763 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10764 report_fatal_error("GHC functions return void only"); 10765 10766 SDValue Glue; 10767 SmallVector<SDValue, 4> RetOps(1, Chain); 10768 10769 // Copy the result values into the output registers. 10770 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10771 SDValue Val = OutVals[i]; 10772 CCValAssign &VA = RVLocs[i]; 10773 assert(VA.isRegLoc() && "Can only return in registers!"); 10774 10775 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10776 // Handle returning f64 on RV32D with a soft float ABI. 10777 assert(VA.isRegLoc() && "Expected return via registers"); 10778 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10779 DAG.getVTList(MVT::i32, MVT::i32), Val); 10780 SDValue Lo = SplitF64.getValue(0); 10781 SDValue Hi = SplitF64.getValue(1); 10782 Register RegLo = VA.getLocReg(); 10783 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10784 Register RegHi = RegLo + 1; 10785 10786 if (STI.isRegisterReservedByUser(RegLo) || 10787 STI.isRegisterReservedByUser(RegHi)) 10788 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10789 MF.getFunction(), 10790 "Return value register required, but has been reserved."}); 10791 10792 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10793 Glue = Chain.getValue(1); 10794 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10795 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10796 Glue = Chain.getValue(1); 10797 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10798 } else { 10799 // Handle a 'normal' return. 10800 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10801 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10802 10803 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10804 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10805 MF.getFunction(), 10806 "Return value register required, but has been reserved."}); 10807 10808 // Guarantee that all emitted copies are stuck together. 10809 Glue = Chain.getValue(1); 10810 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10811 } 10812 } 10813 10814 RetOps[0] = Chain; // Update chain. 10815 10816 // Add the glue node if we have it. 10817 if (Glue.getNode()) { 10818 RetOps.push_back(Glue); 10819 } 10820 10821 unsigned RetOpc = RISCVISD::RET_FLAG; 10822 // Interrupt service routines use different return instructions. 10823 const Function &Func = DAG.getMachineFunction().getFunction(); 10824 if (Func.hasFnAttribute("interrupt")) { 10825 if (!Func.getReturnType()->isVoidTy()) 10826 report_fatal_error( 10827 "Functions with the interrupt attribute must have void return type!"); 10828 10829 MachineFunction &MF = DAG.getMachineFunction(); 10830 StringRef Kind = 10831 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10832 10833 if (Kind == "user") 10834 RetOpc = RISCVISD::URET_FLAG; 10835 else if (Kind == "supervisor") 10836 RetOpc = RISCVISD::SRET_FLAG; 10837 else 10838 RetOpc = RISCVISD::MRET_FLAG; 10839 } 10840 10841 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10842 } 10843 10844 void RISCVTargetLowering::validateCCReservedRegs( 10845 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10846 MachineFunction &MF) const { 10847 const Function &F = MF.getFunction(); 10848 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10849 10850 if (llvm::any_of(Regs, [&STI](auto Reg) { 10851 return STI.isRegisterReservedByUser(Reg.first); 10852 })) 10853 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10854 F, "Argument register required, but has been reserved."}); 10855 } 10856 10857 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10858 return CI->isTailCall(); 10859 } 10860 10861 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10862 #define NODE_NAME_CASE(NODE) \ 10863 case RISCVISD::NODE: \ 10864 return "RISCVISD::" #NODE; 10865 // clang-format off 10866 switch ((RISCVISD::NodeType)Opcode) { 10867 case RISCVISD::FIRST_NUMBER: 10868 break; 10869 NODE_NAME_CASE(RET_FLAG) 10870 NODE_NAME_CASE(URET_FLAG) 10871 NODE_NAME_CASE(SRET_FLAG) 10872 NODE_NAME_CASE(MRET_FLAG) 10873 NODE_NAME_CASE(CALL) 10874 NODE_NAME_CASE(SELECT_CC) 10875 NODE_NAME_CASE(BR_CC) 10876 NODE_NAME_CASE(BuildPairF64) 10877 NODE_NAME_CASE(SplitF64) 10878 NODE_NAME_CASE(TAIL) 10879 NODE_NAME_CASE(MULHSU) 10880 NODE_NAME_CASE(SLLW) 10881 NODE_NAME_CASE(SRAW) 10882 NODE_NAME_CASE(SRLW) 10883 NODE_NAME_CASE(DIVW) 10884 NODE_NAME_CASE(DIVUW) 10885 NODE_NAME_CASE(REMUW) 10886 NODE_NAME_CASE(ROLW) 10887 NODE_NAME_CASE(RORW) 10888 NODE_NAME_CASE(CLZW) 10889 NODE_NAME_CASE(CTZW) 10890 NODE_NAME_CASE(FSLW) 10891 NODE_NAME_CASE(FSRW) 10892 NODE_NAME_CASE(FSL) 10893 NODE_NAME_CASE(FSR) 10894 NODE_NAME_CASE(FMV_H_X) 10895 NODE_NAME_CASE(FMV_X_ANYEXTH) 10896 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10897 NODE_NAME_CASE(FMV_W_X_RV64) 10898 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10899 NODE_NAME_CASE(FCVT_X) 10900 NODE_NAME_CASE(FCVT_XU) 10901 NODE_NAME_CASE(FCVT_W_RV64) 10902 NODE_NAME_CASE(FCVT_WU_RV64) 10903 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10904 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10905 NODE_NAME_CASE(READ_CYCLE_WIDE) 10906 NODE_NAME_CASE(GREV) 10907 NODE_NAME_CASE(GREVW) 10908 NODE_NAME_CASE(GORC) 10909 NODE_NAME_CASE(GORCW) 10910 NODE_NAME_CASE(SHFL) 10911 NODE_NAME_CASE(SHFLW) 10912 NODE_NAME_CASE(UNSHFL) 10913 NODE_NAME_CASE(UNSHFLW) 10914 NODE_NAME_CASE(BFP) 10915 NODE_NAME_CASE(BFPW) 10916 NODE_NAME_CASE(BCOMPRESS) 10917 NODE_NAME_CASE(BCOMPRESSW) 10918 NODE_NAME_CASE(BDECOMPRESS) 10919 NODE_NAME_CASE(BDECOMPRESSW) 10920 NODE_NAME_CASE(VMV_V_X_VL) 10921 NODE_NAME_CASE(VFMV_V_F_VL) 10922 NODE_NAME_CASE(VMV_X_S) 10923 NODE_NAME_CASE(VMV_S_X_VL) 10924 NODE_NAME_CASE(VFMV_S_F_VL) 10925 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10926 NODE_NAME_CASE(READ_VLENB) 10927 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10928 NODE_NAME_CASE(VSLIDEUP_VL) 10929 NODE_NAME_CASE(VSLIDE1UP_VL) 10930 NODE_NAME_CASE(VSLIDEDOWN_VL) 10931 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10932 NODE_NAME_CASE(VID_VL) 10933 NODE_NAME_CASE(VFNCVT_ROD_VL) 10934 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10935 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10936 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10937 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10938 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10939 NODE_NAME_CASE(VECREDUCE_AND_VL) 10940 NODE_NAME_CASE(VECREDUCE_OR_VL) 10941 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10942 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10943 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10944 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10945 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10946 NODE_NAME_CASE(ADD_VL) 10947 NODE_NAME_CASE(AND_VL) 10948 NODE_NAME_CASE(MUL_VL) 10949 NODE_NAME_CASE(OR_VL) 10950 NODE_NAME_CASE(SDIV_VL) 10951 NODE_NAME_CASE(SHL_VL) 10952 NODE_NAME_CASE(SREM_VL) 10953 NODE_NAME_CASE(SRA_VL) 10954 NODE_NAME_CASE(SRL_VL) 10955 NODE_NAME_CASE(SUB_VL) 10956 NODE_NAME_CASE(UDIV_VL) 10957 NODE_NAME_CASE(UREM_VL) 10958 NODE_NAME_CASE(XOR_VL) 10959 NODE_NAME_CASE(SADDSAT_VL) 10960 NODE_NAME_CASE(UADDSAT_VL) 10961 NODE_NAME_CASE(SSUBSAT_VL) 10962 NODE_NAME_CASE(USUBSAT_VL) 10963 NODE_NAME_CASE(FADD_VL) 10964 NODE_NAME_CASE(FSUB_VL) 10965 NODE_NAME_CASE(FMUL_VL) 10966 NODE_NAME_CASE(FDIV_VL) 10967 NODE_NAME_CASE(FNEG_VL) 10968 NODE_NAME_CASE(FABS_VL) 10969 NODE_NAME_CASE(FSQRT_VL) 10970 NODE_NAME_CASE(FMA_VL) 10971 NODE_NAME_CASE(FCOPYSIGN_VL) 10972 NODE_NAME_CASE(SMIN_VL) 10973 NODE_NAME_CASE(SMAX_VL) 10974 NODE_NAME_CASE(UMIN_VL) 10975 NODE_NAME_CASE(UMAX_VL) 10976 NODE_NAME_CASE(FMINNUM_VL) 10977 NODE_NAME_CASE(FMAXNUM_VL) 10978 NODE_NAME_CASE(MULHS_VL) 10979 NODE_NAME_CASE(MULHU_VL) 10980 NODE_NAME_CASE(FP_TO_SINT_VL) 10981 NODE_NAME_CASE(FP_TO_UINT_VL) 10982 NODE_NAME_CASE(SINT_TO_FP_VL) 10983 NODE_NAME_CASE(UINT_TO_FP_VL) 10984 NODE_NAME_CASE(FP_EXTEND_VL) 10985 NODE_NAME_CASE(FP_ROUND_VL) 10986 NODE_NAME_CASE(VWMUL_VL) 10987 NODE_NAME_CASE(VWMULU_VL) 10988 NODE_NAME_CASE(VWMULSU_VL) 10989 NODE_NAME_CASE(VWADD_VL) 10990 NODE_NAME_CASE(VWADDU_VL) 10991 NODE_NAME_CASE(VWSUB_VL) 10992 NODE_NAME_CASE(VWSUBU_VL) 10993 NODE_NAME_CASE(VWADD_W_VL) 10994 NODE_NAME_CASE(VWADDU_W_VL) 10995 NODE_NAME_CASE(VWSUB_W_VL) 10996 NODE_NAME_CASE(VWSUBU_W_VL) 10997 NODE_NAME_CASE(SETCC_VL) 10998 NODE_NAME_CASE(VSELECT_VL) 10999 NODE_NAME_CASE(VP_MERGE_VL) 11000 NODE_NAME_CASE(VMAND_VL) 11001 NODE_NAME_CASE(VMOR_VL) 11002 NODE_NAME_CASE(VMXOR_VL) 11003 NODE_NAME_CASE(VMCLR_VL) 11004 NODE_NAME_CASE(VMSET_VL) 11005 NODE_NAME_CASE(VRGATHER_VX_VL) 11006 NODE_NAME_CASE(VRGATHER_VV_VL) 11007 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11008 NODE_NAME_CASE(VSEXT_VL) 11009 NODE_NAME_CASE(VZEXT_VL) 11010 NODE_NAME_CASE(VCPOP_VL) 11011 NODE_NAME_CASE(READ_CSR) 11012 NODE_NAME_CASE(WRITE_CSR) 11013 NODE_NAME_CASE(SWAP_CSR) 11014 } 11015 // clang-format on 11016 return nullptr; 11017 #undef NODE_NAME_CASE 11018 } 11019 11020 /// getConstraintType - Given a constraint letter, return the type of 11021 /// constraint it is for this target. 11022 RISCVTargetLowering::ConstraintType 11023 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11024 if (Constraint.size() == 1) { 11025 switch (Constraint[0]) { 11026 default: 11027 break; 11028 case 'f': 11029 return C_RegisterClass; 11030 case 'I': 11031 case 'J': 11032 case 'K': 11033 return C_Immediate; 11034 case 'A': 11035 return C_Memory; 11036 case 'S': // A symbolic address 11037 return C_Other; 11038 } 11039 } else { 11040 if (Constraint == "vr" || Constraint == "vm") 11041 return C_RegisterClass; 11042 } 11043 return TargetLowering::getConstraintType(Constraint); 11044 } 11045 11046 std::pair<unsigned, const TargetRegisterClass *> 11047 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11048 StringRef Constraint, 11049 MVT VT) const { 11050 // First, see if this is a constraint that directly corresponds to a 11051 // RISCV register class. 11052 if (Constraint.size() == 1) { 11053 switch (Constraint[0]) { 11054 case 'r': 11055 // TODO: Support fixed vectors up to XLen for P extension? 11056 if (VT.isVector()) 11057 break; 11058 return std::make_pair(0U, &RISCV::GPRRegClass); 11059 case 'f': 11060 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11061 return std::make_pair(0U, &RISCV::FPR16RegClass); 11062 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11063 return std::make_pair(0U, &RISCV::FPR32RegClass); 11064 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11065 return std::make_pair(0U, &RISCV::FPR64RegClass); 11066 break; 11067 default: 11068 break; 11069 } 11070 } else if (Constraint == "vr") { 11071 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11072 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11073 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11074 return std::make_pair(0U, RC); 11075 } 11076 } else if (Constraint == "vm") { 11077 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11078 return std::make_pair(0U, &RISCV::VMV0RegClass); 11079 } 11080 11081 // Clang will correctly decode the usage of register name aliases into their 11082 // official names. However, other frontends like `rustc` do not. This allows 11083 // users of these frontends to use the ABI names for registers in LLVM-style 11084 // register constraints. 11085 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11086 .Case("{zero}", RISCV::X0) 11087 .Case("{ra}", RISCV::X1) 11088 .Case("{sp}", RISCV::X2) 11089 .Case("{gp}", RISCV::X3) 11090 .Case("{tp}", RISCV::X4) 11091 .Case("{t0}", RISCV::X5) 11092 .Case("{t1}", RISCV::X6) 11093 .Case("{t2}", RISCV::X7) 11094 .Cases("{s0}", "{fp}", RISCV::X8) 11095 .Case("{s1}", RISCV::X9) 11096 .Case("{a0}", RISCV::X10) 11097 .Case("{a1}", RISCV::X11) 11098 .Case("{a2}", RISCV::X12) 11099 .Case("{a3}", RISCV::X13) 11100 .Case("{a4}", RISCV::X14) 11101 .Case("{a5}", RISCV::X15) 11102 .Case("{a6}", RISCV::X16) 11103 .Case("{a7}", RISCV::X17) 11104 .Case("{s2}", RISCV::X18) 11105 .Case("{s3}", RISCV::X19) 11106 .Case("{s4}", RISCV::X20) 11107 .Case("{s5}", RISCV::X21) 11108 .Case("{s6}", RISCV::X22) 11109 .Case("{s7}", RISCV::X23) 11110 .Case("{s8}", RISCV::X24) 11111 .Case("{s9}", RISCV::X25) 11112 .Case("{s10}", RISCV::X26) 11113 .Case("{s11}", RISCV::X27) 11114 .Case("{t3}", RISCV::X28) 11115 .Case("{t4}", RISCV::X29) 11116 .Case("{t5}", RISCV::X30) 11117 .Case("{t6}", RISCV::X31) 11118 .Default(RISCV::NoRegister); 11119 if (XRegFromAlias != RISCV::NoRegister) 11120 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11121 11122 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11123 // TableGen record rather than the AsmName to choose registers for InlineAsm 11124 // constraints, plus we want to match those names to the widest floating point 11125 // register type available, manually select floating point registers here. 11126 // 11127 // The second case is the ABI name of the register, so that frontends can also 11128 // use the ABI names in register constraint lists. 11129 if (Subtarget.hasStdExtF()) { 11130 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11131 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11132 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11133 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11134 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11135 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11136 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11137 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11138 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11139 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11140 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11141 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11142 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11143 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11144 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11145 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11146 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11147 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11148 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11149 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11150 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11151 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11152 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11153 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11154 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11155 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11156 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11157 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11158 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11159 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11160 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11161 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11162 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11163 .Default(RISCV::NoRegister); 11164 if (FReg != RISCV::NoRegister) { 11165 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11166 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11167 unsigned RegNo = FReg - RISCV::F0_F; 11168 unsigned DReg = RISCV::F0_D + RegNo; 11169 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11170 } 11171 if (VT == MVT::f32 || VT == MVT::Other) 11172 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11173 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11174 unsigned RegNo = FReg - RISCV::F0_F; 11175 unsigned HReg = RISCV::F0_H + RegNo; 11176 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11177 } 11178 } 11179 } 11180 11181 if (Subtarget.hasVInstructions()) { 11182 Register VReg = StringSwitch<Register>(Constraint.lower()) 11183 .Case("{v0}", RISCV::V0) 11184 .Case("{v1}", RISCV::V1) 11185 .Case("{v2}", RISCV::V2) 11186 .Case("{v3}", RISCV::V3) 11187 .Case("{v4}", RISCV::V4) 11188 .Case("{v5}", RISCV::V5) 11189 .Case("{v6}", RISCV::V6) 11190 .Case("{v7}", RISCV::V7) 11191 .Case("{v8}", RISCV::V8) 11192 .Case("{v9}", RISCV::V9) 11193 .Case("{v10}", RISCV::V10) 11194 .Case("{v11}", RISCV::V11) 11195 .Case("{v12}", RISCV::V12) 11196 .Case("{v13}", RISCV::V13) 11197 .Case("{v14}", RISCV::V14) 11198 .Case("{v15}", RISCV::V15) 11199 .Case("{v16}", RISCV::V16) 11200 .Case("{v17}", RISCV::V17) 11201 .Case("{v18}", RISCV::V18) 11202 .Case("{v19}", RISCV::V19) 11203 .Case("{v20}", RISCV::V20) 11204 .Case("{v21}", RISCV::V21) 11205 .Case("{v22}", RISCV::V22) 11206 .Case("{v23}", RISCV::V23) 11207 .Case("{v24}", RISCV::V24) 11208 .Case("{v25}", RISCV::V25) 11209 .Case("{v26}", RISCV::V26) 11210 .Case("{v27}", RISCV::V27) 11211 .Case("{v28}", RISCV::V28) 11212 .Case("{v29}", RISCV::V29) 11213 .Case("{v30}", RISCV::V30) 11214 .Case("{v31}", RISCV::V31) 11215 .Default(RISCV::NoRegister); 11216 if (VReg != RISCV::NoRegister) { 11217 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11218 return std::make_pair(VReg, &RISCV::VMRegClass); 11219 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11220 return std::make_pair(VReg, &RISCV::VRRegClass); 11221 for (const auto *RC : 11222 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11223 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11224 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11225 return std::make_pair(VReg, RC); 11226 } 11227 } 11228 } 11229 } 11230 11231 std::pair<Register, const TargetRegisterClass *> Res = 11232 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11233 11234 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11235 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11236 // Subtarget into account. 11237 if (Res.second == &RISCV::GPRF16RegClass || 11238 Res.second == &RISCV::GPRF32RegClass || 11239 Res.second == &RISCV::GPRF64RegClass) 11240 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11241 11242 return Res; 11243 } 11244 11245 unsigned 11246 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11247 // Currently only support length 1 constraints. 11248 if (ConstraintCode.size() == 1) { 11249 switch (ConstraintCode[0]) { 11250 case 'A': 11251 return InlineAsm::Constraint_A; 11252 default: 11253 break; 11254 } 11255 } 11256 11257 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11258 } 11259 11260 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11261 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11262 SelectionDAG &DAG) const { 11263 // Currently only support length 1 constraints. 11264 if (Constraint.length() == 1) { 11265 switch (Constraint[0]) { 11266 case 'I': 11267 // Validate & create a 12-bit signed immediate operand. 11268 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11269 uint64_t CVal = C->getSExtValue(); 11270 if (isInt<12>(CVal)) 11271 Ops.push_back( 11272 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11273 } 11274 return; 11275 case 'J': 11276 // Validate & create an integer zero operand. 11277 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11278 if (C->getZExtValue() == 0) 11279 Ops.push_back( 11280 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11281 return; 11282 case 'K': 11283 // Validate & create a 5-bit unsigned immediate operand. 11284 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11285 uint64_t CVal = C->getZExtValue(); 11286 if (isUInt<5>(CVal)) 11287 Ops.push_back( 11288 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11289 } 11290 return; 11291 case 'S': 11292 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11293 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11294 GA->getValueType(0))); 11295 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11296 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11297 BA->getValueType(0))); 11298 } 11299 return; 11300 default: 11301 break; 11302 } 11303 } 11304 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11305 } 11306 11307 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11308 Instruction *Inst, 11309 AtomicOrdering Ord) const { 11310 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11311 return Builder.CreateFence(Ord); 11312 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11313 return Builder.CreateFence(AtomicOrdering::Release); 11314 return nullptr; 11315 } 11316 11317 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11318 Instruction *Inst, 11319 AtomicOrdering Ord) const { 11320 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11321 return Builder.CreateFence(AtomicOrdering::Acquire); 11322 return nullptr; 11323 } 11324 11325 TargetLowering::AtomicExpansionKind 11326 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11327 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11328 // point operations can't be used in an lr/sc sequence without breaking the 11329 // forward-progress guarantee. 11330 if (AI->isFloatingPointOperation()) 11331 return AtomicExpansionKind::CmpXChg; 11332 11333 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11334 if (Size == 8 || Size == 16) 11335 return AtomicExpansionKind::MaskedIntrinsic; 11336 return AtomicExpansionKind::None; 11337 } 11338 11339 static Intrinsic::ID 11340 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11341 if (XLen == 32) { 11342 switch (BinOp) { 11343 default: 11344 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11345 case AtomicRMWInst::Xchg: 11346 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11347 case AtomicRMWInst::Add: 11348 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11349 case AtomicRMWInst::Sub: 11350 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11351 case AtomicRMWInst::Nand: 11352 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11353 case AtomicRMWInst::Max: 11354 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11355 case AtomicRMWInst::Min: 11356 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11357 case AtomicRMWInst::UMax: 11358 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11359 case AtomicRMWInst::UMin: 11360 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11361 } 11362 } 11363 11364 if (XLen == 64) { 11365 switch (BinOp) { 11366 default: 11367 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11368 case AtomicRMWInst::Xchg: 11369 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11370 case AtomicRMWInst::Add: 11371 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11372 case AtomicRMWInst::Sub: 11373 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11374 case AtomicRMWInst::Nand: 11375 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11376 case AtomicRMWInst::Max: 11377 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11378 case AtomicRMWInst::Min: 11379 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11380 case AtomicRMWInst::UMax: 11381 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11382 case AtomicRMWInst::UMin: 11383 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11384 } 11385 } 11386 11387 llvm_unreachable("Unexpected XLen\n"); 11388 } 11389 11390 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11391 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11392 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11393 unsigned XLen = Subtarget.getXLen(); 11394 Value *Ordering = 11395 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11396 Type *Tys[] = {AlignedAddr->getType()}; 11397 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11398 AI->getModule(), 11399 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11400 11401 if (XLen == 64) { 11402 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11403 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11404 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11405 } 11406 11407 Value *Result; 11408 11409 // Must pass the shift amount needed to sign extend the loaded value prior 11410 // to performing a signed comparison for min/max. ShiftAmt is the number of 11411 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11412 // is the number of bits to left+right shift the value in order to 11413 // sign-extend. 11414 if (AI->getOperation() == AtomicRMWInst::Min || 11415 AI->getOperation() == AtomicRMWInst::Max) { 11416 const DataLayout &DL = AI->getModule()->getDataLayout(); 11417 unsigned ValWidth = 11418 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11419 Value *SextShamt = 11420 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11421 Result = Builder.CreateCall(LrwOpScwLoop, 11422 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11423 } else { 11424 Result = 11425 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11426 } 11427 11428 if (XLen == 64) 11429 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11430 return Result; 11431 } 11432 11433 TargetLowering::AtomicExpansionKind 11434 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11435 AtomicCmpXchgInst *CI) const { 11436 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11437 if (Size == 8 || Size == 16) 11438 return AtomicExpansionKind::MaskedIntrinsic; 11439 return AtomicExpansionKind::None; 11440 } 11441 11442 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11443 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11444 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11445 unsigned XLen = Subtarget.getXLen(); 11446 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11447 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11448 if (XLen == 64) { 11449 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11450 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11451 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11452 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11453 } 11454 Type *Tys[] = {AlignedAddr->getType()}; 11455 Function *MaskedCmpXchg = 11456 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11457 Value *Result = Builder.CreateCall( 11458 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11459 if (XLen == 64) 11460 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11461 return Result; 11462 } 11463 11464 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11465 return false; 11466 } 11467 11468 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11469 EVT VT) const { 11470 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11471 return false; 11472 11473 switch (FPVT.getSimpleVT().SimpleTy) { 11474 case MVT::f16: 11475 return Subtarget.hasStdExtZfh(); 11476 case MVT::f32: 11477 return Subtarget.hasStdExtF(); 11478 case MVT::f64: 11479 return Subtarget.hasStdExtD(); 11480 default: 11481 return false; 11482 } 11483 } 11484 11485 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11486 // If we are using the small code model, we can reduce size of jump table 11487 // entry to 4 bytes. 11488 if (Subtarget.is64Bit() && !isPositionIndependent() && 11489 getTargetMachine().getCodeModel() == CodeModel::Small) { 11490 return MachineJumpTableInfo::EK_Custom32; 11491 } 11492 return TargetLowering::getJumpTableEncoding(); 11493 } 11494 11495 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11496 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11497 unsigned uid, MCContext &Ctx) const { 11498 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11499 getTargetMachine().getCodeModel() == CodeModel::Small); 11500 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11501 } 11502 11503 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11504 EVT VT) const { 11505 VT = VT.getScalarType(); 11506 11507 if (!VT.isSimple()) 11508 return false; 11509 11510 switch (VT.getSimpleVT().SimpleTy) { 11511 case MVT::f16: 11512 return Subtarget.hasStdExtZfh(); 11513 case MVT::f32: 11514 return Subtarget.hasStdExtF(); 11515 case MVT::f64: 11516 return Subtarget.hasStdExtD(); 11517 default: 11518 break; 11519 } 11520 11521 return false; 11522 } 11523 11524 Register RISCVTargetLowering::getExceptionPointerRegister( 11525 const Constant *PersonalityFn) const { 11526 return RISCV::X10; 11527 } 11528 11529 Register RISCVTargetLowering::getExceptionSelectorRegister( 11530 const Constant *PersonalityFn) const { 11531 return RISCV::X11; 11532 } 11533 11534 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11535 // Return false to suppress the unnecessary extensions if the LibCall 11536 // arguments or return value is f32 type for LP64 ABI. 11537 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11538 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11539 return false; 11540 11541 return true; 11542 } 11543 11544 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11545 if (Subtarget.is64Bit() && Type == MVT::i32) 11546 return true; 11547 11548 return IsSigned; 11549 } 11550 11551 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11552 SDValue C) const { 11553 // Check integral scalar types. 11554 if (VT.isScalarInteger()) { 11555 // Omit the optimization if the sub target has the M extension and the data 11556 // size exceeds XLen. 11557 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11558 return false; 11559 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11560 // Break the MUL to a SLLI and an ADD/SUB. 11561 const APInt &Imm = ConstNode->getAPIntValue(); 11562 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11563 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11564 return true; 11565 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11566 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11567 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11568 (Imm - 8).isPowerOf2())) 11569 return true; 11570 // Omit the following optimization if the sub target has the M extension 11571 // and the data size >= XLen. 11572 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11573 return false; 11574 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11575 // a pair of LUI/ADDI. 11576 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11577 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11578 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11579 (1 - ImmS).isPowerOf2()) 11580 return true; 11581 } 11582 } 11583 } 11584 11585 return false; 11586 } 11587 11588 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11589 SDValue ConstNode) const { 11590 // Let the DAGCombiner decide for vectors. 11591 EVT VT = AddNode.getValueType(); 11592 if (VT.isVector()) 11593 return true; 11594 11595 // Let the DAGCombiner decide for larger types. 11596 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11597 return true; 11598 11599 // It is worse if c1 is simm12 while c1*c2 is not. 11600 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11601 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11602 const APInt &C1 = C1Node->getAPIntValue(); 11603 const APInt &C2 = C2Node->getAPIntValue(); 11604 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11605 return false; 11606 11607 // Default to true and let the DAGCombiner decide. 11608 return true; 11609 } 11610 11611 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11612 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11613 bool *Fast) const { 11614 if (!VT.isVector()) 11615 return false; 11616 11617 EVT ElemVT = VT.getVectorElementType(); 11618 if (Alignment >= ElemVT.getStoreSize()) { 11619 if (Fast) 11620 *Fast = true; 11621 return true; 11622 } 11623 11624 return false; 11625 } 11626 11627 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11628 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11629 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11630 bool IsABIRegCopy = CC.hasValue(); 11631 EVT ValueVT = Val.getValueType(); 11632 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11633 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11634 // and cast to f32. 11635 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11636 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11637 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11638 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11639 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11640 Parts[0] = Val; 11641 return true; 11642 } 11643 11644 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11645 LLVMContext &Context = *DAG.getContext(); 11646 EVT ValueEltVT = ValueVT.getVectorElementType(); 11647 EVT PartEltVT = PartVT.getVectorElementType(); 11648 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11649 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11650 if (PartVTBitSize % ValueVTBitSize == 0) { 11651 assert(PartVTBitSize >= ValueVTBitSize); 11652 // If the element types are different, bitcast to the same element type of 11653 // PartVT first. 11654 // Give an example here, we want copy a <vscale x 1 x i8> value to 11655 // <vscale x 4 x i16>. 11656 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11657 // subvector, then we can bitcast to <vscale x 4 x i16>. 11658 if (ValueEltVT != PartEltVT) { 11659 if (PartVTBitSize > ValueVTBitSize) { 11660 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11661 assert(Count != 0 && "The number of element should not be zero."); 11662 EVT SameEltTypeVT = 11663 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11664 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11665 DAG.getUNDEF(SameEltTypeVT), Val, 11666 DAG.getVectorIdxConstant(0, DL)); 11667 } 11668 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11669 } else { 11670 Val = 11671 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11672 Val, DAG.getVectorIdxConstant(0, DL)); 11673 } 11674 Parts[0] = Val; 11675 return true; 11676 } 11677 } 11678 return false; 11679 } 11680 11681 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11682 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11683 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11684 bool IsABIRegCopy = CC.hasValue(); 11685 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11686 SDValue Val = Parts[0]; 11687 11688 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11689 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11690 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11691 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11692 return Val; 11693 } 11694 11695 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11696 LLVMContext &Context = *DAG.getContext(); 11697 SDValue Val = Parts[0]; 11698 EVT ValueEltVT = ValueVT.getVectorElementType(); 11699 EVT PartEltVT = PartVT.getVectorElementType(); 11700 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11701 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11702 if (PartVTBitSize % ValueVTBitSize == 0) { 11703 assert(PartVTBitSize >= ValueVTBitSize); 11704 EVT SameEltTypeVT = ValueVT; 11705 // If the element types are different, convert it to the same element type 11706 // of PartVT. 11707 // Give an example here, we want copy a <vscale x 1 x i8> value from 11708 // <vscale x 4 x i16>. 11709 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11710 // then we can extract <vscale x 1 x i8>. 11711 if (ValueEltVT != PartEltVT) { 11712 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11713 assert(Count != 0 && "The number of element should not be zero."); 11714 SameEltTypeVT = 11715 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11716 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11717 } 11718 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11719 DAG.getVectorIdxConstant(0, DL)); 11720 return Val; 11721 } 11722 } 11723 return SDValue(); 11724 } 11725 11726 SDValue 11727 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11728 SelectionDAG &DAG, 11729 SmallVectorImpl<SDNode *> &Created) const { 11730 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11731 if (isIntDivCheap(N->getValueType(0), Attr)) 11732 return SDValue(N, 0); // Lower SDIV as SDIV 11733 11734 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11735 "Unexpected divisor!"); 11736 11737 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11738 if (!Subtarget.hasStdExtZbt()) 11739 return SDValue(); 11740 11741 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11742 // Besides, more critical path instructions will be generated when dividing 11743 // by 2. So we keep using the original DAGs for these cases. 11744 unsigned Lg2 = Divisor.countTrailingZeros(); 11745 if (Lg2 == 1 || Lg2 >= 12) 11746 return SDValue(); 11747 11748 // fold (sdiv X, pow2) 11749 EVT VT = N->getValueType(0); 11750 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11751 return SDValue(); 11752 11753 SDLoc DL(N); 11754 SDValue N0 = N->getOperand(0); 11755 SDValue Zero = DAG.getConstant(0, DL, VT); 11756 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11757 11758 // Add (N0 < 0) ? Pow2 - 1 : 0; 11759 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11760 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11761 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11762 11763 Created.push_back(Cmp.getNode()); 11764 Created.push_back(Add.getNode()); 11765 Created.push_back(Sel.getNode()); 11766 11767 // Divide by pow2. 11768 SDValue SRA = 11769 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11770 11771 // If we're dividing by a positive value, we're done. Otherwise, we must 11772 // negate the result. 11773 if (Divisor.isNonNegative()) 11774 return SRA; 11775 11776 Created.push_back(SRA.getNode()); 11777 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11778 } 11779 11780 #define GET_REGISTER_MATCHER 11781 #include "RISCVGenAsmMatcher.inc" 11782 11783 Register 11784 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11785 const MachineFunction &MF) const { 11786 Register Reg = MatchRegisterAltName(RegName); 11787 if (Reg == RISCV::NoRegister) 11788 Reg = MatchRegisterName(RegName); 11789 if (Reg == RISCV::NoRegister) 11790 report_fatal_error( 11791 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11792 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11793 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11794 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11795 StringRef(RegName) + "\".")); 11796 return Reg; 11797 } 11798 11799 namespace llvm { 11800 namespace RISCVVIntrinsicsTable { 11801 11802 #define GET_RISCVVIntrinsicsTable_IMPL 11803 #include "RISCVGenSearchableTables.inc" 11804 11805 } // namespace RISCVVIntrinsicsTable 11806 11807 } // namespace llvm 11808