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}; 494 495 static const unsigned FloatingPointVPOps[] = { 496 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 497 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 498 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 499 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 500 501 if (!Subtarget.is64Bit()) { 502 // We must custom-lower certain vXi64 operations on RV32 due to the vector 503 // element type being illegal. 504 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 505 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 506 507 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 508 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 509 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 512 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 513 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 515 516 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 517 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 518 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 521 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 522 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 524 } 525 526 for (MVT VT : BoolVecVTs) { 527 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 528 529 // Mask VTs are custom-expanded into a series of standard nodes 530 setOperationAction(ISD::TRUNCATE, VT, Custom); 531 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 532 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 533 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 534 535 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 536 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 537 538 setOperationAction(ISD::SELECT, VT, Custom); 539 setOperationAction(ISD::SELECT_CC, VT, Expand); 540 setOperationAction(ISD::VSELECT, VT, Expand); 541 setOperationAction(ISD::VP_MERGE, VT, Expand); 542 setOperationAction(ISD::VP_SELECT, VT, Expand); 543 544 setOperationAction(ISD::VP_AND, VT, Custom); 545 setOperationAction(ISD::VP_OR, VT, Custom); 546 setOperationAction(ISD::VP_XOR, VT, Custom); 547 548 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 549 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 550 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 551 552 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 553 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 554 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 555 556 // RVV has native int->float & float->int conversions where the 557 // element type sizes are within one power-of-two of each other. Any 558 // wider distances between type sizes have to be lowered as sequences 559 // which progressively narrow the gap in stages. 560 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 561 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 562 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 563 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 564 565 // Expand all extending loads to types larger than this, and truncating 566 // stores from types larger than this. 567 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 568 setTruncStoreAction(OtherVT, VT, Expand); 569 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 570 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 571 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 572 } 573 } 574 575 for (MVT VT : IntVecVTs) { 576 if (VT.getVectorElementType() == MVT::i64 && 577 !Subtarget.hasVInstructionsI64()) 578 continue; 579 580 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 581 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 582 583 // Vectors implement MULHS/MULHU. 584 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 585 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 586 587 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 588 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 589 setOperationAction(ISD::MULHU, VT, Expand); 590 setOperationAction(ISD::MULHS, VT, Expand); 591 } 592 593 setOperationAction(ISD::SMIN, VT, Legal); 594 setOperationAction(ISD::SMAX, VT, Legal); 595 setOperationAction(ISD::UMIN, VT, Legal); 596 setOperationAction(ISD::UMAX, VT, Legal); 597 598 setOperationAction(ISD::ROTL, VT, Expand); 599 setOperationAction(ISD::ROTR, VT, Expand); 600 601 setOperationAction(ISD::CTTZ, VT, Expand); 602 setOperationAction(ISD::CTLZ, VT, Expand); 603 setOperationAction(ISD::CTPOP, VT, Expand); 604 605 setOperationAction(ISD::BSWAP, VT, Expand); 606 607 // Custom-lower extensions and truncations from/to mask types. 608 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 609 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 610 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 611 612 // RVV has native int->float & float->int conversions where the 613 // element type sizes are within one power-of-two of each other. Any 614 // wider distances between type sizes have to be lowered as sequences 615 // which progressively narrow the gap in stages. 616 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 617 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 618 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 619 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 620 621 setOperationAction(ISD::SADDSAT, VT, Legal); 622 setOperationAction(ISD::UADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::USUBSAT, VT, Legal); 625 626 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 627 // nodes which truncate by one power of two at a time. 628 setOperationAction(ISD::TRUNCATE, VT, Custom); 629 630 // Custom-lower insert/extract operations to simplify patterns. 631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 633 634 // Custom-lower reduction operations to set up the corresponding custom 635 // nodes' operands. 636 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 644 645 for (unsigned VPOpc : IntegerVPOps) 646 setOperationAction(VPOpc, VT, Custom); 647 648 setOperationAction(ISD::LOAD, VT, Custom); 649 setOperationAction(ISD::STORE, VT, Custom); 650 651 setOperationAction(ISD::MLOAD, VT, Custom); 652 setOperationAction(ISD::MSTORE, VT, Custom); 653 setOperationAction(ISD::MGATHER, VT, Custom); 654 setOperationAction(ISD::MSCATTER, VT, Custom); 655 656 setOperationAction(ISD::VP_LOAD, VT, Custom); 657 setOperationAction(ISD::VP_STORE, VT, Custom); 658 setOperationAction(ISD::VP_GATHER, VT, Custom); 659 setOperationAction(ISD::VP_SCATTER, VT, Custom); 660 661 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 662 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 663 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 664 665 setOperationAction(ISD::SELECT, VT, Custom); 666 setOperationAction(ISD::SELECT_CC, VT, Expand); 667 668 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 669 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 670 671 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 672 setTruncStoreAction(VT, OtherVT, Expand); 673 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 674 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 675 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 676 } 677 678 // Splice 679 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 680 681 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 682 // type that can represent the value exactly. 683 if (VT.getVectorElementType() != MVT::i64) { 684 MVT FloatEltVT = 685 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 686 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 687 if (isTypeLegal(FloatVT)) { 688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 690 } 691 } 692 } 693 694 // Expand various CCs to best match the RVV ISA, which natively supports UNE 695 // but no other unordered comparisons, and supports all ordered comparisons 696 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 697 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 698 // and we pattern-match those back to the "original", swapping operands once 699 // more. This way we catch both operations and both "vf" and "fv" forms with 700 // fewer patterns. 701 static const ISD::CondCode VFPCCToExpand[] = { 702 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 703 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 704 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 705 }; 706 707 // Sets common operation actions on RVV floating-point vector types. 708 const auto SetCommonVFPActions = [&](MVT VT) { 709 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 710 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 711 // sizes are within one power-of-two of each other. Therefore conversions 712 // between vXf16 and vXf64 must be lowered as sequences which convert via 713 // vXf32. 714 setOperationAction(ISD::FP_ROUND, VT, Custom); 715 setOperationAction(ISD::FP_EXTEND, VT, Custom); 716 // Custom-lower insert/extract operations to simplify patterns. 717 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 719 // Expand various condition codes (explained above). 720 for (auto CC : VFPCCToExpand) 721 setCondCodeAction(CC, VT, Expand); 722 723 setOperationAction(ISD::FMINNUM, VT, Legal); 724 setOperationAction(ISD::FMAXNUM, VT, Legal); 725 726 setOperationAction(ISD::FTRUNC, VT, Custom); 727 setOperationAction(ISD::FCEIL, VT, Custom); 728 setOperationAction(ISD::FFLOOR, VT, Custom); 729 setOperationAction(ISD::FROUND, VT, Custom); 730 731 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 732 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 733 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 734 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 735 736 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 737 738 setOperationAction(ISD::LOAD, VT, Custom); 739 setOperationAction(ISD::STORE, VT, Custom); 740 741 setOperationAction(ISD::MLOAD, VT, Custom); 742 setOperationAction(ISD::MSTORE, VT, Custom); 743 setOperationAction(ISD::MGATHER, VT, Custom); 744 setOperationAction(ISD::MSCATTER, VT, Custom); 745 746 setOperationAction(ISD::VP_LOAD, VT, Custom); 747 setOperationAction(ISD::VP_STORE, VT, Custom); 748 setOperationAction(ISD::VP_GATHER, VT, Custom); 749 setOperationAction(ISD::VP_SCATTER, VT, Custom); 750 751 setOperationAction(ISD::SELECT, VT, Custom); 752 setOperationAction(ISD::SELECT_CC, VT, Expand); 753 754 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 755 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 756 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 757 758 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 759 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 760 761 for (unsigned VPOpc : FloatingPointVPOps) 762 setOperationAction(VPOpc, VT, Custom); 763 }; 764 765 // Sets common extload/truncstore actions on RVV floating-point vector 766 // types. 767 const auto SetCommonVFPExtLoadTruncStoreActions = 768 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 769 for (auto SmallVT : SmallerVTs) { 770 setTruncStoreAction(VT, SmallVT, Expand); 771 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 772 } 773 }; 774 775 if (Subtarget.hasVInstructionsF16()) 776 for (MVT VT : F16VecVTs) 777 SetCommonVFPActions(VT); 778 779 for (MVT VT : F32VecVTs) { 780 if (Subtarget.hasVInstructionsF32()) 781 SetCommonVFPActions(VT); 782 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 783 } 784 785 for (MVT VT : F64VecVTs) { 786 if (Subtarget.hasVInstructionsF64()) 787 SetCommonVFPActions(VT); 788 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 789 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 790 } 791 792 if (Subtarget.useRVVForFixedLengthVectors()) { 793 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 794 if (!useRVVForFixedLengthVectorVT(VT)) 795 continue; 796 797 // By default everything must be expanded. 798 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 799 setOperationAction(Op, VT, Expand); 800 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 801 setTruncStoreAction(VT, OtherVT, Expand); 802 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 803 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 804 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 805 } 806 807 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 808 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 809 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 810 811 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 812 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 813 814 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 816 817 setOperationAction(ISD::LOAD, VT, Custom); 818 setOperationAction(ISD::STORE, VT, Custom); 819 820 setOperationAction(ISD::SETCC, VT, Custom); 821 822 setOperationAction(ISD::SELECT, VT, Custom); 823 824 setOperationAction(ISD::TRUNCATE, VT, Custom); 825 826 setOperationAction(ISD::BITCAST, VT, Custom); 827 828 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 829 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 830 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 831 832 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 833 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 834 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 835 836 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 837 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 838 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 839 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 840 841 // Operations below are different for between masks and other vectors. 842 if (VT.getVectorElementType() == MVT::i1) { 843 setOperationAction(ISD::VP_AND, VT, Custom); 844 setOperationAction(ISD::VP_OR, VT, Custom); 845 setOperationAction(ISD::VP_XOR, VT, Custom); 846 setOperationAction(ISD::AND, VT, Custom); 847 setOperationAction(ISD::OR, VT, Custom); 848 setOperationAction(ISD::XOR, VT, Custom); 849 continue; 850 } 851 852 // Use SPLAT_VECTOR to prevent type legalization from destroying the 853 // splats when type legalizing i64 scalar on RV32. 854 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 855 // improvements first. 856 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 857 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 858 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 859 } 860 861 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 862 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 863 864 setOperationAction(ISD::MLOAD, VT, Custom); 865 setOperationAction(ISD::MSTORE, VT, Custom); 866 setOperationAction(ISD::MGATHER, VT, Custom); 867 setOperationAction(ISD::MSCATTER, VT, Custom); 868 869 setOperationAction(ISD::VP_LOAD, VT, Custom); 870 setOperationAction(ISD::VP_STORE, VT, Custom); 871 setOperationAction(ISD::VP_GATHER, VT, Custom); 872 setOperationAction(ISD::VP_SCATTER, VT, Custom); 873 874 setOperationAction(ISD::ADD, VT, Custom); 875 setOperationAction(ISD::MUL, VT, Custom); 876 setOperationAction(ISD::SUB, VT, Custom); 877 setOperationAction(ISD::AND, VT, Custom); 878 setOperationAction(ISD::OR, VT, Custom); 879 setOperationAction(ISD::XOR, VT, Custom); 880 setOperationAction(ISD::SDIV, VT, Custom); 881 setOperationAction(ISD::SREM, VT, Custom); 882 setOperationAction(ISD::UDIV, VT, Custom); 883 setOperationAction(ISD::UREM, VT, Custom); 884 setOperationAction(ISD::SHL, VT, Custom); 885 setOperationAction(ISD::SRA, VT, Custom); 886 setOperationAction(ISD::SRL, VT, Custom); 887 888 setOperationAction(ISD::SMIN, VT, Custom); 889 setOperationAction(ISD::SMAX, VT, Custom); 890 setOperationAction(ISD::UMIN, VT, Custom); 891 setOperationAction(ISD::UMAX, VT, Custom); 892 setOperationAction(ISD::ABS, VT, Custom); 893 894 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 895 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 896 setOperationAction(ISD::MULHS, VT, Custom); 897 setOperationAction(ISD::MULHU, VT, Custom); 898 } 899 900 setOperationAction(ISD::SADDSAT, VT, Custom); 901 setOperationAction(ISD::UADDSAT, VT, Custom); 902 setOperationAction(ISD::SSUBSAT, VT, Custom); 903 setOperationAction(ISD::USUBSAT, VT, Custom); 904 905 setOperationAction(ISD::VSELECT, VT, Custom); 906 setOperationAction(ISD::SELECT_CC, VT, Expand); 907 908 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 909 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 910 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 911 912 // Custom-lower reduction operations to set up the corresponding custom 913 // nodes' operands. 914 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 915 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 916 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 917 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 918 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 919 920 for (unsigned VPOpc : IntegerVPOps) 921 setOperationAction(VPOpc, VT, Custom); 922 923 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 924 // type that can represent the value exactly. 925 if (VT.getVectorElementType() != MVT::i64) { 926 MVT FloatEltVT = 927 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 928 EVT FloatVT = 929 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 930 if (isTypeLegal(FloatVT)) { 931 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 932 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 933 } 934 } 935 } 936 937 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 938 if (!useRVVForFixedLengthVectorVT(VT)) 939 continue; 940 941 // By default everything must be expanded. 942 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 943 setOperationAction(Op, VT, Expand); 944 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 945 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 946 setTruncStoreAction(VT, OtherVT, Expand); 947 } 948 949 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 950 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 951 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 952 953 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 954 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 955 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 956 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 957 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 958 959 setOperationAction(ISD::LOAD, VT, Custom); 960 setOperationAction(ISD::STORE, VT, Custom); 961 setOperationAction(ISD::MLOAD, VT, Custom); 962 setOperationAction(ISD::MSTORE, VT, Custom); 963 setOperationAction(ISD::MGATHER, VT, Custom); 964 setOperationAction(ISD::MSCATTER, VT, Custom); 965 966 setOperationAction(ISD::VP_LOAD, VT, Custom); 967 setOperationAction(ISD::VP_STORE, VT, Custom); 968 setOperationAction(ISD::VP_GATHER, VT, Custom); 969 setOperationAction(ISD::VP_SCATTER, VT, Custom); 970 971 setOperationAction(ISD::FADD, VT, Custom); 972 setOperationAction(ISD::FSUB, VT, Custom); 973 setOperationAction(ISD::FMUL, VT, Custom); 974 setOperationAction(ISD::FDIV, VT, Custom); 975 setOperationAction(ISD::FNEG, VT, Custom); 976 setOperationAction(ISD::FABS, VT, Custom); 977 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 978 setOperationAction(ISD::FSQRT, VT, Custom); 979 setOperationAction(ISD::FMA, VT, Custom); 980 setOperationAction(ISD::FMINNUM, VT, Custom); 981 setOperationAction(ISD::FMAXNUM, VT, Custom); 982 983 setOperationAction(ISD::FP_ROUND, VT, Custom); 984 setOperationAction(ISD::FP_EXTEND, VT, Custom); 985 986 setOperationAction(ISD::FTRUNC, VT, Custom); 987 setOperationAction(ISD::FCEIL, VT, Custom); 988 setOperationAction(ISD::FFLOOR, VT, Custom); 989 setOperationAction(ISD::FROUND, VT, Custom); 990 991 for (auto CC : VFPCCToExpand) 992 setCondCodeAction(CC, VT, Expand); 993 994 setOperationAction(ISD::VSELECT, VT, Custom); 995 setOperationAction(ISD::SELECT, VT, Custom); 996 setOperationAction(ISD::SELECT_CC, VT, Expand); 997 998 setOperationAction(ISD::BITCAST, VT, Custom); 999 1000 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1001 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1002 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1003 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1004 1005 for (unsigned VPOpc : FloatingPointVPOps) 1006 setOperationAction(VPOpc, VT, Custom); 1007 } 1008 1009 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1010 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1011 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1012 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1013 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1014 if (Subtarget.hasStdExtZfh()) 1015 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1016 if (Subtarget.hasStdExtF()) 1017 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1018 if (Subtarget.hasStdExtD()) 1019 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1020 } 1021 } 1022 1023 // Function alignments. 1024 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1025 setMinFunctionAlignment(FunctionAlignment); 1026 setPrefFunctionAlignment(FunctionAlignment); 1027 1028 setMinimumJumpTableEntries(5); 1029 1030 // Jumps are expensive, compared to logic 1031 setJumpIsExpensive(); 1032 1033 setTargetDAGCombine(ISD::ADD); 1034 setTargetDAGCombine(ISD::SUB); 1035 setTargetDAGCombine(ISD::AND); 1036 setTargetDAGCombine(ISD::OR); 1037 setTargetDAGCombine(ISD::XOR); 1038 if (Subtarget.hasStdExtZbp()) { 1039 setTargetDAGCombine(ISD::ROTL); 1040 setTargetDAGCombine(ISD::ROTR); 1041 } 1042 if (Subtarget.hasStdExtZbkb()) 1043 setTargetDAGCombine(ISD::BITREVERSE); 1044 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1045 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 1046 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1047 if (Subtarget.hasStdExtF()) { 1048 setTargetDAGCombine(ISD::ZERO_EXTEND); 1049 setTargetDAGCombine(ISD::FP_TO_SINT); 1050 setTargetDAGCombine(ISD::FP_TO_UINT); 1051 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1052 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1053 } 1054 if (Subtarget.hasVInstructions()) { 1055 setTargetDAGCombine(ISD::FCOPYSIGN); 1056 setTargetDAGCombine(ISD::MGATHER); 1057 setTargetDAGCombine(ISD::MSCATTER); 1058 setTargetDAGCombine(ISD::VP_GATHER); 1059 setTargetDAGCombine(ISD::VP_SCATTER); 1060 setTargetDAGCombine(ISD::SRA); 1061 setTargetDAGCombine(ISD::SRL); 1062 setTargetDAGCombine(ISD::SHL); 1063 setTargetDAGCombine(ISD::STORE); 1064 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1065 } 1066 1067 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1068 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1069 } 1070 1071 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1072 LLVMContext &Context, 1073 EVT VT) const { 1074 if (!VT.isVector()) 1075 return getPointerTy(DL); 1076 if (Subtarget.hasVInstructions() && 1077 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1078 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1079 return VT.changeVectorElementTypeToInteger(); 1080 } 1081 1082 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1083 return Subtarget.getXLenVT(); 1084 } 1085 1086 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1087 const CallInst &I, 1088 MachineFunction &MF, 1089 unsigned Intrinsic) const { 1090 auto &DL = I.getModule()->getDataLayout(); 1091 switch (Intrinsic) { 1092 default: 1093 return false; 1094 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1099 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1100 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1101 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1102 case Intrinsic::riscv_masked_cmpxchg_i32: 1103 Info.opc = ISD::INTRINSIC_W_CHAIN; 1104 Info.memVT = MVT::i32; 1105 Info.ptrVal = I.getArgOperand(0); 1106 Info.offset = 0; 1107 Info.align = Align(4); 1108 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1109 MachineMemOperand::MOVolatile; 1110 return true; 1111 case Intrinsic::riscv_masked_strided_load: 1112 Info.opc = ISD::INTRINSIC_W_CHAIN; 1113 Info.ptrVal = I.getArgOperand(1); 1114 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1115 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1116 Info.size = MemoryLocation::UnknownSize; 1117 Info.flags |= MachineMemOperand::MOLoad; 1118 return true; 1119 case Intrinsic::riscv_masked_strided_store: 1120 Info.opc = ISD::INTRINSIC_VOID; 1121 Info.ptrVal = I.getArgOperand(1); 1122 Info.memVT = 1123 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1124 Info.align = Align( 1125 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1126 8); 1127 Info.size = MemoryLocation::UnknownSize; 1128 Info.flags |= MachineMemOperand::MOStore; 1129 return true; 1130 case Intrinsic::riscv_seg2_load: 1131 case Intrinsic::riscv_seg3_load: 1132 case Intrinsic::riscv_seg4_load: 1133 case Intrinsic::riscv_seg5_load: 1134 case Intrinsic::riscv_seg6_load: 1135 case Intrinsic::riscv_seg7_load: 1136 case Intrinsic::riscv_seg8_load: 1137 Info.opc = ISD::INTRINSIC_W_CHAIN; 1138 Info.ptrVal = I.getArgOperand(0); 1139 Info.memVT = 1140 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1141 Info.align = 1142 Align(DL.getTypeSizeInBits( 1143 I.getType()->getStructElementType(0)->getScalarType()) / 1144 8); 1145 Info.size = MemoryLocation::UnknownSize; 1146 Info.flags |= MachineMemOperand::MOLoad; 1147 return true; 1148 } 1149 } 1150 1151 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1152 const AddrMode &AM, Type *Ty, 1153 unsigned AS, 1154 Instruction *I) const { 1155 // No global is ever allowed as a base. 1156 if (AM.BaseGV) 1157 return false; 1158 1159 // Require a 12-bit signed offset. 1160 if (!isInt<12>(AM.BaseOffs)) 1161 return false; 1162 1163 switch (AM.Scale) { 1164 case 0: // "r+i" or just "i", depending on HasBaseReg. 1165 break; 1166 case 1: 1167 if (!AM.HasBaseReg) // allow "r+i". 1168 break; 1169 return false; // disallow "r+r" or "r+r+i". 1170 default: 1171 return false; 1172 } 1173 1174 return true; 1175 } 1176 1177 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1178 return isInt<12>(Imm); 1179 } 1180 1181 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1182 return isInt<12>(Imm); 1183 } 1184 1185 // On RV32, 64-bit integers are split into their high and low parts and held 1186 // in two different registers, so the trunc is free since the low register can 1187 // just be used. 1188 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1189 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1190 return false; 1191 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1192 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1193 return (SrcBits == 64 && DestBits == 32); 1194 } 1195 1196 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1197 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1198 !SrcVT.isInteger() || !DstVT.isInteger()) 1199 return false; 1200 unsigned SrcBits = SrcVT.getSizeInBits(); 1201 unsigned DestBits = DstVT.getSizeInBits(); 1202 return (SrcBits == 64 && DestBits == 32); 1203 } 1204 1205 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1206 // Zexts are free if they can be combined with a load. 1207 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1208 // poorly with type legalization of compares preferring sext. 1209 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1210 EVT MemVT = LD->getMemoryVT(); 1211 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1212 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1213 LD->getExtensionType() == ISD::ZEXTLOAD)) 1214 return true; 1215 } 1216 1217 return TargetLowering::isZExtFree(Val, VT2); 1218 } 1219 1220 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1221 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1222 } 1223 1224 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1225 return Subtarget.hasStdExtZbb(); 1226 } 1227 1228 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1229 return Subtarget.hasStdExtZbb(); 1230 } 1231 1232 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1233 EVT VT = Y.getValueType(); 1234 1235 // FIXME: Support vectors once we have tests. 1236 if (VT.isVector()) 1237 return false; 1238 1239 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1240 Subtarget.hasStdExtZbkb()) && 1241 !isa<ConstantSDNode>(Y); 1242 } 1243 1244 /// Check if sinking \p I's operands to I's basic block is profitable, because 1245 /// the operands can be folded into a target instruction, e.g. 1246 /// splats of scalars can fold into vector instructions. 1247 bool RISCVTargetLowering::shouldSinkOperands( 1248 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1249 using namespace llvm::PatternMatch; 1250 1251 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1252 return false; 1253 1254 auto IsSinker = [&](Instruction *I, int Operand) { 1255 switch (I->getOpcode()) { 1256 case Instruction::Add: 1257 case Instruction::Sub: 1258 case Instruction::Mul: 1259 case Instruction::And: 1260 case Instruction::Or: 1261 case Instruction::Xor: 1262 case Instruction::FAdd: 1263 case Instruction::FSub: 1264 case Instruction::FMul: 1265 case Instruction::FDiv: 1266 case Instruction::ICmp: 1267 case Instruction::FCmp: 1268 return true; 1269 case Instruction::Shl: 1270 case Instruction::LShr: 1271 case Instruction::AShr: 1272 case Instruction::UDiv: 1273 case Instruction::SDiv: 1274 case Instruction::URem: 1275 case Instruction::SRem: 1276 return Operand == 1; 1277 case Instruction::Call: 1278 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1279 switch (II->getIntrinsicID()) { 1280 case Intrinsic::fma: 1281 case Intrinsic::vp_fma: 1282 return Operand == 0 || Operand == 1; 1283 // FIXME: Our patterns can only match vx/vf instructions when the splat 1284 // it on the RHS, because TableGen doesn't recognize our VP operations 1285 // as commutative. 1286 case Intrinsic::vp_add: 1287 case Intrinsic::vp_mul: 1288 case Intrinsic::vp_and: 1289 case Intrinsic::vp_or: 1290 case Intrinsic::vp_xor: 1291 case Intrinsic::vp_fadd: 1292 case Intrinsic::vp_fmul: 1293 case Intrinsic::vp_shl: 1294 case Intrinsic::vp_lshr: 1295 case Intrinsic::vp_ashr: 1296 case Intrinsic::vp_udiv: 1297 case Intrinsic::vp_sdiv: 1298 case Intrinsic::vp_urem: 1299 case Intrinsic::vp_srem: 1300 return Operand == 1; 1301 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1302 // explicit patterns for both LHS and RHS (as 'vr' versions). 1303 case Intrinsic::vp_sub: 1304 case Intrinsic::vp_fsub: 1305 case Intrinsic::vp_fdiv: 1306 return Operand == 0 || Operand == 1; 1307 default: 1308 return false; 1309 } 1310 } 1311 return false; 1312 default: 1313 return false; 1314 } 1315 }; 1316 1317 for (auto OpIdx : enumerate(I->operands())) { 1318 if (!IsSinker(I, OpIdx.index())) 1319 continue; 1320 1321 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1322 // Make sure we are not already sinking this operand 1323 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1324 continue; 1325 1326 // We are looking for a splat that can be sunk. 1327 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1328 m_Undef(), m_ZeroMask()))) 1329 continue; 1330 1331 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1332 // and vector registers 1333 for (Use &U : Op->uses()) { 1334 Instruction *Insn = cast<Instruction>(U.getUser()); 1335 if (!IsSinker(Insn, U.getOperandNo())) 1336 return false; 1337 } 1338 1339 Ops.push_back(&Op->getOperandUse(0)); 1340 Ops.push_back(&OpIdx.value()); 1341 } 1342 return true; 1343 } 1344 1345 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1346 bool ForCodeSize) const { 1347 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1348 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1349 return false; 1350 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1351 return false; 1352 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1353 return false; 1354 return Imm.isZero(); 1355 } 1356 1357 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1358 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1359 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1360 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1361 } 1362 1363 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1364 CallingConv::ID CC, 1365 EVT VT) const { 1366 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1367 // We might still end up using a GPR but that will be decided based on ABI. 1368 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1369 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1370 return MVT::f32; 1371 1372 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1373 } 1374 1375 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1376 CallingConv::ID CC, 1377 EVT VT) const { 1378 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1379 // We might still end up using a GPR but that will be decided based on ABI. 1380 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1381 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1382 return 1; 1383 1384 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1385 } 1386 1387 // Changes the condition code and swaps operands if necessary, so the SetCC 1388 // operation matches one of the comparisons supported directly by branches 1389 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1390 // with 1/-1. 1391 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1392 ISD::CondCode &CC, SelectionDAG &DAG) { 1393 // Convert X > -1 to X >= 0. 1394 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1395 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1396 CC = ISD::SETGE; 1397 return; 1398 } 1399 // Convert X < 1 to 0 >= X. 1400 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1401 RHS = LHS; 1402 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1403 CC = ISD::SETGE; 1404 return; 1405 } 1406 1407 switch (CC) { 1408 default: 1409 break; 1410 case ISD::SETGT: 1411 case ISD::SETLE: 1412 case ISD::SETUGT: 1413 case ISD::SETULE: 1414 CC = ISD::getSetCCSwappedOperands(CC); 1415 std::swap(LHS, RHS); 1416 break; 1417 } 1418 } 1419 1420 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1421 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1422 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1423 if (VT.getVectorElementType() == MVT::i1) 1424 KnownSize *= 8; 1425 1426 switch (KnownSize) { 1427 default: 1428 llvm_unreachable("Invalid LMUL."); 1429 case 8: 1430 return RISCVII::VLMUL::LMUL_F8; 1431 case 16: 1432 return RISCVII::VLMUL::LMUL_F4; 1433 case 32: 1434 return RISCVII::VLMUL::LMUL_F2; 1435 case 64: 1436 return RISCVII::VLMUL::LMUL_1; 1437 case 128: 1438 return RISCVII::VLMUL::LMUL_2; 1439 case 256: 1440 return RISCVII::VLMUL::LMUL_4; 1441 case 512: 1442 return RISCVII::VLMUL::LMUL_8; 1443 } 1444 } 1445 1446 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1447 switch (LMul) { 1448 default: 1449 llvm_unreachable("Invalid LMUL."); 1450 case RISCVII::VLMUL::LMUL_F8: 1451 case RISCVII::VLMUL::LMUL_F4: 1452 case RISCVII::VLMUL::LMUL_F2: 1453 case RISCVII::VLMUL::LMUL_1: 1454 return RISCV::VRRegClassID; 1455 case RISCVII::VLMUL::LMUL_2: 1456 return RISCV::VRM2RegClassID; 1457 case RISCVII::VLMUL::LMUL_4: 1458 return RISCV::VRM4RegClassID; 1459 case RISCVII::VLMUL::LMUL_8: 1460 return RISCV::VRM8RegClassID; 1461 } 1462 } 1463 1464 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1465 RISCVII::VLMUL LMUL = getLMUL(VT); 1466 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1467 LMUL == RISCVII::VLMUL::LMUL_F4 || 1468 LMUL == RISCVII::VLMUL::LMUL_F2 || 1469 LMUL == RISCVII::VLMUL::LMUL_1) { 1470 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1471 "Unexpected subreg numbering"); 1472 return RISCV::sub_vrm1_0 + Index; 1473 } 1474 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1475 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1476 "Unexpected subreg numbering"); 1477 return RISCV::sub_vrm2_0 + Index; 1478 } 1479 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1480 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1481 "Unexpected subreg numbering"); 1482 return RISCV::sub_vrm4_0 + Index; 1483 } 1484 llvm_unreachable("Invalid vector type."); 1485 } 1486 1487 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1488 if (VT.getVectorElementType() == MVT::i1) 1489 return RISCV::VRRegClassID; 1490 return getRegClassIDForLMUL(getLMUL(VT)); 1491 } 1492 1493 // Attempt to decompose a subvector insert/extract between VecVT and 1494 // SubVecVT via subregister indices. Returns the subregister index that 1495 // can perform the subvector insert/extract with the given element index, as 1496 // well as the index corresponding to any leftover subvectors that must be 1497 // further inserted/extracted within the register class for SubVecVT. 1498 std::pair<unsigned, unsigned> 1499 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1500 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1501 const RISCVRegisterInfo *TRI) { 1502 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1503 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1504 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1505 "Register classes not ordered"); 1506 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1507 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1508 // Try to compose a subregister index that takes us from the incoming 1509 // LMUL>1 register class down to the outgoing one. At each step we half 1510 // the LMUL: 1511 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1512 // Note that this is not guaranteed to find a subregister index, such as 1513 // when we are extracting from one VR type to another. 1514 unsigned SubRegIdx = RISCV::NoSubRegister; 1515 for (const unsigned RCID : 1516 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1517 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1518 VecVT = VecVT.getHalfNumVectorElementsVT(); 1519 bool IsHi = 1520 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1521 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1522 getSubregIndexByMVT(VecVT, IsHi)); 1523 if (IsHi) 1524 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1525 } 1526 return {SubRegIdx, InsertExtractIdx}; 1527 } 1528 1529 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1530 // stores for those types. 1531 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1532 return !Subtarget.useRVVForFixedLengthVectors() || 1533 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1534 } 1535 1536 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1537 if (ScalarTy->isPointerTy()) 1538 return true; 1539 1540 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1541 ScalarTy->isIntegerTy(32)) 1542 return true; 1543 1544 if (ScalarTy->isIntegerTy(64)) 1545 return Subtarget.hasVInstructionsI64(); 1546 1547 if (ScalarTy->isHalfTy()) 1548 return Subtarget.hasVInstructionsF16(); 1549 if (ScalarTy->isFloatTy()) 1550 return Subtarget.hasVInstructionsF32(); 1551 if (ScalarTy->isDoubleTy()) 1552 return Subtarget.hasVInstructionsF64(); 1553 1554 return false; 1555 } 1556 1557 static SDValue getVLOperand(SDValue Op) { 1558 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1559 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1560 "Unexpected opcode"); 1561 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1562 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1563 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1564 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1565 if (!II) 1566 return SDValue(); 1567 return Op.getOperand(II->VLOperand + 1 + HasChain); 1568 } 1569 1570 static bool useRVVForFixedLengthVectorVT(MVT VT, 1571 const RISCVSubtarget &Subtarget) { 1572 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1573 if (!Subtarget.useRVVForFixedLengthVectors()) 1574 return false; 1575 1576 // We only support a set of vector types with a consistent maximum fixed size 1577 // across all supported vector element types to avoid legalization issues. 1578 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1579 // fixed-length vector type we support is 1024 bytes. 1580 if (VT.getFixedSizeInBits() > 1024 * 8) 1581 return false; 1582 1583 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1584 1585 MVT EltVT = VT.getVectorElementType(); 1586 1587 // Don't use RVV for vectors we cannot scalarize if required. 1588 switch (EltVT.SimpleTy) { 1589 // i1 is supported but has different rules. 1590 default: 1591 return false; 1592 case MVT::i1: 1593 // Masks can only use a single register. 1594 if (VT.getVectorNumElements() > MinVLen) 1595 return false; 1596 MinVLen /= 8; 1597 break; 1598 case MVT::i8: 1599 case MVT::i16: 1600 case MVT::i32: 1601 break; 1602 case MVT::i64: 1603 if (!Subtarget.hasVInstructionsI64()) 1604 return false; 1605 break; 1606 case MVT::f16: 1607 if (!Subtarget.hasVInstructionsF16()) 1608 return false; 1609 break; 1610 case MVT::f32: 1611 if (!Subtarget.hasVInstructionsF32()) 1612 return false; 1613 break; 1614 case MVT::f64: 1615 if (!Subtarget.hasVInstructionsF64()) 1616 return false; 1617 break; 1618 } 1619 1620 // Reject elements larger than ELEN. 1621 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1622 return false; 1623 1624 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1625 // Don't use RVV for types that don't fit. 1626 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1627 return false; 1628 1629 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1630 // the base fixed length RVV support in place. 1631 if (!VT.isPow2VectorType()) 1632 return false; 1633 1634 return true; 1635 } 1636 1637 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1638 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1639 } 1640 1641 // Return the largest legal scalable vector type that matches VT's element type. 1642 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1643 const RISCVSubtarget &Subtarget) { 1644 // This may be called before legal types are setup. 1645 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1646 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1647 "Expected legal fixed length vector!"); 1648 1649 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1650 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1651 1652 MVT EltVT = VT.getVectorElementType(); 1653 switch (EltVT.SimpleTy) { 1654 default: 1655 llvm_unreachable("unexpected element type for RVV container"); 1656 case MVT::i1: 1657 case MVT::i8: 1658 case MVT::i16: 1659 case MVT::i32: 1660 case MVT::i64: 1661 case MVT::f16: 1662 case MVT::f32: 1663 case MVT::f64: { 1664 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1665 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1666 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1667 unsigned NumElts = 1668 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1669 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1670 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1671 return MVT::getScalableVectorVT(EltVT, NumElts); 1672 } 1673 } 1674 } 1675 1676 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1677 const RISCVSubtarget &Subtarget) { 1678 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1679 Subtarget); 1680 } 1681 1682 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1683 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1684 } 1685 1686 // Grow V to consume an entire RVV register. 1687 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1688 const RISCVSubtarget &Subtarget) { 1689 assert(VT.isScalableVector() && 1690 "Expected to convert into a scalable vector!"); 1691 assert(V.getValueType().isFixedLengthVector() && 1692 "Expected a fixed length vector operand!"); 1693 SDLoc DL(V); 1694 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1695 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1696 } 1697 1698 // Shrink V so it's just big enough to maintain a VT's worth of data. 1699 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1700 const RISCVSubtarget &Subtarget) { 1701 assert(VT.isFixedLengthVector() && 1702 "Expected to convert into a fixed length vector!"); 1703 assert(V.getValueType().isScalableVector() && 1704 "Expected a scalable vector operand!"); 1705 SDLoc DL(V); 1706 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1707 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1708 } 1709 1710 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1711 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1712 // the vector type that it is contained in. 1713 static std::pair<SDValue, SDValue> 1714 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1715 const RISCVSubtarget &Subtarget) { 1716 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1717 MVT XLenVT = Subtarget.getXLenVT(); 1718 SDValue VL = VecVT.isFixedLengthVector() 1719 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1720 : DAG.getRegister(RISCV::X0, XLenVT); 1721 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1722 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1723 return {Mask, VL}; 1724 } 1725 1726 // As above but assuming the given type is a scalable vector type. 1727 static std::pair<SDValue, SDValue> 1728 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1729 const RISCVSubtarget &Subtarget) { 1730 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1731 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1732 } 1733 1734 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1735 // of either is (currently) supported. This can get us into an infinite loop 1736 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1737 // as a ..., etc. 1738 // Until either (or both) of these can reliably lower any node, reporting that 1739 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1740 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1741 // which is not desirable. 1742 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1743 EVT VT, unsigned DefinedValues) const { 1744 return false; 1745 } 1746 1747 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1748 const RISCVSubtarget &Subtarget) { 1749 // RISCV FP-to-int conversions saturate to the destination register size, but 1750 // don't produce 0 for nan. We can use a conversion instruction and fix the 1751 // nan case with a compare and a select. 1752 SDValue Src = Op.getOperand(0); 1753 1754 EVT DstVT = Op.getValueType(); 1755 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1756 1757 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1758 unsigned Opc; 1759 if (SatVT == DstVT) 1760 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1761 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1762 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1763 else 1764 return SDValue(); 1765 // FIXME: Support other SatVTs by clamping before or after the conversion. 1766 1767 SDLoc DL(Op); 1768 SDValue FpToInt = DAG.getNode( 1769 Opc, DL, DstVT, Src, 1770 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1771 1772 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1773 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1774 } 1775 1776 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1777 // and back. Taking care to avoid converting values that are nan or already 1778 // correct. 1779 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1780 // have FRM dependencies modeled yet. 1781 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1782 MVT VT = Op.getSimpleValueType(); 1783 assert(VT.isVector() && "Unexpected type"); 1784 1785 SDLoc DL(Op); 1786 1787 // Freeze the source since we are increasing the number of uses. 1788 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1789 1790 // Truncate to integer and convert back to FP. 1791 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1792 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1793 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1794 1795 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1796 1797 if (Op.getOpcode() == ISD::FCEIL) { 1798 // If the truncated value is the greater than or equal to the original 1799 // value, we've computed the ceil. Otherwise, we went the wrong way and 1800 // need to increase by 1. 1801 // FIXME: This should use a masked operation. Handle here or in isel? 1802 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1803 DAG.getConstantFP(1.0, DL, VT)); 1804 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1805 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1806 } else if (Op.getOpcode() == ISD::FFLOOR) { 1807 // If the truncated value is the less than or equal to the original value, 1808 // we've computed the floor. Otherwise, we went the wrong way and need to 1809 // decrease by 1. 1810 // FIXME: This should use a masked operation. Handle here or in isel? 1811 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1812 DAG.getConstantFP(1.0, DL, VT)); 1813 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1814 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1815 } 1816 1817 // Restore the original sign so that -0.0 is preserved. 1818 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1819 1820 // Determine the largest integer that can be represented exactly. This and 1821 // values larger than it don't have any fractional bits so don't need to 1822 // be converted. 1823 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1824 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1825 APFloat MaxVal = APFloat(FltSem); 1826 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1827 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1828 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1829 1830 // If abs(Src) was larger than MaxVal or nan, keep it. 1831 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1832 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1833 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1834 } 1835 1836 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1837 // This mode isn't supported in vector hardware on RISCV. But as long as we 1838 // aren't compiling with trapping math, we can emulate this with 1839 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1840 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1841 // dependencies modeled yet. 1842 // FIXME: Use masked operations to avoid final merge. 1843 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1844 MVT VT = Op.getSimpleValueType(); 1845 assert(VT.isVector() && "Unexpected type"); 1846 1847 SDLoc DL(Op); 1848 1849 // Freeze the source since we are increasing the number of uses. 1850 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1851 1852 // We do the conversion on the absolute value and fix the sign at the end. 1853 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1854 1855 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1856 bool Ignored; 1857 APFloat Point5Pred = APFloat(0.5f); 1858 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1859 Point5Pred.next(/*nextDown*/ true); 1860 1861 // Add the adjustment. 1862 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1863 DAG.getConstantFP(Point5Pred, DL, VT)); 1864 1865 // Truncate to integer and convert back to fp. 1866 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1867 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1868 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1869 1870 // Restore the original sign. 1871 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1872 1873 // Determine the largest integer that can be represented exactly. This and 1874 // values larger than it don't have any fractional bits so don't need to 1875 // be converted. 1876 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1877 APFloat MaxVal = APFloat(FltSem); 1878 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1879 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1880 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1881 1882 // If abs(Src) was larger than MaxVal or nan, keep it. 1883 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1884 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1885 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1886 } 1887 1888 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1889 const RISCVSubtarget &Subtarget) { 1890 MVT VT = Op.getSimpleValueType(); 1891 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1892 1893 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1894 1895 SDLoc DL(Op); 1896 SDValue Mask, VL; 1897 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1898 1899 unsigned Opc = 1900 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1901 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 1902 Op.getOperand(0), VL); 1903 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1904 } 1905 1906 struct VIDSequence { 1907 int64_t StepNumerator; 1908 unsigned StepDenominator; 1909 int64_t Addend; 1910 }; 1911 1912 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1913 // to the (non-zero) step S and start value X. This can be then lowered as the 1914 // RVV sequence (VID * S) + X, for example. 1915 // The step S is represented as an integer numerator divided by a positive 1916 // denominator. Note that the implementation currently only identifies 1917 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1918 // cannot detect 2/3, for example. 1919 // Note that this method will also match potentially unappealing index 1920 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1921 // determine whether this is worth generating code for. 1922 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1923 unsigned NumElts = Op.getNumOperands(); 1924 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1925 if (!Op.getValueType().isInteger()) 1926 return None; 1927 1928 Optional<unsigned> SeqStepDenom; 1929 Optional<int64_t> SeqStepNum, SeqAddend; 1930 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1931 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1932 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1933 // Assume undef elements match the sequence; we just have to be careful 1934 // when interpolating across them. 1935 if (Op.getOperand(Idx).isUndef()) 1936 continue; 1937 // The BUILD_VECTOR must be all constants. 1938 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1939 return None; 1940 1941 uint64_t Val = Op.getConstantOperandVal(Idx) & 1942 maskTrailingOnes<uint64_t>(EltSizeInBits); 1943 1944 if (PrevElt) { 1945 // Calculate the step since the last non-undef element, and ensure 1946 // it's consistent across the entire sequence. 1947 unsigned IdxDiff = Idx - PrevElt->second; 1948 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1949 1950 // A zero-value value difference means that we're somewhere in the middle 1951 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1952 // step change before evaluating the sequence. 1953 if (ValDiff != 0) { 1954 int64_t Remainder = ValDiff % IdxDiff; 1955 // Normalize the step if it's greater than 1. 1956 if (Remainder != ValDiff) { 1957 // The difference must cleanly divide the element span. 1958 if (Remainder != 0) 1959 return None; 1960 ValDiff /= IdxDiff; 1961 IdxDiff = 1; 1962 } 1963 1964 if (!SeqStepNum) 1965 SeqStepNum = ValDiff; 1966 else if (ValDiff != SeqStepNum) 1967 return None; 1968 1969 if (!SeqStepDenom) 1970 SeqStepDenom = IdxDiff; 1971 else if (IdxDiff != *SeqStepDenom) 1972 return None; 1973 } 1974 } 1975 1976 // Record and/or check any addend. 1977 if (SeqStepNum && SeqStepDenom) { 1978 uint64_t ExpectedVal = 1979 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1980 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1981 if (!SeqAddend) 1982 SeqAddend = Addend; 1983 else if (SeqAddend != Addend) 1984 return None; 1985 } 1986 1987 // Record this non-undef element for later. 1988 if (!PrevElt || PrevElt->first != Val) 1989 PrevElt = std::make_pair(Val, Idx); 1990 } 1991 // We need to have logged both a step and an addend for this to count as 1992 // a legal index sequence. 1993 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1994 return None; 1995 1996 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1997 } 1998 1999 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 2000 // and lower it as a VRGATHER_VX_VL from the source vector. 2001 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 2002 SelectionDAG &DAG, 2003 const RISCVSubtarget &Subtarget) { 2004 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2005 return SDValue(); 2006 SDValue Vec = SplatVal.getOperand(0); 2007 // Only perform this optimization on vectors of the same size for simplicity. 2008 if (Vec.getValueType() != VT) 2009 return SDValue(); 2010 SDValue Idx = SplatVal.getOperand(1); 2011 // The index must be a legal type. 2012 if (Idx.getValueType() != Subtarget.getXLenVT()) 2013 return SDValue(); 2014 2015 MVT ContainerVT = VT; 2016 if (VT.isFixedLengthVector()) { 2017 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2018 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2019 } 2020 2021 SDValue Mask, VL; 2022 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2023 2024 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2025 Idx, Mask, VL); 2026 2027 if (!VT.isFixedLengthVector()) 2028 return Gather; 2029 2030 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2031 } 2032 2033 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2034 const RISCVSubtarget &Subtarget) { 2035 MVT VT = Op.getSimpleValueType(); 2036 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2037 2038 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2039 2040 SDLoc DL(Op); 2041 SDValue Mask, VL; 2042 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2043 2044 MVT XLenVT = Subtarget.getXLenVT(); 2045 unsigned NumElts = Op.getNumOperands(); 2046 2047 if (VT.getVectorElementType() == MVT::i1) { 2048 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2049 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2050 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2051 } 2052 2053 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2054 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2055 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2056 } 2057 2058 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2059 // scalar integer chunks whose bit-width depends on the number of mask 2060 // bits and XLEN. 2061 // First, determine the most appropriate scalar integer type to use. This 2062 // is at most XLenVT, but may be shrunk to a smaller vector element type 2063 // according to the size of the final vector - use i8 chunks rather than 2064 // XLenVT if we're producing a v8i1. This results in more consistent 2065 // codegen across RV32 and RV64. 2066 unsigned NumViaIntegerBits = 2067 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2068 NumViaIntegerBits = std::min(NumViaIntegerBits, 2069 Subtarget.getMaxELENForFixedLengthVectors()); 2070 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2071 // If we have to use more than one INSERT_VECTOR_ELT then this 2072 // optimization is likely to increase code size; avoid peforming it in 2073 // such a case. We can use a load from a constant pool in this case. 2074 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2075 return SDValue(); 2076 // Now we can create our integer vector type. Note that it may be larger 2077 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2078 MVT IntegerViaVecVT = 2079 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2080 divideCeil(NumElts, NumViaIntegerBits)); 2081 2082 uint64_t Bits = 0; 2083 unsigned BitPos = 0, IntegerEltIdx = 0; 2084 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2085 2086 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2087 // Once we accumulate enough bits to fill our scalar type, insert into 2088 // our vector and clear our accumulated data. 2089 if (I != 0 && I % NumViaIntegerBits == 0) { 2090 if (NumViaIntegerBits <= 32) 2091 Bits = SignExtend64(Bits, 32); 2092 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2093 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2094 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2095 Bits = 0; 2096 BitPos = 0; 2097 IntegerEltIdx++; 2098 } 2099 SDValue V = Op.getOperand(I); 2100 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2101 Bits |= ((uint64_t)BitValue << BitPos); 2102 } 2103 2104 // Insert the (remaining) scalar value into position in our integer 2105 // vector type. 2106 if (NumViaIntegerBits <= 32) 2107 Bits = SignExtend64(Bits, 32); 2108 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2109 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2110 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2111 2112 if (NumElts < NumViaIntegerBits) { 2113 // If we're producing a smaller vector than our minimum legal integer 2114 // type, bitcast to the equivalent (known-legal) mask type, and extract 2115 // our final mask. 2116 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2117 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2118 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2119 DAG.getConstant(0, DL, XLenVT)); 2120 } else { 2121 // Else we must have produced an integer type with the same size as the 2122 // mask type; bitcast for the final result. 2123 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2124 Vec = DAG.getBitcast(VT, Vec); 2125 } 2126 2127 return Vec; 2128 } 2129 2130 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2131 // vector type, we have a legal equivalently-sized i8 type, so we can use 2132 // that. 2133 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2134 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2135 2136 SDValue WideVec; 2137 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2138 // For a splat, perform a scalar truncate before creating the wider 2139 // vector. 2140 assert(Splat.getValueType() == XLenVT && 2141 "Unexpected type for i1 splat value"); 2142 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2143 DAG.getConstant(1, DL, XLenVT)); 2144 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2145 } else { 2146 SmallVector<SDValue, 8> Ops(Op->op_values()); 2147 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2148 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2149 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2150 } 2151 2152 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2153 } 2154 2155 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2156 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2157 return Gather; 2158 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2159 : RISCVISD::VMV_V_X_VL; 2160 Splat = 2161 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2162 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2163 } 2164 2165 // Try and match index sequences, which we can lower to the vid instruction 2166 // with optional modifications. An all-undef vector is matched by 2167 // getSplatValue, above. 2168 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2169 int64_t StepNumerator = SimpleVID->StepNumerator; 2170 unsigned StepDenominator = SimpleVID->StepDenominator; 2171 int64_t Addend = SimpleVID->Addend; 2172 2173 assert(StepNumerator != 0 && "Invalid step"); 2174 bool Negate = false; 2175 int64_t SplatStepVal = StepNumerator; 2176 unsigned StepOpcode = ISD::MUL; 2177 if (StepNumerator != 1) { 2178 if (isPowerOf2_64(std::abs(StepNumerator))) { 2179 Negate = StepNumerator < 0; 2180 StepOpcode = ISD::SHL; 2181 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2182 } 2183 } 2184 2185 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2186 // threshold since it's the immediate value many RVV instructions accept. 2187 // There is no vmul.vi instruction so ensure multiply constant can fit in 2188 // a single addi instruction. 2189 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2190 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2191 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2192 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2193 // Convert right out of the scalable type so we can use standard ISD 2194 // nodes for the rest of the computation. If we used scalable types with 2195 // these, we'd lose the fixed-length vector info and generate worse 2196 // vsetvli code. 2197 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2198 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2199 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2200 SDValue SplatStep = DAG.getSplatVector( 2201 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2202 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2203 } 2204 if (StepDenominator != 1) { 2205 SDValue SplatStep = DAG.getSplatVector( 2206 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2207 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2208 } 2209 if (Addend != 0 || Negate) { 2210 SDValue SplatAddend = 2211 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2212 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2213 } 2214 return VID; 2215 } 2216 } 2217 2218 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2219 // when re-interpreted as a vector with a larger element type. For example, 2220 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2221 // could be instead splat as 2222 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2223 // TODO: This optimization could also work on non-constant splats, but it 2224 // would require bit-manipulation instructions to construct the splat value. 2225 SmallVector<SDValue> Sequence; 2226 unsigned EltBitSize = VT.getScalarSizeInBits(); 2227 const auto *BV = cast<BuildVectorSDNode>(Op); 2228 if (VT.isInteger() && EltBitSize < 64 && 2229 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2230 BV->getRepeatedSequence(Sequence) && 2231 (Sequence.size() * EltBitSize) <= 64) { 2232 unsigned SeqLen = Sequence.size(); 2233 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2234 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2235 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2236 ViaIntVT == MVT::i64) && 2237 "Unexpected sequence type"); 2238 2239 unsigned EltIdx = 0; 2240 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2241 uint64_t SplatValue = 0; 2242 // Construct the amalgamated value which can be splatted as this larger 2243 // vector type. 2244 for (const auto &SeqV : Sequence) { 2245 if (!SeqV.isUndef()) 2246 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2247 << (EltIdx * EltBitSize)); 2248 EltIdx++; 2249 } 2250 2251 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2252 // achieve better constant materializion. 2253 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2254 SplatValue = SignExtend64(SplatValue, 32); 2255 2256 // Since we can't introduce illegal i64 types at this stage, we can only 2257 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2258 // way we can use RVV instructions to splat. 2259 assert((ViaIntVT.bitsLE(XLenVT) || 2260 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2261 "Unexpected bitcast sequence"); 2262 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2263 SDValue ViaVL = 2264 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2265 MVT ViaContainerVT = 2266 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2267 SDValue Splat = 2268 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2269 DAG.getUNDEF(ViaContainerVT), 2270 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2271 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2272 return DAG.getBitcast(VT, Splat); 2273 } 2274 } 2275 2276 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2277 // which constitute a large proportion of the elements. In such cases we can 2278 // splat a vector with the dominant element and make up the shortfall with 2279 // INSERT_VECTOR_ELTs. 2280 // Note that this includes vectors of 2 elements by association. The 2281 // upper-most element is the "dominant" one, allowing us to use a splat to 2282 // "insert" the upper element, and an insert of the lower element at position 2283 // 0, which improves codegen. 2284 SDValue DominantValue; 2285 unsigned MostCommonCount = 0; 2286 DenseMap<SDValue, unsigned> ValueCounts; 2287 unsigned NumUndefElts = 2288 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2289 2290 // Track the number of scalar loads we know we'd be inserting, estimated as 2291 // any non-zero floating-point constant. Other kinds of element are either 2292 // already in registers or are materialized on demand. The threshold at which 2293 // a vector load is more desirable than several scalar materializion and 2294 // vector-insertion instructions is not known. 2295 unsigned NumScalarLoads = 0; 2296 2297 for (SDValue V : Op->op_values()) { 2298 if (V.isUndef()) 2299 continue; 2300 2301 ValueCounts.insert(std::make_pair(V, 0)); 2302 unsigned &Count = ValueCounts[V]; 2303 2304 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2305 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2306 2307 // Is this value dominant? In case of a tie, prefer the highest element as 2308 // it's cheaper to insert near the beginning of a vector than it is at the 2309 // end. 2310 if (++Count >= MostCommonCount) { 2311 DominantValue = V; 2312 MostCommonCount = Count; 2313 } 2314 } 2315 2316 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2317 unsigned NumDefElts = NumElts - NumUndefElts; 2318 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2319 2320 // Don't perform this optimization when optimizing for size, since 2321 // materializing elements and inserting them tends to cause code bloat. 2322 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2323 ((MostCommonCount > DominantValueCountThreshold) || 2324 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2325 // Start by splatting the most common element. 2326 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2327 2328 DenseSet<SDValue> Processed{DominantValue}; 2329 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2330 for (const auto &OpIdx : enumerate(Op->ops())) { 2331 const SDValue &V = OpIdx.value(); 2332 if (V.isUndef() || !Processed.insert(V).second) 2333 continue; 2334 if (ValueCounts[V] == 1) { 2335 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2336 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2337 } else { 2338 // Blend in all instances of this value using a VSELECT, using a 2339 // mask where each bit signals whether that element is the one 2340 // we're after. 2341 SmallVector<SDValue> Ops; 2342 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2343 return DAG.getConstant(V == V1, DL, XLenVT); 2344 }); 2345 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2346 DAG.getBuildVector(SelMaskTy, DL, Ops), 2347 DAG.getSplatBuildVector(VT, DL, V), Vec); 2348 } 2349 } 2350 2351 return Vec; 2352 } 2353 2354 return SDValue(); 2355 } 2356 2357 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2358 SDValue Lo, SDValue Hi, SDValue VL, 2359 SelectionDAG &DAG) { 2360 bool HasPassthru = Passthru && !Passthru.isUndef(); 2361 if (!HasPassthru && !Passthru) 2362 Passthru = DAG.getUNDEF(VT); 2363 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2364 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2365 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2366 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2367 // node in order to try and match RVV vector/scalar instructions. 2368 if ((LoC >> 31) == HiC) 2369 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2370 2371 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2372 // vmv.v.x whose EEW = 32 to lower it. 2373 auto *Const = dyn_cast<ConstantSDNode>(VL); 2374 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2375 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2376 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2377 // access the subtarget here now. 2378 auto InterVec = DAG.getNode( 2379 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2380 DAG.getRegister(RISCV::X0, MVT::i32)); 2381 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2382 } 2383 } 2384 2385 // Fall back to a stack store and stride x0 vector load. 2386 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2387 Hi, VL); 2388 } 2389 2390 // Called by type legalization to handle splat of i64 on RV32. 2391 // FIXME: We can optimize this when the type has sign or zero bits in one 2392 // of the halves. 2393 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2394 SDValue Scalar, SDValue VL, 2395 SelectionDAG &DAG) { 2396 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2397 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2398 DAG.getConstant(0, DL, MVT::i32)); 2399 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2400 DAG.getConstant(1, DL, MVT::i32)); 2401 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2402 } 2403 2404 // This function lowers a splat of a scalar operand Splat with the vector 2405 // length VL. It ensures the final sequence is type legal, which is useful when 2406 // lowering a splat after type legalization. 2407 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2408 MVT VT, SDLoc DL, SelectionDAG &DAG, 2409 const RISCVSubtarget &Subtarget) { 2410 bool HasPassthru = Passthru && !Passthru.isUndef(); 2411 if (!HasPassthru && !Passthru) 2412 Passthru = DAG.getUNDEF(VT); 2413 if (VT.isFloatingPoint()) { 2414 // If VL is 1, we could use vfmv.s.f. 2415 if (isOneConstant(VL)) 2416 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2417 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2418 } 2419 2420 MVT XLenVT = Subtarget.getXLenVT(); 2421 2422 // Simplest case is that the operand needs to be promoted to XLenVT. 2423 if (Scalar.getValueType().bitsLE(XLenVT)) { 2424 // If the operand is a constant, sign extend to increase our chances 2425 // of being able to use a .vi instruction. ANY_EXTEND would become a 2426 // a zero extend and the simm5 check in isel would fail. 2427 // FIXME: Should we ignore the upper bits in isel instead? 2428 unsigned ExtOpc = 2429 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2430 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2431 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2432 // If VL is 1 and the scalar value won't benefit from immediate, we could 2433 // use vmv.s.x. 2434 if (isOneConstant(VL) && 2435 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2436 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2437 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2438 } 2439 2440 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2441 "Unexpected scalar for splat lowering!"); 2442 2443 if (isOneConstant(VL) && isNullConstant(Scalar)) 2444 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2445 DAG.getConstant(0, DL, XLenVT), VL); 2446 2447 // Otherwise use the more complicated splatting algorithm. 2448 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2449 } 2450 2451 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2452 const RISCVSubtarget &Subtarget) { 2453 // We need to be able to widen elements to the next larger integer type. 2454 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2455 return false; 2456 2457 int Size = Mask.size(); 2458 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2459 2460 int Srcs[] = {-1, -1}; 2461 for (int i = 0; i != Size; ++i) { 2462 // Ignore undef elements. 2463 if (Mask[i] < 0) 2464 continue; 2465 2466 // Is this an even or odd element. 2467 int Pol = i % 2; 2468 2469 // Ensure we consistently use the same source for this element polarity. 2470 int Src = Mask[i] / Size; 2471 if (Srcs[Pol] < 0) 2472 Srcs[Pol] = Src; 2473 if (Srcs[Pol] != Src) 2474 return false; 2475 2476 // Make sure the element within the source is appropriate for this element 2477 // in the destination. 2478 int Elt = Mask[i] % Size; 2479 if (Elt != i / 2) 2480 return false; 2481 } 2482 2483 // We need to find a source for each polarity and they can't be the same. 2484 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2485 return false; 2486 2487 // Swap the sources if the second source was in the even polarity. 2488 SwapSources = Srcs[0] > Srcs[1]; 2489 2490 return true; 2491 } 2492 2493 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2494 /// and then extract the original number of elements from the rotated result. 2495 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2496 /// returned rotation amount is for a rotate right, where elements move from 2497 /// higher elements to lower elements. \p LoSrc indicates the first source 2498 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2499 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2500 /// 0 or 1 if a rotation is found. 2501 /// 2502 /// NOTE: We talk about rotate to the right which matches how bit shift and 2503 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2504 /// and the table below write vectors with the lowest elements on the left. 2505 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2506 int Size = Mask.size(); 2507 2508 // We need to detect various ways of spelling a rotation: 2509 // [11, 12, 13, 14, 15, 0, 1, 2] 2510 // [-1, 12, 13, 14, -1, -1, 1, -1] 2511 // [-1, -1, -1, -1, -1, -1, 1, 2] 2512 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2513 // [-1, 4, 5, 6, -1, -1, 9, -1] 2514 // [-1, 4, 5, 6, -1, -1, -1, -1] 2515 int Rotation = 0; 2516 LoSrc = -1; 2517 HiSrc = -1; 2518 for (int i = 0; i != Size; ++i) { 2519 int M = Mask[i]; 2520 if (M < 0) 2521 continue; 2522 2523 // Determine where a rotate vector would have started. 2524 int StartIdx = i - (M % Size); 2525 // The identity rotation isn't interesting, stop. 2526 if (StartIdx == 0) 2527 return -1; 2528 2529 // If we found the tail of a vector the rotation must be the missing 2530 // front. If we found the head of a vector, it must be how much of the 2531 // head. 2532 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2533 2534 if (Rotation == 0) 2535 Rotation = CandidateRotation; 2536 else if (Rotation != CandidateRotation) 2537 // The rotations don't match, so we can't match this mask. 2538 return -1; 2539 2540 // Compute which value this mask is pointing at. 2541 int MaskSrc = M < Size ? 0 : 1; 2542 2543 // Compute which of the two target values this index should be assigned to. 2544 // This reflects whether the high elements are remaining or the low elemnts 2545 // are remaining. 2546 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2547 2548 // Either set up this value if we've not encountered it before, or check 2549 // that it remains consistent. 2550 if (TargetSrc < 0) 2551 TargetSrc = MaskSrc; 2552 else if (TargetSrc != MaskSrc) 2553 // This may be a rotation, but it pulls from the inputs in some 2554 // unsupported interleaving. 2555 return -1; 2556 } 2557 2558 // Check that we successfully analyzed the mask, and normalize the results. 2559 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2560 assert((LoSrc >= 0 || HiSrc >= 0) && 2561 "Failed to find a rotated input vector!"); 2562 2563 return Rotation; 2564 } 2565 2566 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2567 const RISCVSubtarget &Subtarget) { 2568 SDValue V1 = Op.getOperand(0); 2569 SDValue V2 = Op.getOperand(1); 2570 SDLoc DL(Op); 2571 MVT XLenVT = Subtarget.getXLenVT(); 2572 MVT VT = Op.getSimpleValueType(); 2573 unsigned NumElts = VT.getVectorNumElements(); 2574 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2575 2576 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2577 2578 SDValue TrueMask, VL; 2579 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2580 2581 if (SVN->isSplat()) { 2582 const int Lane = SVN->getSplatIndex(); 2583 if (Lane >= 0) { 2584 MVT SVT = VT.getVectorElementType(); 2585 2586 // Turn splatted vector load into a strided load with an X0 stride. 2587 SDValue V = V1; 2588 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2589 // with undef. 2590 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2591 int Offset = Lane; 2592 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2593 int OpElements = 2594 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2595 V = V.getOperand(Offset / OpElements); 2596 Offset %= OpElements; 2597 } 2598 2599 // We need to ensure the load isn't atomic or volatile. 2600 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2601 auto *Ld = cast<LoadSDNode>(V); 2602 Offset *= SVT.getStoreSize(); 2603 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2604 TypeSize::Fixed(Offset), DL); 2605 2606 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2607 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2608 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2609 SDValue IntID = 2610 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2611 SDValue Ops[] = {Ld->getChain(), 2612 IntID, 2613 DAG.getUNDEF(ContainerVT), 2614 NewAddr, 2615 DAG.getRegister(RISCV::X0, XLenVT), 2616 VL}; 2617 SDValue NewLoad = DAG.getMemIntrinsicNode( 2618 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2619 DAG.getMachineFunction().getMachineMemOperand( 2620 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2621 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2622 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2623 } 2624 2625 // Otherwise use a scalar load and splat. This will give the best 2626 // opportunity to fold a splat into the operation. ISel can turn it into 2627 // the x0 strided load if we aren't able to fold away the select. 2628 if (SVT.isFloatingPoint()) 2629 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2630 Ld->getPointerInfo().getWithOffset(Offset), 2631 Ld->getOriginalAlign(), 2632 Ld->getMemOperand()->getFlags()); 2633 else 2634 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2635 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2636 Ld->getOriginalAlign(), 2637 Ld->getMemOperand()->getFlags()); 2638 DAG.makeEquivalentMemoryOrdering(Ld, V); 2639 2640 unsigned Opc = 2641 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2642 SDValue Splat = 2643 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2644 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2645 } 2646 2647 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2648 assert(Lane < (int)NumElts && "Unexpected lane!"); 2649 SDValue Gather = 2650 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2651 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2652 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2653 } 2654 } 2655 2656 ArrayRef<int> Mask = SVN->getMask(); 2657 2658 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2659 // be undef which can be handled with a single SLIDEDOWN/UP. 2660 int LoSrc, HiSrc; 2661 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2662 if (Rotation > 0) { 2663 SDValue LoV, HiV; 2664 if (LoSrc >= 0) { 2665 LoV = LoSrc == 0 ? V1 : V2; 2666 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2667 } 2668 if (HiSrc >= 0) { 2669 HiV = HiSrc == 0 ? V1 : V2; 2670 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2671 } 2672 2673 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2674 // to slide LoV up by (NumElts - Rotation). 2675 unsigned InvRotate = NumElts - Rotation; 2676 2677 SDValue Res = DAG.getUNDEF(ContainerVT); 2678 if (HiV) { 2679 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2680 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2681 // causes multiple vsetvlis in some test cases such as lowering 2682 // reduce.mul 2683 SDValue DownVL = VL; 2684 if (LoV) 2685 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2686 Res = 2687 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2688 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2689 } 2690 if (LoV) 2691 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2692 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2693 2694 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2695 } 2696 2697 // Detect an interleave shuffle and lower to 2698 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2699 bool SwapSources; 2700 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2701 // Swap sources if needed. 2702 if (SwapSources) 2703 std::swap(V1, V2); 2704 2705 // Extract the lower half of the vectors. 2706 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2707 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2708 DAG.getConstant(0, DL, XLenVT)); 2709 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2710 DAG.getConstant(0, DL, XLenVT)); 2711 2712 // Double the element width and halve the number of elements in an int type. 2713 unsigned EltBits = VT.getScalarSizeInBits(); 2714 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2715 MVT WideIntVT = 2716 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2717 // Convert this to a scalable vector. We need to base this on the 2718 // destination size to ensure there's always a type with a smaller LMUL. 2719 MVT WideIntContainerVT = 2720 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2721 2722 // Convert sources to scalable vectors with the same element count as the 2723 // larger type. 2724 MVT HalfContainerVT = MVT::getVectorVT( 2725 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2726 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2727 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2728 2729 // Cast sources to integer. 2730 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2731 MVT IntHalfVT = 2732 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2733 V1 = DAG.getBitcast(IntHalfVT, V1); 2734 V2 = DAG.getBitcast(IntHalfVT, V2); 2735 2736 // Freeze V2 since we use it twice and we need to be sure that the add and 2737 // multiply see the same value. 2738 V2 = DAG.getFreeze(V2); 2739 2740 // Recreate TrueMask using the widened type's element count. 2741 MVT MaskVT = 2742 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2743 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2744 2745 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2746 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2747 V2, TrueMask, VL); 2748 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2749 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2750 DAG.getUNDEF(IntHalfVT), 2751 DAG.getAllOnesConstant(DL, XLenVT)); 2752 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2753 V2, Multiplier, TrueMask, VL); 2754 // Add the new copies to our previous addition giving us 2^eltbits copies of 2755 // V2. This is equivalent to shifting V2 left by eltbits. This should 2756 // combine with the vwmulu.vv above to form vwmaccu.vv. 2757 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2758 TrueMask, VL); 2759 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2760 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2761 // vector VT. 2762 ContainerVT = 2763 MVT::getVectorVT(VT.getVectorElementType(), 2764 WideIntContainerVT.getVectorElementCount() * 2); 2765 Add = DAG.getBitcast(ContainerVT, Add); 2766 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2767 } 2768 2769 // Detect shuffles which can be re-expressed as vector selects; these are 2770 // shuffles in which each element in the destination is taken from an element 2771 // at the corresponding index in either source vectors. 2772 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2773 int MaskIndex = MaskIdx.value(); 2774 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2775 }); 2776 2777 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2778 2779 SmallVector<SDValue> MaskVals; 2780 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2781 // merged with a second vrgather. 2782 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2783 2784 // By default we preserve the original operand order, and use a mask to 2785 // select LHS as true and RHS as false. However, since RVV vector selects may 2786 // feature splats but only on the LHS, we may choose to invert our mask and 2787 // instead select between RHS and LHS. 2788 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2789 bool InvertMask = IsSelect == SwapOps; 2790 2791 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2792 // half. 2793 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2794 2795 // Now construct the mask that will be used by the vselect or blended 2796 // vrgather operation. For vrgathers, construct the appropriate indices into 2797 // each vector. 2798 for (int MaskIndex : Mask) { 2799 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2800 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2801 if (!IsSelect) { 2802 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2803 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2804 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2805 : DAG.getUNDEF(XLenVT)); 2806 GatherIndicesRHS.push_back( 2807 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2808 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2809 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2810 ++LHSIndexCounts[MaskIndex]; 2811 if (!IsLHSOrUndefIndex) 2812 ++RHSIndexCounts[MaskIndex - NumElts]; 2813 } 2814 } 2815 2816 if (SwapOps) { 2817 std::swap(V1, V2); 2818 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2819 } 2820 2821 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2822 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2823 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2824 2825 if (IsSelect) 2826 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2827 2828 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2829 // On such a large vector we're unable to use i8 as the index type. 2830 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2831 // may involve vector splitting if we're already at LMUL=8, or our 2832 // user-supplied maximum fixed-length LMUL. 2833 return SDValue(); 2834 } 2835 2836 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2837 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2838 MVT IndexVT = VT.changeTypeToInteger(); 2839 // Since we can't introduce illegal index types at this stage, use i16 and 2840 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2841 // than XLenVT. 2842 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2843 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2844 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2845 } 2846 2847 MVT IndexContainerVT = 2848 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2849 2850 SDValue Gather; 2851 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2852 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2853 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2854 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2855 Subtarget); 2856 } else { 2857 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2858 // If only one index is used, we can use a "splat" vrgather. 2859 // TODO: We can splat the most-common index and fix-up any stragglers, if 2860 // that's beneficial. 2861 if (LHSIndexCounts.size() == 1) { 2862 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2863 Gather = 2864 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2865 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2866 } else { 2867 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2868 LHSIndices = 2869 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2870 2871 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2872 TrueMask, VL); 2873 } 2874 } 2875 2876 // If a second vector operand is used by this shuffle, blend it in with an 2877 // additional vrgather. 2878 if (!V2.isUndef()) { 2879 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2880 // If only one index is used, we can use a "splat" vrgather. 2881 // TODO: We can splat the most-common index and fix-up any stragglers, if 2882 // that's beneficial. 2883 if (RHSIndexCounts.size() == 1) { 2884 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2885 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2886 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2887 } else { 2888 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2889 RHSIndices = 2890 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2891 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2892 VL); 2893 } 2894 2895 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2896 SelectMask = 2897 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2898 2899 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2900 Gather, VL); 2901 } 2902 2903 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2904 } 2905 2906 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2907 // Support splats for any type. These should type legalize well. 2908 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2909 return true; 2910 2911 // Only support legal VTs for other shuffles for now. 2912 if (!isTypeLegal(VT)) 2913 return false; 2914 2915 MVT SVT = VT.getSimpleVT(); 2916 2917 bool SwapSources; 2918 int LoSrc, HiSrc; 2919 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2920 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2921 } 2922 2923 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2924 SDLoc DL, SelectionDAG &DAG, 2925 const RISCVSubtarget &Subtarget) { 2926 if (VT.isScalableVector()) 2927 return DAG.getFPExtendOrRound(Op, DL, VT); 2928 assert(VT.isFixedLengthVector() && 2929 "Unexpected value type for RVV FP extend/round lowering"); 2930 SDValue Mask, VL; 2931 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2932 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2933 ? RISCVISD::FP_EXTEND_VL 2934 : RISCVISD::FP_ROUND_VL; 2935 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2936 } 2937 2938 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2939 // the exponent. 2940 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2941 MVT VT = Op.getSimpleValueType(); 2942 unsigned EltSize = VT.getScalarSizeInBits(); 2943 SDValue Src = Op.getOperand(0); 2944 SDLoc DL(Op); 2945 2946 // We need a FP type that can represent the value. 2947 // TODO: Use f16 for i8 when possible? 2948 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2949 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2950 2951 // Legal types should have been checked in the RISCVTargetLowering 2952 // constructor. 2953 // TODO: Splitting may make sense in some cases. 2954 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2955 "Expected legal float type!"); 2956 2957 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2958 // The trailing zero count is equal to log2 of this single bit value. 2959 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2960 SDValue Neg = 2961 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2962 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2963 } 2964 2965 // We have a legal FP type, convert to it. 2966 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2967 // Bitcast to integer and shift the exponent to the LSB. 2968 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2969 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2970 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2971 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2972 DAG.getConstant(ShiftAmt, DL, IntVT)); 2973 // Truncate back to original type to allow vnsrl. 2974 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2975 // The exponent contains log2 of the value in biased form. 2976 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2977 2978 // For trailing zeros, we just need to subtract the bias. 2979 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2980 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2981 DAG.getConstant(ExponentBias, DL, VT)); 2982 2983 // For leading zeros, we need to remove the bias and convert from log2 to 2984 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2985 unsigned Adjust = ExponentBias + (EltSize - 1); 2986 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2987 } 2988 2989 // While RVV has alignment restrictions, we should always be able to load as a 2990 // legal equivalently-sized byte-typed vector instead. This method is 2991 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2992 // the load is already correctly-aligned, it returns SDValue(). 2993 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2994 SelectionDAG &DAG) const { 2995 auto *Load = cast<LoadSDNode>(Op); 2996 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2997 2998 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2999 Load->getMemoryVT(), 3000 *Load->getMemOperand())) 3001 return SDValue(); 3002 3003 SDLoc DL(Op); 3004 MVT VT = Op.getSimpleValueType(); 3005 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3006 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3007 "Unexpected unaligned RVV load type"); 3008 MVT NewVT = 3009 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3010 assert(NewVT.isValid() && 3011 "Expecting equally-sized RVV vector types to be legal"); 3012 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 3013 Load->getPointerInfo(), Load->getOriginalAlign(), 3014 Load->getMemOperand()->getFlags()); 3015 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3016 } 3017 3018 // While RVV has alignment restrictions, we should always be able to store as a 3019 // legal equivalently-sized byte-typed vector instead. This method is 3020 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3021 // returns SDValue() if the store is already correctly aligned. 3022 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3023 SelectionDAG &DAG) const { 3024 auto *Store = cast<StoreSDNode>(Op); 3025 assert(Store && Store->getValue().getValueType().isVector() && 3026 "Expected vector store"); 3027 3028 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3029 Store->getMemoryVT(), 3030 *Store->getMemOperand())) 3031 return SDValue(); 3032 3033 SDLoc DL(Op); 3034 SDValue StoredVal = Store->getValue(); 3035 MVT VT = StoredVal.getSimpleValueType(); 3036 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3037 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3038 "Unexpected unaligned RVV store type"); 3039 MVT NewVT = 3040 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3041 assert(NewVT.isValid() && 3042 "Expecting equally-sized RVV vector types to be legal"); 3043 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3044 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3045 Store->getPointerInfo(), Store->getOriginalAlign(), 3046 Store->getMemOperand()->getFlags()); 3047 } 3048 3049 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3050 SelectionDAG &DAG) const { 3051 switch (Op.getOpcode()) { 3052 default: 3053 report_fatal_error("unimplemented operand"); 3054 case ISD::GlobalAddress: 3055 return lowerGlobalAddress(Op, DAG); 3056 case ISD::BlockAddress: 3057 return lowerBlockAddress(Op, DAG); 3058 case ISD::ConstantPool: 3059 return lowerConstantPool(Op, DAG); 3060 case ISD::JumpTable: 3061 return lowerJumpTable(Op, DAG); 3062 case ISD::GlobalTLSAddress: 3063 return lowerGlobalTLSAddress(Op, DAG); 3064 case ISD::SELECT: 3065 return lowerSELECT(Op, DAG); 3066 case ISD::BRCOND: 3067 return lowerBRCOND(Op, DAG); 3068 case ISD::VASTART: 3069 return lowerVASTART(Op, DAG); 3070 case ISD::FRAMEADDR: 3071 return lowerFRAMEADDR(Op, DAG); 3072 case ISD::RETURNADDR: 3073 return lowerRETURNADDR(Op, DAG); 3074 case ISD::SHL_PARTS: 3075 return lowerShiftLeftParts(Op, DAG); 3076 case ISD::SRA_PARTS: 3077 return lowerShiftRightParts(Op, DAG, true); 3078 case ISD::SRL_PARTS: 3079 return lowerShiftRightParts(Op, DAG, false); 3080 case ISD::BITCAST: { 3081 SDLoc DL(Op); 3082 EVT VT = Op.getValueType(); 3083 SDValue Op0 = Op.getOperand(0); 3084 EVT Op0VT = Op0.getValueType(); 3085 MVT XLenVT = Subtarget.getXLenVT(); 3086 if (VT.isFixedLengthVector()) { 3087 // We can handle fixed length vector bitcasts with a simple replacement 3088 // in isel. 3089 if (Op0VT.isFixedLengthVector()) 3090 return Op; 3091 // When bitcasting from scalar to fixed-length vector, insert the scalar 3092 // into a one-element vector of the result type, and perform a vector 3093 // bitcast. 3094 if (!Op0VT.isVector()) { 3095 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3096 if (!isTypeLegal(BVT)) 3097 return SDValue(); 3098 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3099 DAG.getUNDEF(BVT), Op0, 3100 DAG.getConstant(0, DL, XLenVT))); 3101 } 3102 return SDValue(); 3103 } 3104 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3105 // thus: bitcast the vector to a one-element vector type whose element type 3106 // is the same as the result type, and extract the first element. 3107 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3108 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3109 if (!isTypeLegal(BVT)) 3110 return SDValue(); 3111 SDValue BVec = DAG.getBitcast(BVT, Op0); 3112 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3113 DAG.getConstant(0, DL, XLenVT)); 3114 } 3115 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3116 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3117 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3118 return FPConv; 3119 } 3120 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3121 Subtarget.hasStdExtF()) { 3122 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3123 SDValue FPConv = 3124 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3125 return FPConv; 3126 } 3127 return SDValue(); 3128 } 3129 case ISD::INTRINSIC_WO_CHAIN: 3130 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3131 case ISD::INTRINSIC_W_CHAIN: 3132 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3133 case ISD::INTRINSIC_VOID: 3134 return LowerINTRINSIC_VOID(Op, DAG); 3135 case ISD::BSWAP: 3136 case ISD::BITREVERSE: { 3137 MVT VT = Op.getSimpleValueType(); 3138 SDLoc DL(Op); 3139 if (Subtarget.hasStdExtZbp()) { 3140 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3141 // Start with the maximum immediate value which is the bitwidth - 1. 3142 unsigned Imm = VT.getSizeInBits() - 1; 3143 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3144 if (Op.getOpcode() == ISD::BSWAP) 3145 Imm &= ~0x7U; 3146 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3147 DAG.getConstant(Imm, DL, VT)); 3148 } 3149 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3150 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3151 // Expand bitreverse to a bswap(rev8) followed by brev8. 3152 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3153 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3154 // as brev8 by an isel pattern. 3155 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3156 DAG.getConstant(7, DL, VT)); 3157 } 3158 case ISD::FSHL: 3159 case ISD::FSHR: { 3160 MVT VT = Op.getSimpleValueType(); 3161 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3162 SDLoc DL(Op); 3163 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3164 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3165 // accidentally setting the extra bit. 3166 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3167 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3168 DAG.getConstant(ShAmtWidth, DL, VT)); 3169 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3170 // instruction use different orders. fshl will return its first operand for 3171 // shift of zero, fshr will return its second operand. fsl and fsr both 3172 // return rs1 so the ISD nodes need to have different operand orders. 3173 // Shift amount is in rs2. 3174 SDValue Op0 = Op.getOperand(0); 3175 SDValue Op1 = Op.getOperand(1); 3176 unsigned Opc = RISCVISD::FSL; 3177 if (Op.getOpcode() == ISD::FSHR) { 3178 std::swap(Op0, Op1); 3179 Opc = RISCVISD::FSR; 3180 } 3181 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3182 } 3183 case ISD::TRUNCATE: { 3184 SDLoc DL(Op); 3185 MVT VT = Op.getSimpleValueType(); 3186 // Only custom-lower vector truncates 3187 if (!VT.isVector()) 3188 return Op; 3189 3190 // Truncates to mask types are handled differently 3191 if (VT.getVectorElementType() == MVT::i1) 3192 return lowerVectorMaskTrunc(Op, DAG); 3193 3194 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3195 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3196 // truncate by one power of two at a time. 3197 MVT DstEltVT = VT.getVectorElementType(); 3198 3199 SDValue Src = Op.getOperand(0); 3200 MVT SrcVT = Src.getSimpleValueType(); 3201 MVT SrcEltVT = SrcVT.getVectorElementType(); 3202 3203 assert(DstEltVT.bitsLT(SrcEltVT) && 3204 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3205 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3206 "Unexpected vector truncate lowering"); 3207 3208 MVT ContainerVT = SrcVT; 3209 if (SrcVT.isFixedLengthVector()) { 3210 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3211 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3212 } 3213 3214 SDValue Result = Src; 3215 SDValue Mask, VL; 3216 std::tie(Mask, VL) = 3217 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3218 LLVMContext &Context = *DAG.getContext(); 3219 const ElementCount Count = ContainerVT.getVectorElementCount(); 3220 do { 3221 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3222 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3223 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3224 Mask, VL); 3225 } while (SrcEltVT != DstEltVT); 3226 3227 if (SrcVT.isFixedLengthVector()) 3228 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3229 3230 return Result; 3231 } 3232 case ISD::ANY_EXTEND: 3233 case ISD::ZERO_EXTEND: 3234 if (Op.getOperand(0).getValueType().isVector() && 3235 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3236 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3237 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3238 case ISD::SIGN_EXTEND: 3239 if (Op.getOperand(0).getValueType().isVector() && 3240 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3241 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3242 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3243 case ISD::SPLAT_VECTOR_PARTS: 3244 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3245 case ISD::INSERT_VECTOR_ELT: 3246 return lowerINSERT_VECTOR_ELT(Op, DAG); 3247 case ISD::EXTRACT_VECTOR_ELT: 3248 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3249 case ISD::VSCALE: { 3250 MVT VT = Op.getSimpleValueType(); 3251 SDLoc DL(Op); 3252 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3253 // We define our scalable vector types for lmul=1 to use a 64 bit known 3254 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3255 // vscale as VLENB / 8. 3256 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3257 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3258 report_fatal_error("Support for VLEN==32 is incomplete."); 3259 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3260 // We assume VLENB is a multiple of 8. We manually choose the best shift 3261 // here because SimplifyDemandedBits isn't always able to simplify it. 3262 uint64_t Val = Op.getConstantOperandVal(0); 3263 if (isPowerOf2_64(Val)) { 3264 uint64_t Log2 = Log2_64(Val); 3265 if (Log2 < 3) 3266 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3267 DAG.getConstant(3 - Log2, DL, VT)); 3268 if (Log2 > 3) 3269 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3270 DAG.getConstant(Log2 - 3, DL, VT)); 3271 return VLENB; 3272 } 3273 // If the multiplier is a multiple of 8, scale it down to avoid needing 3274 // to shift the VLENB value. 3275 if ((Val % 8) == 0) 3276 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3277 DAG.getConstant(Val / 8, DL, VT)); 3278 } 3279 3280 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3281 DAG.getConstant(3, DL, VT)); 3282 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3283 } 3284 case ISD::FPOWI: { 3285 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3286 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3287 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3288 Op.getOperand(1).getValueType() == MVT::i32) { 3289 SDLoc DL(Op); 3290 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3291 SDValue Powi = 3292 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3293 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3294 DAG.getIntPtrConstant(0, DL)); 3295 } 3296 return SDValue(); 3297 } 3298 case ISD::FP_EXTEND: { 3299 // RVV can only do fp_extend to types double the size as the source. We 3300 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3301 // via f32. 3302 SDLoc DL(Op); 3303 MVT VT = Op.getSimpleValueType(); 3304 SDValue Src = Op.getOperand(0); 3305 MVT SrcVT = Src.getSimpleValueType(); 3306 3307 // Prepare any fixed-length vector operands. 3308 MVT ContainerVT = VT; 3309 if (SrcVT.isFixedLengthVector()) { 3310 ContainerVT = getContainerForFixedLengthVector(VT); 3311 MVT SrcContainerVT = 3312 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3313 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3314 } 3315 3316 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3317 SrcVT.getVectorElementType() != MVT::f16) { 3318 // For scalable vectors, we only need to close the gap between 3319 // vXf16->vXf64. 3320 if (!VT.isFixedLengthVector()) 3321 return Op; 3322 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3323 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3324 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3325 } 3326 3327 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3328 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3329 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3330 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3331 3332 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3333 DL, DAG, Subtarget); 3334 if (VT.isFixedLengthVector()) 3335 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3336 return Extend; 3337 } 3338 case ISD::FP_ROUND: { 3339 // RVV can only do fp_round to types half the size as the source. We 3340 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3341 // conversion instruction. 3342 SDLoc DL(Op); 3343 MVT VT = Op.getSimpleValueType(); 3344 SDValue Src = Op.getOperand(0); 3345 MVT SrcVT = Src.getSimpleValueType(); 3346 3347 // Prepare any fixed-length vector operands. 3348 MVT ContainerVT = VT; 3349 if (VT.isFixedLengthVector()) { 3350 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3351 ContainerVT = 3352 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3353 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3354 } 3355 3356 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3357 SrcVT.getVectorElementType() != MVT::f64) { 3358 // For scalable vectors, we only need to close the gap between 3359 // vXf64<->vXf16. 3360 if (!VT.isFixedLengthVector()) 3361 return Op; 3362 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3363 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3364 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3365 } 3366 3367 SDValue Mask, VL; 3368 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3369 3370 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3371 SDValue IntermediateRound = 3372 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3373 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3374 DL, DAG, Subtarget); 3375 3376 if (VT.isFixedLengthVector()) 3377 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3378 return Round; 3379 } 3380 case ISD::FP_TO_SINT: 3381 case ISD::FP_TO_UINT: 3382 case ISD::SINT_TO_FP: 3383 case ISD::UINT_TO_FP: { 3384 // RVV can only do fp<->int conversions to types half/double the size as 3385 // the source. We custom-lower any conversions that do two hops into 3386 // sequences. 3387 MVT VT = Op.getSimpleValueType(); 3388 if (!VT.isVector()) 3389 return Op; 3390 SDLoc DL(Op); 3391 SDValue Src = Op.getOperand(0); 3392 MVT EltVT = VT.getVectorElementType(); 3393 MVT SrcVT = Src.getSimpleValueType(); 3394 MVT SrcEltVT = SrcVT.getVectorElementType(); 3395 unsigned EltSize = EltVT.getSizeInBits(); 3396 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3397 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3398 "Unexpected vector element types"); 3399 3400 bool IsInt2FP = SrcEltVT.isInteger(); 3401 // Widening conversions 3402 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3403 if (IsInt2FP) { 3404 // Do a regular integer sign/zero extension then convert to float. 3405 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3406 VT.getVectorElementCount()); 3407 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3408 ? ISD::ZERO_EXTEND 3409 : ISD::SIGN_EXTEND; 3410 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3411 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3412 } 3413 // FP2Int 3414 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3415 // Do one doubling fp_extend then complete the operation by converting 3416 // to int. 3417 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3418 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3419 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3420 } 3421 3422 // Narrowing conversions 3423 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3424 if (IsInt2FP) { 3425 // One narrowing int_to_fp, then an fp_round. 3426 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3427 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3428 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3429 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3430 } 3431 // FP2Int 3432 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3433 // representable by the integer, the result is poison. 3434 MVT IVecVT = 3435 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3436 VT.getVectorElementCount()); 3437 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3438 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3439 } 3440 3441 // Scalable vectors can exit here. Patterns will handle equally-sized 3442 // conversions halving/doubling ones. 3443 if (!VT.isFixedLengthVector()) 3444 return Op; 3445 3446 // For fixed-length vectors we lower to a custom "VL" node. 3447 unsigned RVVOpc = 0; 3448 switch (Op.getOpcode()) { 3449 default: 3450 llvm_unreachable("Impossible opcode"); 3451 case ISD::FP_TO_SINT: 3452 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3453 break; 3454 case ISD::FP_TO_UINT: 3455 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3456 break; 3457 case ISD::SINT_TO_FP: 3458 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3459 break; 3460 case ISD::UINT_TO_FP: 3461 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3462 break; 3463 } 3464 3465 MVT ContainerVT, SrcContainerVT; 3466 // Derive the reference container type from the larger vector type. 3467 if (SrcEltSize > EltSize) { 3468 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3469 ContainerVT = 3470 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3471 } else { 3472 ContainerVT = getContainerForFixedLengthVector(VT); 3473 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3474 } 3475 3476 SDValue Mask, VL; 3477 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3478 3479 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3480 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3481 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3482 } 3483 case ISD::FP_TO_SINT_SAT: 3484 case ISD::FP_TO_UINT_SAT: 3485 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3486 case ISD::FTRUNC: 3487 case ISD::FCEIL: 3488 case ISD::FFLOOR: 3489 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3490 case ISD::FROUND: 3491 return lowerFROUND(Op, DAG); 3492 case ISD::VECREDUCE_ADD: 3493 case ISD::VECREDUCE_UMAX: 3494 case ISD::VECREDUCE_SMAX: 3495 case ISD::VECREDUCE_UMIN: 3496 case ISD::VECREDUCE_SMIN: 3497 return lowerVECREDUCE(Op, DAG); 3498 case ISD::VECREDUCE_AND: 3499 case ISD::VECREDUCE_OR: 3500 case ISD::VECREDUCE_XOR: 3501 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3502 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3503 return lowerVECREDUCE(Op, DAG); 3504 case ISD::VECREDUCE_FADD: 3505 case ISD::VECREDUCE_SEQ_FADD: 3506 case ISD::VECREDUCE_FMIN: 3507 case ISD::VECREDUCE_FMAX: 3508 return lowerFPVECREDUCE(Op, DAG); 3509 case ISD::VP_REDUCE_ADD: 3510 case ISD::VP_REDUCE_UMAX: 3511 case ISD::VP_REDUCE_SMAX: 3512 case ISD::VP_REDUCE_UMIN: 3513 case ISD::VP_REDUCE_SMIN: 3514 case ISD::VP_REDUCE_FADD: 3515 case ISD::VP_REDUCE_SEQ_FADD: 3516 case ISD::VP_REDUCE_FMIN: 3517 case ISD::VP_REDUCE_FMAX: 3518 return lowerVPREDUCE(Op, DAG); 3519 case ISD::VP_REDUCE_AND: 3520 case ISD::VP_REDUCE_OR: 3521 case ISD::VP_REDUCE_XOR: 3522 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3523 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3524 return lowerVPREDUCE(Op, DAG); 3525 case ISD::INSERT_SUBVECTOR: 3526 return lowerINSERT_SUBVECTOR(Op, DAG); 3527 case ISD::EXTRACT_SUBVECTOR: 3528 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3529 case ISD::STEP_VECTOR: 3530 return lowerSTEP_VECTOR(Op, DAG); 3531 case ISD::VECTOR_REVERSE: 3532 return lowerVECTOR_REVERSE(Op, DAG); 3533 case ISD::VECTOR_SPLICE: 3534 return lowerVECTOR_SPLICE(Op, DAG); 3535 case ISD::BUILD_VECTOR: 3536 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3537 case ISD::SPLAT_VECTOR: 3538 if (Op.getValueType().getVectorElementType() == MVT::i1) 3539 return lowerVectorMaskSplat(Op, DAG); 3540 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3541 case ISD::VECTOR_SHUFFLE: 3542 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3543 case ISD::CONCAT_VECTORS: { 3544 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3545 // better than going through the stack, as the default expansion does. 3546 SDLoc DL(Op); 3547 MVT VT = Op.getSimpleValueType(); 3548 unsigned NumOpElts = 3549 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3550 SDValue Vec = DAG.getUNDEF(VT); 3551 for (const auto &OpIdx : enumerate(Op->ops())) { 3552 SDValue SubVec = OpIdx.value(); 3553 // Don't insert undef subvectors. 3554 if (SubVec.isUndef()) 3555 continue; 3556 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3557 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3558 } 3559 return Vec; 3560 } 3561 case ISD::LOAD: 3562 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3563 return V; 3564 if (Op.getValueType().isFixedLengthVector()) 3565 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3566 return Op; 3567 case ISD::STORE: 3568 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3569 return V; 3570 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3571 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3572 return Op; 3573 case ISD::MLOAD: 3574 case ISD::VP_LOAD: 3575 return lowerMaskedLoad(Op, DAG); 3576 case ISD::MSTORE: 3577 case ISD::VP_STORE: 3578 return lowerMaskedStore(Op, DAG); 3579 case ISD::SETCC: 3580 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3581 case ISD::ADD: 3582 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3583 case ISD::SUB: 3584 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3585 case ISD::MUL: 3586 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3587 case ISD::MULHS: 3588 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3589 case ISD::MULHU: 3590 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3591 case ISD::AND: 3592 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3593 RISCVISD::AND_VL); 3594 case ISD::OR: 3595 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3596 RISCVISD::OR_VL); 3597 case ISD::XOR: 3598 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3599 RISCVISD::XOR_VL); 3600 case ISD::SDIV: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3602 case ISD::SREM: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3604 case ISD::UDIV: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3606 case ISD::UREM: 3607 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3608 case ISD::SHL: 3609 case ISD::SRA: 3610 case ISD::SRL: 3611 if (Op.getSimpleValueType().isFixedLengthVector()) 3612 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3613 // This can be called for an i32 shift amount that needs to be promoted. 3614 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3615 "Unexpected custom legalisation"); 3616 return SDValue(); 3617 case ISD::SADDSAT: 3618 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3619 case ISD::UADDSAT: 3620 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3621 case ISD::SSUBSAT: 3622 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3623 case ISD::USUBSAT: 3624 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3625 case ISD::FADD: 3626 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3627 case ISD::FSUB: 3628 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3629 case ISD::FMUL: 3630 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3631 case ISD::FDIV: 3632 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3633 case ISD::FNEG: 3634 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3635 case ISD::FABS: 3636 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3637 case ISD::FSQRT: 3638 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3639 case ISD::FMA: 3640 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3641 case ISD::SMIN: 3642 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3643 case ISD::SMAX: 3644 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3645 case ISD::UMIN: 3646 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3647 case ISD::UMAX: 3648 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3649 case ISD::FMINNUM: 3650 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3651 case ISD::FMAXNUM: 3652 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3653 case ISD::ABS: 3654 return lowerABS(Op, DAG); 3655 case ISD::CTLZ_ZERO_UNDEF: 3656 case ISD::CTTZ_ZERO_UNDEF: 3657 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3658 case ISD::VSELECT: 3659 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3660 case ISD::FCOPYSIGN: 3661 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3662 case ISD::MGATHER: 3663 case ISD::VP_GATHER: 3664 return lowerMaskedGather(Op, DAG); 3665 case ISD::MSCATTER: 3666 case ISD::VP_SCATTER: 3667 return lowerMaskedScatter(Op, DAG); 3668 case ISD::FLT_ROUNDS_: 3669 return lowerGET_ROUNDING(Op, DAG); 3670 case ISD::SET_ROUNDING: 3671 return lowerSET_ROUNDING(Op, DAG); 3672 case ISD::VP_SELECT: 3673 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3674 case ISD::VP_MERGE: 3675 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3676 case ISD::VP_ADD: 3677 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3678 case ISD::VP_SUB: 3679 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3680 case ISD::VP_MUL: 3681 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3682 case ISD::VP_SDIV: 3683 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3684 case ISD::VP_UDIV: 3685 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3686 case ISD::VP_SREM: 3687 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3688 case ISD::VP_UREM: 3689 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3690 case ISD::VP_AND: 3691 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3692 case ISD::VP_OR: 3693 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3694 case ISD::VP_XOR: 3695 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3696 case ISD::VP_ASHR: 3697 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3698 case ISD::VP_LSHR: 3699 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3700 case ISD::VP_SHL: 3701 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3702 case ISD::VP_FADD: 3703 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3704 case ISD::VP_FSUB: 3705 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3706 case ISD::VP_FMUL: 3707 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3708 case ISD::VP_FDIV: 3709 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3710 case ISD::VP_FNEG: 3711 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3712 case ISD::VP_FMA: 3713 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3714 } 3715 } 3716 3717 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3718 SelectionDAG &DAG, unsigned Flags) { 3719 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3720 } 3721 3722 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3723 SelectionDAG &DAG, unsigned Flags) { 3724 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3725 Flags); 3726 } 3727 3728 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3729 SelectionDAG &DAG, unsigned Flags) { 3730 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3731 N->getOffset(), Flags); 3732 } 3733 3734 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3735 SelectionDAG &DAG, unsigned Flags) { 3736 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3737 } 3738 3739 template <class NodeTy> 3740 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3741 bool IsLocal) const { 3742 SDLoc DL(N); 3743 EVT Ty = getPointerTy(DAG.getDataLayout()); 3744 3745 if (isPositionIndependent()) { 3746 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3747 if (IsLocal) 3748 // Use PC-relative addressing to access the symbol. This generates the 3749 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3750 // %pcrel_lo(auipc)). 3751 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3752 3753 // Use PC-relative addressing to access the GOT for this symbol, then load 3754 // the address from the GOT. This generates the pattern (PseudoLA sym), 3755 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3756 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3757 } 3758 3759 switch (getTargetMachine().getCodeModel()) { 3760 default: 3761 report_fatal_error("Unsupported code model for lowering"); 3762 case CodeModel::Small: { 3763 // Generate a sequence for accessing addresses within the first 2 GiB of 3764 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3765 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3766 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3767 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3768 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3769 } 3770 case CodeModel::Medium: { 3771 // Generate a sequence for accessing addresses within any 2GiB range within 3772 // the address space. This generates the pattern (PseudoLLA sym), which 3773 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3774 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3775 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3776 } 3777 } 3778 } 3779 3780 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3781 SelectionDAG &DAG) const { 3782 SDLoc DL(Op); 3783 EVT Ty = Op.getValueType(); 3784 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3785 int64_t Offset = N->getOffset(); 3786 MVT XLenVT = Subtarget.getXLenVT(); 3787 3788 const GlobalValue *GV = N->getGlobal(); 3789 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3790 SDValue Addr = getAddr(N, DAG, IsLocal); 3791 3792 // In order to maximise the opportunity for common subexpression elimination, 3793 // emit a separate ADD node for the global address offset instead of folding 3794 // it in the global address node. Later peephole optimisations may choose to 3795 // fold it back in when profitable. 3796 if (Offset != 0) 3797 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3798 DAG.getConstant(Offset, DL, XLenVT)); 3799 return Addr; 3800 } 3801 3802 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3803 SelectionDAG &DAG) const { 3804 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3805 3806 return getAddr(N, DAG); 3807 } 3808 3809 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3810 SelectionDAG &DAG) const { 3811 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3812 3813 return getAddr(N, DAG); 3814 } 3815 3816 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3817 SelectionDAG &DAG) const { 3818 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3819 3820 return getAddr(N, DAG); 3821 } 3822 3823 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3824 SelectionDAG &DAG, 3825 bool UseGOT) const { 3826 SDLoc DL(N); 3827 EVT Ty = getPointerTy(DAG.getDataLayout()); 3828 const GlobalValue *GV = N->getGlobal(); 3829 MVT XLenVT = Subtarget.getXLenVT(); 3830 3831 if (UseGOT) { 3832 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3833 // load the address from the GOT and add the thread pointer. This generates 3834 // the pattern (PseudoLA_TLS_IE sym), which expands to 3835 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3836 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3837 SDValue Load = 3838 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3839 3840 // Add the thread pointer. 3841 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3842 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3843 } 3844 3845 // Generate a sequence for accessing the address relative to the thread 3846 // pointer, with the appropriate adjustment for the thread pointer offset. 3847 // This generates the pattern 3848 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3849 SDValue AddrHi = 3850 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3851 SDValue AddrAdd = 3852 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3853 SDValue AddrLo = 3854 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3855 3856 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3857 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3858 SDValue MNAdd = SDValue( 3859 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3860 0); 3861 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3862 } 3863 3864 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3865 SelectionDAG &DAG) const { 3866 SDLoc DL(N); 3867 EVT Ty = getPointerTy(DAG.getDataLayout()); 3868 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3869 const GlobalValue *GV = N->getGlobal(); 3870 3871 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3872 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3873 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3874 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3875 SDValue Load = 3876 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3877 3878 // Prepare argument list to generate call. 3879 ArgListTy Args; 3880 ArgListEntry Entry; 3881 Entry.Node = Load; 3882 Entry.Ty = CallTy; 3883 Args.push_back(Entry); 3884 3885 // Setup call to __tls_get_addr. 3886 TargetLowering::CallLoweringInfo CLI(DAG); 3887 CLI.setDebugLoc(DL) 3888 .setChain(DAG.getEntryNode()) 3889 .setLibCallee(CallingConv::C, CallTy, 3890 DAG.getExternalSymbol("__tls_get_addr", Ty), 3891 std::move(Args)); 3892 3893 return LowerCallTo(CLI).first; 3894 } 3895 3896 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3897 SelectionDAG &DAG) const { 3898 SDLoc DL(Op); 3899 EVT Ty = Op.getValueType(); 3900 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3901 int64_t Offset = N->getOffset(); 3902 MVT XLenVT = Subtarget.getXLenVT(); 3903 3904 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3905 3906 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3907 CallingConv::GHC) 3908 report_fatal_error("In GHC calling convention TLS is not supported"); 3909 3910 SDValue Addr; 3911 switch (Model) { 3912 case TLSModel::LocalExec: 3913 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3914 break; 3915 case TLSModel::InitialExec: 3916 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3917 break; 3918 case TLSModel::LocalDynamic: 3919 case TLSModel::GeneralDynamic: 3920 Addr = getDynamicTLSAddr(N, DAG); 3921 break; 3922 } 3923 3924 // In order to maximise the opportunity for common subexpression elimination, 3925 // emit a separate ADD node for the global address offset instead of folding 3926 // it in the global address node. Later peephole optimisations may choose to 3927 // fold it back in when profitable. 3928 if (Offset != 0) 3929 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3930 DAG.getConstant(Offset, DL, XLenVT)); 3931 return Addr; 3932 } 3933 3934 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3935 SDValue CondV = Op.getOperand(0); 3936 SDValue TrueV = Op.getOperand(1); 3937 SDValue FalseV = Op.getOperand(2); 3938 SDLoc DL(Op); 3939 MVT VT = Op.getSimpleValueType(); 3940 MVT XLenVT = Subtarget.getXLenVT(); 3941 3942 // Lower vector SELECTs to VSELECTs by splatting the condition. 3943 if (VT.isVector()) { 3944 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3945 SDValue CondSplat = VT.isScalableVector() 3946 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3947 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3948 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3949 } 3950 3951 // If the result type is XLenVT and CondV is the output of a SETCC node 3952 // which also operated on XLenVT inputs, then merge the SETCC node into the 3953 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3954 // compare+branch instructions. i.e.: 3955 // (select (setcc lhs, rhs, cc), truev, falsev) 3956 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3957 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3958 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3959 SDValue LHS = CondV.getOperand(0); 3960 SDValue RHS = CondV.getOperand(1); 3961 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3962 ISD::CondCode CCVal = CC->get(); 3963 3964 // Special case for a select of 2 constants that have a diffence of 1. 3965 // Normally this is done by DAGCombine, but if the select is introduced by 3966 // type legalization or op legalization, we miss it. Restricting to SETLT 3967 // case for now because that is what signed saturating add/sub need. 3968 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3969 // but we would probably want to swap the true/false values if the condition 3970 // is SETGE/SETLE to avoid an XORI. 3971 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3972 CCVal == ISD::SETLT) { 3973 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3974 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3975 if (TrueVal - 1 == FalseVal) 3976 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3977 if (TrueVal + 1 == FalseVal) 3978 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3979 } 3980 3981 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3982 3983 SDValue TargetCC = DAG.getCondCode(CCVal); 3984 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3985 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3986 } 3987 3988 // Otherwise: 3989 // (select condv, truev, falsev) 3990 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3991 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3992 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3993 3994 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3995 3996 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3997 } 3998 3999 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4000 SDValue CondV = Op.getOperand(1); 4001 SDLoc DL(Op); 4002 MVT XLenVT = Subtarget.getXLenVT(); 4003 4004 if (CondV.getOpcode() == ISD::SETCC && 4005 CondV.getOperand(0).getValueType() == XLenVT) { 4006 SDValue LHS = CondV.getOperand(0); 4007 SDValue RHS = CondV.getOperand(1); 4008 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 4009 4010 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4011 4012 SDValue TargetCC = DAG.getCondCode(CCVal); 4013 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4014 LHS, RHS, TargetCC, Op.getOperand(2)); 4015 } 4016 4017 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 4018 CondV, DAG.getConstant(0, DL, XLenVT), 4019 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4020 } 4021 4022 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4023 MachineFunction &MF = DAG.getMachineFunction(); 4024 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4025 4026 SDLoc DL(Op); 4027 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4028 getPointerTy(MF.getDataLayout())); 4029 4030 // vastart just stores the address of the VarArgsFrameIndex slot into the 4031 // memory location argument. 4032 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4033 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4034 MachinePointerInfo(SV)); 4035 } 4036 4037 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4038 SelectionDAG &DAG) const { 4039 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4040 MachineFunction &MF = DAG.getMachineFunction(); 4041 MachineFrameInfo &MFI = MF.getFrameInfo(); 4042 MFI.setFrameAddressIsTaken(true); 4043 Register FrameReg = RI.getFrameRegister(MF); 4044 int XLenInBytes = Subtarget.getXLen() / 8; 4045 4046 EVT VT = Op.getValueType(); 4047 SDLoc DL(Op); 4048 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4049 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4050 while (Depth--) { 4051 int Offset = -(XLenInBytes * 2); 4052 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4053 DAG.getIntPtrConstant(Offset, DL)); 4054 FrameAddr = 4055 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4056 } 4057 return FrameAddr; 4058 } 4059 4060 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4061 SelectionDAG &DAG) const { 4062 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4063 MachineFunction &MF = DAG.getMachineFunction(); 4064 MachineFrameInfo &MFI = MF.getFrameInfo(); 4065 MFI.setReturnAddressIsTaken(true); 4066 MVT XLenVT = Subtarget.getXLenVT(); 4067 int XLenInBytes = Subtarget.getXLen() / 8; 4068 4069 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4070 return SDValue(); 4071 4072 EVT VT = Op.getValueType(); 4073 SDLoc DL(Op); 4074 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4075 if (Depth) { 4076 int Off = -XLenInBytes; 4077 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4078 SDValue Offset = DAG.getConstant(Off, DL, VT); 4079 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4080 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4081 MachinePointerInfo()); 4082 } 4083 4084 // Return the value of the return address register, marking it an implicit 4085 // live-in. 4086 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4087 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4088 } 4089 4090 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4091 SelectionDAG &DAG) const { 4092 SDLoc DL(Op); 4093 SDValue Lo = Op.getOperand(0); 4094 SDValue Hi = Op.getOperand(1); 4095 SDValue Shamt = Op.getOperand(2); 4096 EVT VT = Lo.getValueType(); 4097 4098 // if Shamt-XLEN < 0: // Shamt < XLEN 4099 // Lo = Lo << Shamt 4100 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4101 // else: 4102 // Lo = 0 4103 // Hi = Lo << (Shamt-XLEN) 4104 4105 SDValue Zero = DAG.getConstant(0, DL, VT); 4106 SDValue One = DAG.getConstant(1, DL, VT); 4107 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4108 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4109 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4110 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4111 4112 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4113 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4114 SDValue ShiftRightLo = 4115 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4116 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4117 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4118 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4119 4120 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4121 4122 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4123 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4124 4125 SDValue Parts[2] = {Lo, Hi}; 4126 return DAG.getMergeValues(Parts, DL); 4127 } 4128 4129 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4130 bool IsSRA) const { 4131 SDLoc DL(Op); 4132 SDValue Lo = Op.getOperand(0); 4133 SDValue Hi = Op.getOperand(1); 4134 SDValue Shamt = Op.getOperand(2); 4135 EVT VT = Lo.getValueType(); 4136 4137 // SRA expansion: 4138 // if Shamt-XLEN < 0: // Shamt < XLEN 4139 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4140 // Hi = Hi >>s Shamt 4141 // else: 4142 // Lo = Hi >>s (Shamt-XLEN); 4143 // Hi = Hi >>s (XLEN-1) 4144 // 4145 // SRL expansion: 4146 // if Shamt-XLEN < 0: // Shamt < XLEN 4147 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4148 // Hi = Hi >>u Shamt 4149 // else: 4150 // Lo = Hi >>u (Shamt-XLEN); 4151 // Hi = 0; 4152 4153 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4154 4155 SDValue Zero = DAG.getConstant(0, DL, VT); 4156 SDValue One = DAG.getConstant(1, DL, VT); 4157 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4158 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4159 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4160 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4161 4162 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4163 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4164 SDValue ShiftLeftHi = 4165 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4166 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4167 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4168 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4169 SDValue HiFalse = 4170 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4171 4172 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4173 4174 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4175 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4176 4177 SDValue Parts[2] = {Lo, Hi}; 4178 return DAG.getMergeValues(Parts, DL); 4179 } 4180 4181 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4182 // legal equivalently-sized i8 type, so we can use that as a go-between. 4183 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4184 SelectionDAG &DAG) const { 4185 SDLoc DL(Op); 4186 MVT VT = Op.getSimpleValueType(); 4187 SDValue SplatVal = Op.getOperand(0); 4188 // All-zeros or all-ones splats are handled specially. 4189 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4190 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4191 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4192 } 4193 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4194 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4195 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4196 } 4197 MVT XLenVT = Subtarget.getXLenVT(); 4198 assert(SplatVal.getValueType() == XLenVT && 4199 "Unexpected type for i1 splat value"); 4200 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4201 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4202 DAG.getConstant(1, DL, XLenVT)); 4203 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4204 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4205 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4206 } 4207 4208 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4209 // illegal (currently only vXi64 RV32). 4210 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4211 // them to VMV_V_X_VL. 4212 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4213 SelectionDAG &DAG) const { 4214 SDLoc DL(Op); 4215 MVT VecVT = Op.getSimpleValueType(); 4216 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4217 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4218 4219 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4220 SDValue Lo = Op.getOperand(0); 4221 SDValue Hi = Op.getOperand(1); 4222 4223 if (VecVT.isFixedLengthVector()) { 4224 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4225 SDLoc DL(Op); 4226 SDValue Mask, VL; 4227 std::tie(Mask, VL) = 4228 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4229 4230 SDValue Res = 4231 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4232 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4233 } 4234 4235 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4236 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4237 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4238 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4239 // node in order to try and match RVV vector/scalar instructions. 4240 if ((LoC >> 31) == HiC) 4241 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4242 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4243 } 4244 4245 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4246 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4247 isa<ConstantSDNode>(Hi.getOperand(1)) && 4248 Hi.getConstantOperandVal(1) == 31) 4249 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4250 DAG.getRegister(RISCV::X0, MVT::i32)); 4251 4252 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4253 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4254 DAG.getUNDEF(VecVT), Lo, Hi, 4255 DAG.getRegister(RISCV::X0, MVT::i32)); 4256 } 4257 4258 // Custom-lower extensions from mask vectors by using a vselect either with 1 4259 // for zero/any-extension or -1 for sign-extension: 4260 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4261 // Note that any-extension is lowered identically to zero-extension. 4262 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4263 int64_t ExtTrueVal) const { 4264 SDLoc DL(Op); 4265 MVT VecVT = Op.getSimpleValueType(); 4266 SDValue Src = Op.getOperand(0); 4267 // Only custom-lower extensions from mask types 4268 assert(Src.getValueType().isVector() && 4269 Src.getValueType().getVectorElementType() == MVT::i1); 4270 4271 MVT XLenVT = Subtarget.getXLenVT(); 4272 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4273 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4274 4275 if (VecVT.isScalableVector()) { 4276 // Be careful not to introduce illegal scalar types at this stage, and be 4277 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4278 // illegal and must be expanded. Since we know that the constants are 4279 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4280 bool IsRV32E64 = 4281 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4282 4283 if (!IsRV32E64) { 4284 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4285 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4286 } else { 4287 SplatZero = 4288 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4289 SplatZero, DAG.getRegister(RISCV::X0, XLenVT)); 4290 SplatTrueVal = 4291 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4292 SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT)); 4293 } 4294 4295 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4296 } 4297 4298 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4299 MVT I1ContainerVT = 4300 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4301 4302 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4303 4304 SDValue Mask, VL; 4305 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4306 4307 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4308 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4309 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4310 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4311 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4312 SplatTrueVal, SplatZero, VL); 4313 4314 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4315 } 4316 4317 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4318 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4319 MVT ExtVT = Op.getSimpleValueType(); 4320 // Only custom-lower extensions from fixed-length vector types. 4321 if (!ExtVT.isFixedLengthVector()) 4322 return Op; 4323 MVT VT = Op.getOperand(0).getSimpleValueType(); 4324 // Grab the canonical container type for the extended type. Infer the smaller 4325 // type from that to ensure the same number of vector elements, as we know 4326 // the LMUL will be sufficient to hold the smaller type. 4327 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4328 // Get the extended container type manually to ensure the same number of 4329 // vector elements between source and dest. 4330 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4331 ContainerExtVT.getVectorElementCount()); 4332 4333 SDValue Op1 = 4334 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4335 4336 SDLoc DL(Op); 4337 SDValue Mask, VL; 4338 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4339 4340 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4341 4342 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4343 } 4344 4345 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4346 // setcc operation: 4347 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4348 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4349 SelectionDAG &DAG) const { 4350 SDLoc DL(Op); 4351 EVT MaskVT = Op.getValueType(); 4352 // Only expect to custom-lower truncations to mask types 4353 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4354 "Unexpected type for vector mask lowering"); 4355 SDValue Src = Op.getOperand(0); 4356 MVT VecVT = Src.getSimpleValueType(); 4357 4358 // If this is a fixed vector, we need to convert it to a scalable vector. 4359 MVT ContainerVT = VecVT; 4360 if (VecVT.isFixedLengthVector()) { 4361 ContainerVT = getContainerForFixedLengthVector(VecVT); 4362 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4363 } 4364 4365 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4366 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4367 4368 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4369 DAG.getUNDEF(ContainerVT), SplatOne); 4370 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4371 DAG.getUNDEF(ContainerVT), SplatZero); 4372 4373 if (VecVT.isScalableVector()) { 4374 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4375 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4376 } 4377 4378 SDValue Mask, VL; 4379 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4380 4381 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4382 SDValue Trunc = 4383 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4384 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4385 DAG.getCondCode(ISD::SETNE), Mask, VL); 4386 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4387 } 4388 4389 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4390 // first position of a vector, and that vector is slid up to the insert index. 4391 // By limiting the active vector length to index+1 and merging with the 4392 // original vector (with an undisturbed tail policy for elements >= VL), we 4393 // achieve the desired result of leaving all elements untouched except the one 4394 // at VL-1, which is replaced with the desired value. 4395 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4396 SelectionDAG &DAG) const { 4397 SDLoc DL(Op); 4398 MVT VecVT = Op.getSimpleValueType(); 4399 SDValue Vec = Op.getOperand(0); 4400 SDValue Val = Op.getOperand(1); 4401 SDValue Idx = Op.getOperand(2); 4402 4403 if (VecVT.getVectorElementType() == MVT::i1) { 4404 // FIXME: For now we just promote to an i8 vector and insert into that, 4405 // but this is probably not optimal. 4406 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4407 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4408 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4409 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4410 } 4411 4412 MVT ContainerVT = VecVT; 4413 // If the operand is a fixed-length vector, convert to a scalable one. 4414 if (VecVT.isFixedLengthVector()) { 4415 ContainerVT = getContainerForFixedLengthVector(VecVT); 4416 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4417 } 4418 4419 MVT XLenVT = Subtarget.getXLenVT(); 4420 4421 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4422 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4423 // Even i64-element vectors on RV32 can be lowered without scalar 4424 // legalization if the most-significant 32 bits of the value are not affected 4425 // by the sign-extension of the lower 32 bits. 4426 // TODO: We could also catch sign extensions of a 32-bit value. 4427 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4428 const auto *CVal = cast<ConstantSDNode>(Val); 4429 if (isInt<32>(CVal->getSExtValue())) { 4430 IsLegalInsert = true; 4431 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4432 } 4433 } 4434 4435 SDValue Mask, VL; 4436 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4437 4438 SDValue ValInVec; 4439 4440 if (IsLegalInsert) { 4441 unsigned Opc = 4442 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4443 if (isNullConstant(Idx)) { 4444 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4445 if (!VecVT.isFixedLengthVector()) 4446 return Vec; 4447 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4448 } 4449 ValInVec = 4450 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4451 } else { 4452 // On RV32, i64-element vectors must be specially handled to place the 4453 // value at element 0, by using two vslide1up instructions in sequence on 4454 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4455 // this. 4456 SDValue One = DAG.getConstant(1, DL, XLenVT); 4457 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4458 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4459 MVT I32ContainerVT = 4460 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4461 SDValue I32Mask = 4462 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4463 // Limit the active VL to two. 4464 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4465 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4466 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4467 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4468 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4469 // First slide in the hi value, then the lo in underneath it. 4470 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4471 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4472 I32Mask, InsertI64VL); 4473 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4474 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4475 I32Mask, InsertI64VL); 4476 // Bitcast back to the right container type. 4477 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4478 } 4479 4480 // Now that the value is in a vector, slide it into position. 4481 SDValue InsertVL = 4482 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4483 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4484 ValInVec, Idx, Mask, InsertVL); 4485 if (!VecVT.isFixedLengthVector()) 4486 return Slideup; 4487 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4488 } 4489 4490 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4491 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4492 // types this is done using VMV_X_S to allow us to glean information about the 4493 // sign bits of the result. 4494 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4495 SelectionDAG &DAG) const { 4496 SDLoc DL(Op); 4497 SDValue Idx = Op.getOperand(1); 4498 SDValue Vec = Op.getOperand(0); 4499 EVT EltVT = Op.getValueType(); 4500 MVT VecVT = Vec.getSimpleValueType(); 4501 MVT XLenVT = Subtarget.getXLenVT(); 4502 4503 if (VecVT.getVectorElementType() == MVT::i1) { 4504 if (VecVT.isFixedLengthVector()) { 4505 unsigned NumElts = VecVT.getVectorNumElements(); 4506 if (NumElts >= 8) { 4507 MVT WideEltVT; 4508 unsigned WidenVecLen; 4509 SDValue ExtractElementIdx; 4510 SDValue ExtractBitIdx; 4511 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4512 MVT LargestEltVT = MVT::getIntegerVT( 4513 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4514 if (NumElts <= LargestEltVT.getSizeInBits()) { 4515 assert(isPowerOf2_32(NumElts) && 4516 "the number of elements should be power of 2"); 4517 WideEltVT = MVT::getIntegerVT(NumElts); 4518 WidenVecLen = 1; 4519 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4520 ExtractBitIdx = Idx; 4521 } else { 4522 WideEltVT = LargestEltVT; 4523 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4524 // extract element index = index / element width 4525 ExtractElementIdx = DAG.getNode( 4526 ISD::SRL, DL, XLenVT, Idx, 4527 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4528 // mask bit index = index % element width 4529 ExtractBitIdx = DAG.getNode( 4530 ISD::AND, DL, XLenVT, Idx, 4531 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4532 } 4533 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4534 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4535 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4536 Vec, ExtractElementIdx); 4537 // Extract the bit from GPR. 4538 SDValue ShiftRight = 4539 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4540 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4541 DAG.getConstant(1, DL, XLenVT)); 4542 } 4543 } 4544 // Otherwise, promote to an i8 vector and extract from that. 4545 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4546 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4547 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4548 } 4549 4550 // If this is a fixed vector, we need to convert it to a scalable vector. 4551 MVT ContainerVT = VecVT; 4552 if (VecVT.isFixedLengthVector()) { 4553 ContainerVT = getContainerForFixedLengthVector(VecVT); 4554 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4555 } 4556 4557 // If the index is 0, the vector is already in the right position. 4558 if (!isNullConstant(Idx)) { 4559 // Use a VL of 1 to avoid processing more elements than we need. 4560 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4561 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4562 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4563 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4564 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4565 } 4566 4567 if (!EltVT.isInteger()) { 4568 // Floating-point extracts are handled in TableGen. 4569 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4570 DAG.getConstant(0, DL, XLenVT)); 4571 } 4572 4573 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4574 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4575 } 4576 4577 // Some RVV intrinsics may claim that they want an integer operand to be 4578 // promoted or expanded. 4579 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4580 const RISCVSubtarget &Subtarget) { 4581 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4582 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4583 "Unexpected opcode"); 4584 4585 if (!Subtarget.hasVInstructions()) 4586 return SDValue(); 4587 4588 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4589 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4590 SDLoc DL(Op); 4591 4592 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4593 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4594 if (!II || !II->hasScalarOperand()) 4595 return SDValue(); 4596 4597 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4598 assert(SplatOp < Op.getNumOperands()); 4599 4600 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4601 SDValue &ScalarOp = Operands[SplatOp]; 4602 MVT OpVT = ScalarOp.getSimpleValueType(); 4603 MVT XLenVT = Subtarget.getXLenVT(); 4604 4605 // If this isn't a scalar, or its type is XLenVT we're done. 4606 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4607 return SDValue(); 4608 4609 // Simplest case is that the operand needs to be promoted to XLenVT. 4610 if (OpVT.bitsLT(XLenVT)) { 4611 // If the operand is a constant, sign extend to increase our chances 4612 // of being able to use a .vi instruction. ANY_EXTEND would become a 4613 // a zero extend and the simm5 check in isel would fail. 4614 // FIXME: Should we ignore the upper bits in isel instead? 4615 unsigned ExtOpc = 4616 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4617 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4618 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4619 } 4620 4621 // Use the previous operand to get the vXi64 VT. The result might be a mask 4622 // VT for compares. Using the previous operand assumes that the previous 4623 // operand will never have a smaller element size than a scalar operand and 4624 // that a widening operation never uses SEW=64. 4625 // NOTE: If this fails the below assert, we can probably just find the 4626 // element count from any operand or result and use it to construct the VT. 4627 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4628 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4629 4630 // The more complex case is when the scalar is larger than XLenVT. 4631 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4632 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4633 4634 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4635 // on the instruction to sign-extend since SEW>XLEN. 4636 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4637 if (isInt<32>(CVal->getSExtValue())) { 4638 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4639 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4640 } 4641 } 4642 4643 switch (IntNo) { 4644 case Intrinsic::riscv_vslide1up: 4645 case Intrinsic::riscv_vslide1down: 4646 case Intrinsic::riscv_vslide1up_mask: 4647 case Intrinsic::riscv_vslide1down_mask: { 4648 // We need to special case these when the scalar is larger than XLen. 4649 unsigned NumOps = Op.getNumOperands(); 4650 bool IsMasked = NumOps == 7; 4651 4652 // Convert the vector source to the equivalent nxvXi32 vector. 4653 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4654 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4655 4656 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4657 DAG.getConstant(0, DL, XLenVT)); 4658 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4659 DAG.getConstant(1, DL, XLenVT)); 4660 4661 // Double the VL since we halved SEW. 4662 SDValue AVL = getVLOperand(Op); 4663 SDValue I32VL; 4664 4665 // Optimize for constant AVL 4666 if (isa<ConstantSDNode>(AVL)) { 4667 unsigned EltSize = VT.getScalarSizeInBits(); 4668 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4669 4670 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4671 unsigned MaxVLMAX = 4672 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4673 4674 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4675 unsigned MinVLMAX = 4676 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4677 4678 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4679 if (AVLInt <= MinVLMAX) { 4680 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4681 } else if (AVLInt >= 2 * MaxVLMAX) { 4682 // Just set vl to VLMAX in this situation 4683 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4684 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4685 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4686 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4687 SDValue SETVLMAX = DAG.getTargetConstant( 4688 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4689 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4690 LMUL); 4691 } else { 4692 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4693 // is related to the hardware implementation. 4694 // So let the following code handle 4695 } 4696 } 4697 if (!I32VL) { 4698 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4699 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4700 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4701 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4702 SDValue SETVL = 4703 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4704 // Using vsetvli instruction to get actually used length which related to 4705 // the hardware implementation 4706 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4707 SEW, LMUL); 4708 I32VL = 4709 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4710 } 4711 4712 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4713 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL); 4714 4715 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4716 // instructions. 4717 SDValue Passthru; 4718 if (IsMasked) 4719 Passthru = DAG.getUNDEF(I32VT); 4720 else 4721 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4722 4723 if (IntNo == Intrinsic::riscv_vslide1up || 4724 IntNo == Intrinsic::riscv_vslide1up_mask) { 4725 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4726 ScalarHi, I32Mask, I32VL); 4727 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4728 ScalarLo, I32Mask, I32VL); 4729 } else { 4730 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4731 ScalarLo, I32Mask, I32VL); 4732 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4733 ScalarHi, I32Mask, I32VL); 4734 } 4735 4736 // Convert back to nxvXi64. 4737 Vec = DAG.getBitcast(VT, Vec); 4738 4739 if (!IsMasked) 4740 return Vec; 4741 // Apply mask after the operation. 4742 SDValue Mask = Operands[NumOps - 3]; 4743 SDValue MaskedOff = Operands[1]; 4744 // Assume Policy operand is the last operand. 4745 uint64_t Policy = 4746 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4747 // We don't need to select maskedoff if it's undef. 4748 if (MaskedOff.isUndef()) 4749 return Vec; 4750 // TAMU 4751 if (Policy == RISCVII::TAIL_AGNOSTIC) 4752 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4753 AVL); 4754 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4755 // It's fine because vmerge does not care mask policy. 4756 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4757 AVL); 4758 } 4759 } 4760 4761 // We need to convert the scalar to a splat vector. 4762 // FIXME: Can we implicitly truncate the scalar if it is known to 4763 // be sign extended? 4764 SDValue VL = getVLOperand(Op); 4765 assert(VL.getValueType() == XLenVT); 4766 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4767 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4768 } 4769 4770 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4771 SelectionDAG &DAG) const { 4772 unsigned IntNo = Op.getConstantOperandVal(0); 4773 SDLoc DL(Op); 4774 MVT XLenVT = Subtarget.getXLenVT(); 4775 4776 switch (IntNo) { 4777 default: 4778 break; // Don't custom lower most intrinsics. 4779 case Intrinsic::thread_pointer: { 4780 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4781 return DAG.getRegister(RISCV::X4, PtrVT); 4782 } 4783 case Intrinsic::riscv_orc_b: 4784 case Intrinsic::riscv_brev8: { 4785 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4786 unsigned Opc = 4787 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4788 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4789 DAG.getConstant(7, DL, XLenVT)); 4790 } 4791 case Intrinsic::riscv_grev: 4792 case Intrinsic::riscv_gorc: { 4793 unsigned Opc = 4794 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4795 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4796 } 4797 case Intrinsic::riscv_zip: 4798 case Intrinsic::riscv_unzip: { 4799 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4800 // For i32 the immediate is 15. For i64 the immediate is 31. 4801 unsigned Opc = 4802 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4803 unsigned BitWidth = Op.getValueSizeInBits(); 4804 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4805 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4806 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4807 } 4808 case Intrinsic::riscv_shfl: 4809 case Intrinsic::riscv_unshfl: { 4810 unsigned Opc = 4811 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4812 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4813 } 4814 case Intrinsic::riscv_bcompress: 4815 case Intrinsic::riscv_bdecompress: { 4816 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4817 : RISCVISD::BDECOMPRESS; 4818 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4819 } 4820 case Intrinsic::riscv_bfp: 4821 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4822 Op.getOperand(2)); 4823 case Intrinsic::riscv_fsl: 4824 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4825 Op.getOperand(2), Op.getOperand(3)); 4826 case Intrinsic::riscv_fsr: 4827 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4828 Op.getOperand(2), Op.getOperand(3)); 4829 case Intrinsic::riscv_vmv_x_s: 4830 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4831 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4832 Op.getOperand(1)); 4833 case Intrinsic::riscv_vmv_v_x: 4834 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4835 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4836 Subtarget); 4837 case Intrinsic::riscv_vfmv_v_f: 4838 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4839 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4840 case Intrinsic::riscv_vmv_s_x: { 4841 SDValue Scalar = Op.getOperand(2); 4842 4843 if (Scalar.getValueType().bitsLE(XLenVT)) { 4844 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4845 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4846 Op.getOperand(1), Scalar, Op.getOperand(3)); 4847 } 4848 4849 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4850 4851 // This is an i64 value that lives in two scalar registers. We have to 4852 // insert this in a convoluted way. First we build vXi64 splat containing 4853 // the/ two values that we assemble using some bit math. Next we'll use 4854 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4855 // to merge element 0 from our splat into the source vector. 4856 // FIXME: This is probably not the best way to do this, but it is 4857 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4858 // point. 4859 // sw lo, (a0) 4860 // sw hi, 4(a0) 4861 // vlse vX, (a0) 4862 // 4863 // vid.v vVid 4864 // vmseq.vx mMask, vVid, 0 4865 // vmerge.vvm vDest, vSrc, vVal, mMask 4866 MVT VT = Op.getSimpleValueType(); 4867 SDValue Vec = Op.getOperand(1); 4868 SDValue VL = getVLOperand(Op); 4869 4870 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4871 if (Op.getOperand(1).isUndef()) 4872 return SplattedVal; 4873 SDValue SplattedIdx = 4874 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4875 DAG.getConstant(0, DL, MVT::i32), VL); 4876 4877 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4878 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4879 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4880 SDValue SelectCond = 4881 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4882 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4883 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4884 Vec, VL); 4885 } 4886 } 4887 4888 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4889 } 4890 4891 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4892 SelectionDAG &DAG) const { 4893 unsigned IntNo = Op.getConstantOperandVal(1); 4894 switch (IntNo) { 4895 default: 4896 break; 4897 case Intrinsic::riscv_masked_strided_load: { 4898 SDLoc DL(Op); 4899 MVT XLenVT = Subtarget.getXLenVT(); 4900 4901 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4902 // the selection of the masked intrinsics doesn't do this for us. 4903 SDValue Mask = Op.getOperand(5); 4904 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4905 4906 MVT VT = Op->getSimpleValueType(0); 4907 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4908 4909 SDValue PassThru = Op.getOperand(2); 4910 if (!IsUnmasked) { 4911 MVT MaskVT = 4912 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4913 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4914 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4915 } 4916 4917 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4918 4919 SDValue IntID = DAG.getTargetConstant( 4920 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4921 XLenVT); 4922 4923 auto *Load = cast<MemIntrinsicSDNode>(Op); 4924 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4925 if (IsUnmasked) 4926 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4927 else 4928 Ops.push_back(PassThru); 4929 Ops.push_back(Op.getOperand(3)); // Ptr 4930 Ops.push_back(Op.getOperand(4)); // Stride 4931 if (!IsUnmasked) 4932 Ops.push_back(Mask); 4933 Ops.push_back(VL); 4934 if (!IsUnmasked) { 4935 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4936 Ops.push_back(Policy); 4937 } 4938 4939 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4940 SDValue Result = 4941 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4942 Load->getMemoryVT(), Load->getMemOperand()); 4943 SDValue Chain = Result.getValue(1); 4944 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4945 return DAG.getMergeValues({Result, Chain}, DL); 4946 } 4947 case Intrinsic::riscv_seg2_load: 4948 case Intrinsic::riscv_seg3_load: 4949 case Intrinsic::riscv_seg4_load: 4950 case Intrinsic::riscv_seg5_load: 4951 case Intrinsic::riscv_seg6_load: 4952 case Intrinsic::riscv_seg7_load: 4953 case Intrinsic::riscv_seg8_load: { 4954 SDLoc DL(Op); 4955 static const Intrinsic::ID VlsegInts[7] = { 4956 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4957 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4958 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4959 Intrinsic::riscv_vlseg8}; 4960 unsigned NF = Op->getNumValues() - 1; 4961 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4962 MVT XLenVT = Subtarget.getXLenVT(); 4963 MVT VT = Op->getSimpleValueType(0); 4964 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4965 4966 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4967 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4968 auto *Load = cast<MemIntrinsicSDNode>(Op); 4969 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4970 ContainerVTs.push_back(MVT::Other); 4971 SDVTList VTs = DAG.getVTList(ContainerVTs); 4972 SDValue Result = 4973 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4974 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4975 Load->getMemoryVT(), Load->getMemOperand()); 4976 SmallVector<SDValue, 9> Results; 4977 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4978 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4979 DAG, Subtarget)); 4980 Results.push_back(Result.getValue(NF)); 4981 return DAG.getMergeValues(Results, DL); 4982 } 4983 } 4984 4985 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4986 } 4987 4988 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4989 SelectionDAG &DAG) const { 4990 unsigned IntNo = Op.getConstantOperandVal(1); 4991 switch (IntNo) { 4992 default: 4993 break; 4994 case Intrinsic::riscv_masked_strided_store: { 4995 SDLoc DL(Op); 4996 MVT XLenVT = Subtarget.getXLenVT(); 4997 4998 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4999 // the selection of the masked intrinsics doesn't do this for us. 5000 SDValue Mask = Op.getOperand(5); 5001 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5002 5003 SDValue Val = Op.getOperand(2); 5004 MVT VT = Val.getSimpleValueType(); 5005 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5006 5007 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5008 if (!IsUnmasked) { 5009 MVT MaskVT = 5010 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5011 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5012 } 5013 5014 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5015 5016 SDValue IntID = DAG.getTargetConstant( 5017 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5018 XLenVT); 5019 5020 auto *Store = cast<MemIntrinsicSDNode>(Op); 5021 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5022 Ops.push_back(Val); 5023 Ops.push_back(Op.getOperand(3)); // Ptr 5024 Ops.push_back(Op.getOperand(4)); // Stride 5025 if (!IsUnmasked) 5026 Ops.push_back(Mask); 5027 Ops.push_back(VL); 5028 5029 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5030 Ops, Store->getMemoryVT(), 5031 Store->getMemOperand()); 5032 } 5033 } 5034 5035 return SDValue(); 5036 } 5037 5038 static MVT getLMUL1VT(MVT VT) { 5039 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5040 "Unexpected vector MVT"); 5041 return MVT::getScalableVectorVT( 5042 VT.getVectorElementType(), 5043 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5044 } 5045 5046 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5047 switch (ISDOpcode) { 5048 default: 5049 llvm_unreachable("Unhandled reduction"); 5050 case ISD::VECREDUCE_ADD: 5051 return RISCVISD::VECREDUCE_ADD_VL; 5052 case ISD::VECREDUCE_UMAX: 5053 return RISCVISD::VECREDUCE_UMAX_VL; 5054 case ISD::VECREDUCE_SMAX: 5055 return RISCVISD::VECREDUCE_SMAX_VL; 5056 case ISD::VECREDUCE_UMIN: 5057 return RISCVISD::VECREDUCE_UMIN_VL; 5058 case ISD::VECREDUCE_SMIN: 5059 return RISCVISD::VECREDUCE_SMIN_VL; 5060 case ISD::VECREDUCE_AND: 5061 return RISCVISD::VECREDUCE_AND_VL; 5062 case ISD::VECREDUCE_OR: 5063 return RISCVISD::VECREDUCE_OR_VL; 5064 case ISD::VECREDUCE_XOR: 5065 return RISCVISD::VECREDUCE_XOR_VL; 5066 } 5067 } 5068 5069 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5070 SelectionDAG &DAG, 5071 bool IsVP) const { 5072 SDLoc DL(Op); 5073 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5074 MVT VecVT = Vec.getSimpleValueType(); 5075 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5076 Op.getOpcode() == ISD::VECREDUCE_OR || 5077 Op.getOpcode() == ISD::VECREDUCE_XOR || 5078 Op.getOpcode() == ISD::VP_REDUCE_AND || 5079 Op.getOpcode() == ISD::VP_REDUCE_OR || 5080 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5081 "Unexpected reduction lowering"); 5082 5083 MVT XLenVT = Subtarget.getXLenVT(); 5084 assert(Op.getValueType() == XLenVT && 5085 "Expected reduction output to be legalized to XLenVT"); 5086 5087 MVT ContainerVT = VecVT; 5088 if (VecVT.isFixedLengthVector()) { 5089 ContainerVT = getContainerForFixedLengthVector(VecVT); 5090 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5091 } 5092 5093 SDValue Mask, VL; 5094 if (IsVP) { 5095 Mask = Op.getOperand(2); 5096 VL = Op.getOperand(3); 5097 } else { 5098 std::tie(Mask, VL) = 5099 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5100 } 5101 5102 unsigned BaseOpc; 5103 ISD::CondCode CC; 5104 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5105 5106 switch (Op.getOpcode()) { 5107 default: 5108 llvm_unreachable("Unhandled reduction"); 5109 case ISD::VECREDUCE_AND: 5110 case ISD::VP_REDUCE_AND: { 5111 // vcpop ~x == 0 5112 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5113 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5114 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5115 CC = ISD::SETEQ; 5116 BaseOpc = ISD::AND; 5117 break; 5118 } 5119 case ISD::VECREDUCE_OR: 5120 case ISD::VP_REDUCE_OR: 5121 // vcpop x != 0 5122 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5123 CC = ISD::SETNE; 5124 BaseOpc = ISD::OR; 5125 break; 5126 case ISD::VECREDUCE_XOR: 5127 case ISD::VP_REDUCE_XOR: { 5128 // ((vcpop x) & 1) != 0 5129 SDValue One = DAG.getConstant(1, DL, XLenVT); 5130 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5131 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5132 CC = ISD::SETNE; 5133 BaseOpc = ISD::XOR; 5134 break; 5135 } 5136 } 5137 5138 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5139 5140 if (!IsVP) 5141 return SetCC; 5142 5143 // Now include the start value in the operation. 5144 // Note that we must return the start value when no elements are operated 5145 // upon. The vcpop instructions we've emitted in each case above will return 5146 // 0 for an inactive vector, and so we've already received the neutral value: 5147 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5148 // can simply include the start value. 5149 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5150 } 5151 5152 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5153 SelectionDAG &DAG) const { 5154 SDLoc DL(Op); 5155 SDValue Vec = Op.getOperand(0); 5156 EVT VecEVT = Vec.getValueType(); 5157 5158 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5159 5160 // Due to ordering in legalize types we may have a vector type that needs to 5161 // be split. Do that manually so we can get down to a legal type. 5162 while (getTypeAction(*DAG.getContext(), VecEVT) == 5163 TargetLowering::TypeSplitVector) { 5164 SDValue Lo, Hi; 5165 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5166 VecEVT = Lo.getValueType(); 5167 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5168 } 5169 5170 // TODO: The type may need to be widened rather than split. Or widened before 5171 // it can be split. 5172 if (!isTypeLegal(VecEVT)) 5173 return SDValue(); 5174 5175 MVT VecVT = VecEVT.getSimpleVT(); 5176 MVT VecEltVT = VecVT.getVectorElementType(); 5177 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5178 5179 MVT ContainerVT = VecVT; 5180 if (VecVT.isFixedLengthVector()) { 5181 ContainerVT = getContainerForFixedLengthVector(VecVT); 5182 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5183 } 5184 5185 MVT M1VT = getLMUL1VT(ContainerVT); 5186 MVT XLenVT = Subtarget.getXLenVT(); 5187 5188 SDValue Mask, VL; 5189 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5190 5191 SDValue NeutralElem = 5192 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5193 SDValue IdentitySplat = 5194 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5195 M1VT, DL, DAG, Subtarget); 5196 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5197 IdentitySplat, Mask, VL); 5198 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5199 DAG.getConstant(0, DL, XLenVT)); 5200 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5201 } 5202 5203 // Given a reduction op, this function returns the matching reduction opcode, 5204 // the vector SDValue and the scalar SDValue required to lower this to a 5205 // RISCVISD node. 5206 static std::tuple<unsigned, SDValue, SDValue> 5207 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5208 SDLoc DL(Op); 5209 auto Flags = Op->getFlags(); 5210 unsigned Opcode = Op.getOpcode(); 5211 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5212 switch (Opcode) { 5213 default: 5214 llvm_unreachable("Unhandled reduction"); 5215 case ISD::VECREDUCE_FADD: { 5216 // Use positive zero if we can. It is cheaper to materialize. 5217 SDValue Zero = 5218 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5219 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5220 } 5221 case ISD::VECREDUCE_SEQ_FADD: 5222 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5223 Op.getOperand(0)); 5224 case ISD::VECREDUCE_FMIN: 5225 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5226 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5227 case ISD::VECREDUCE_FMAX: 5228 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5229 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5230 } 5231 } 5232 5233 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5234 SelectionDAG &DAG) const { 5235 SDLoc DL(Op); 5236 MVT VecEltVT = Op.getSimpleValueType(); 5237 5238 unsigned RVVOpcode; 5239 SDValue VectorVal, ScalarVal; 5240 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5241 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5242 MVT VecVT = VectorVal.getSimpleValueType(); 5243 5244 MVT ContainerVT = VecVT; 5245 if (VecVT.isFixedLengthVector()) { 5246 ContainerVT = getContainerForFixedLengthVector(VecVT); 5247 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5248 } 5249 5250 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5251 MVT XLenVT = Subtarget.getXLenVT(); 5252 5253 SDValue Mask, VL; 5254 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5255 5256 SDValue ScalarSplat = 5257 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5258 M1VT, DL, DAG, Subtarget); 5259 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5260 VectorVal, ScalarSplat, Mask, VL); 5261 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5262 DAG.getConstant(0, DL, XLenVT)); 5263 } 5264 5265 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5266 switch (ISDOpcode) { 5267 default: 5268 llvm_unreachable("Unhandled reduction"); 5269 case ISD::VP_REDUCE_ADD: 5270 return RISCVISD::VECREDUCE_ADD_VL; 5271 case ISD::VP_REDUCE_UMAX: 5272 return RISCVISD::VECREDUCE_UMAX_VL; 5273 case ISD::VP_REDUCE_SMAX: 5274 return RISCVISD::VECREDUCE_SMAX_VL; 5275 case ISD::VP_REDUCE_UMIN: 5276 return RISCVISD::VECREDUCE_UMIN_VL; 5277 case ISD::VP_REDUCE_SMIN: 5278 return RISCVISD::VECREDUCE_SMIN_VL; 5279 case ISD::VP_REDUCE_AND: 5280 return RISCVISD::VECREDUCE_AND_VL; 5281 case ISD::VP_REDUCE_OR: 5282 return RISCVISD::VECREDUCE_OR_VL; 5283 case ISD::VP_REDUCE_XOR: 5284 return RISCVISD::VECREDUCE_XOR_VL; 5285 case ISD::VP_REDUCE_FADD: 5286 return RISCVISD::VECREDUCE_FADD_VL; 5287 case ISD::VP_REDUCE_SEQ_FADD: 5288 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5289 case ISD::VP_REDUCE_FMAX: 5290 return RISCVISD::VECREDUCE_FMAX_VL; 5291 case ISD::VP_REDUCE_FMIN: 5292 return RISCVISD::VECREDUCE_FMIN_VL; 5293 } 5294 } 5295 5296 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5297 SelectionDAG &DAG) const { 5298 SDLoc DL(Op); 5299 SDValue Vec = Op.getOperand(1); 5300 EVT VecEVT = Vec.getValueType(); 5301 5302 // TODO: The type may need to be widened rather than split. Or widened before 5303 // it can be split. 5304 if (!isTypeLegal(VecEVT)) 5305 return SDValue(); 5306 5307 MVT VecVT = VecEVT.getSimpleVT(); 5308 MVT VecEltVT = VecVT.getVectorElementType(); 5309 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5310 5311 MVT ContainerVT = VecVT; 5312 if (VecVT.isFixedLengthVector()) { 5313 ContainerVT = getContainerForFixedLengthVector(VecVT); 5314 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5315 } 5316 5317 SDValue VL = Op.getOperand(3); 5318 SDValue Mask = Op.getOperand(2); 5319 5320 MVT M1VT = getLMUL1VT(ContainerVT); 5321 MVT XLenVT = Subtarget.getXLenVT(); 5322 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5323 5324 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5325 DAG.getConstant(1, DL, XLenVT), M1VT, 5326 DL, DAG, Subtarget); 5327 SDValue Reduction = 5328 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5329 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5330 DAG.getConstant(0, DL, XLenVT)); 5331 if (!VecVT.isInteger()) 5332 return Elt0; 5333 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5334 } 5335 5336 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5337 SelectionDAG &DAG) const { 5338 SDValue Vec = Op.getOperand(0); 5339 SDValue SubVec = Op.getOperand(1); 5340 MVT VecVT = Vec.getSimpleValueType(); 5341 MVT SubVecVT = SubVec.getSimpleValueType(); 5342 5343 SDLoc DL(Op); 5344 MVT XLenVT = Subtarget.getXLenVT(); 5345 unsigned OrigIdx = Op.getConstantOperandVal(2); 5346 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5347 5348 // We don't have the ability to slide mask vectors up indexed by their i1 5349 // elements; the smallest we can do is i8. Often we are able to bitcast to 5350 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5351 // into a scalable one, we might not necessarily have enough scalable 5352 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5353 if (SubVecVT.getVectorElementType() == MVT::i1 && 5354 (OrigIdx != 0 || !Vec.isUndef())) { 5355 if (VecVT.getVectorMinNumElements() >= 8 && 5356 SubVecVT.getVectorMinNumElements() >= 8) { 5357 assert(OrigIdx % 8 == 0 && "Invalid index"); 5358 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5359 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5360 "Unexpected mask vector lowering"); 5361 OrigIdx /= 8; 5362 SubVecVT = 5363 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5364 SubVecVT.isScalableVector()); 5365 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5366 VecVT.isScalableVector()); 5367 Vec = DAG.getBitcast(VecVT, Vec); 5368 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5369 } else { 5370 // We can't slide this mask vector up indexed by its i1 elements. 5371 // This poses a problem when we wish to insert a scalable vector which 5372 // can't be re-expressed as a larger type. Just choose the slow path and 5373 // extend to a larger type, then truncate back down. 5374 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5375 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5376 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5377 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5378 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5379 Op.getOperand(2)); 5380 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5381 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5382 } 5383 } 5384 5385 // If the subvector vector is a fixed-length type, we cannot use subregister 5386 // manipulation to simplify the codegen; we don't know which register of a 5387 // LMUL group contains the specific subvector as we only know the minimum 5388 // register size. Therefore we must slide the vector group up the full 5389 // amount. 5390 if (SubVecVT.isFixedLengthVector()) { 5391 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5392 return Op; 5393 MVT ContainerVT = VecVT; 5394 if (VecVT.isFixedLengthVector()) { 5395 ContainerVT = getContainerForFixedLengthVector(VecVT); 5396 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5397 } 5398 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5399 DAG.getUNDEF(ContainerVT), SubVec, 5400 DAG.getConstant(0, DL, XLenVT)); 5401 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5402 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5403 return DAG.getBitcast(Op.getValueType(), SubVec); 5404 } 5405 SDValue Mask = 5406 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5407 // Set the vector length to only the number of elements we care about. Note 5408 // that for slideup this includes the offset. 5409 SDValue VL = 5410 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5411 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5412 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5413 SubVec, SlideupAmt, Mask, VL); 5414 if (VecVT.isFixedLengthVector()) 5415 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5416 return DAG.getBitcast(Op.getValueType(), Slideup); 5417 } 5418 5419 unsigned SubRegIdx, RemIdx; 5420 std::tie(SubRegIdx, RemIdx) = 5421 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5422 VecVT, SubVecVT, OrigIdx, TRI); 5423 5424 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5425 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5426 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5427 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5428 5429 // 1. If the Idx has been completely eliminated and this subvector's size is 5430 // a vector register or a multiple thereof, or the surrounding elements are 5431 // undef, then this is a subvector insert which naturally aligns to a vector 5432 // register. These can easily be handled using subregister manipulation. 5433 // 2. If the subvector is smaller than a vector register, then the insertion 5434 // must preserve the undisturbed elements of the register. We do this by 5435 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5436 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5437 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5438 // LMUL=1 type back into the larger vector (resolving to another subregister 5439 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5440 // to avoid allocating a large register group to hold our subvector. 5441 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5442 return Op; 5443 5444 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5445 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5446 // (in our case undisturbed). This means we can set up a subvector insertion 5447 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5448 // size of the subvector. 5449 MVT InterSubVT = VecVT; 5450 SDValue AlignedExtract = Vec; 5451 unsigned AlignedIdx = OrigIdx - RemIdx; 5452 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5453 InterSubVT = getLMUL1VT(VecVT); 5454 // Extract a subvector equal to the nearest full vector register type. This 5455 // should resolve to a EXTRACT_SUBREG instruction. 5456 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5457 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5458 } 5459 5460 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5461 // For scalable vectors this must be further multiplied by vscale. 5462 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5463 5464 SDValue Mask, VL; 5465 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5466 5467 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5468 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5469 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5470 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5471 5472 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5473 DAG.getUNDEF(InterSubVT), SubVec, 5474 DAG.getConstant(0, DL, XLenVT)); 5475 5476 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5477 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5478 5479 // If required, insert this subvector back into the correct vector register. 5480 // This should resolve to an INSERT_SUBREG instruction. 5481 if (VecVT.bitsGT(InterSubVT)) 5482 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5483 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5484 5485 // We might have bitcast from a mask type: cast back to the original type if 5486 // required. 5487 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5488 } 5489 5490 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5491 SelectionDAG &DAG) const { 5492 SDValue Vec = Op.getOperand(0); 5493 MVT SubVecVT = Op.getSimpleValueType(); 5494 MVT VecVT = Vec.getSimpleValueType(); 5495 5496 SDLoc DL(Op); 5497 MVT XLenVT = Subtarget.getXLenVT(); 5498 unsigned OrigIdx = Op.getConstantOperandVal(1); 5499 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5500 5501 // We don't have the ability to slide mask vectors down indexed by their i1 5502 // elements; the smallest we can do is i8. Often we are able to bitcast to 5503 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5504 // from a scalable one, we might not necessarily have enough scalable 5505 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5506 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5507 if (VecVT.getVectorMinNumElements() >= 8 && 5508 SubVecVT.getVectorMinNumElements() >= 8) { 5509 assert(OrigIdx % 8 == 0 && "Invalid index"); 5510 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5511 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5512 "Unexpected mask vector lowering"); 5513 OrigIdx /= 8; 5514 SubVecVT = 5515 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5516 SubVecVT.isScalableVector()); 5517 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5518 VecVT.isScalableVector()); 5519 Vec = DAG.getBitcast(VecVT, Vec); 5520 } else { 5521 // We can't slide this mask vector down, indexed by its i1 elements. 5522 // This poses a problem when we wish to extract a scalable vector which 5523 // can't be re-expressed as a larger type. Just choose the slow path and 5524 // extend to a larger type, then truncate back down. 5525 // TODO: We could probably improve this when extracting certain fixed 5526 // from fixed, where we can extract as i8 and shift the correct element 5527 // right to reach the desired subvector? 5528 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5529 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5530 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5531 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5532 Op.getOperand(1)); 5533 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5534 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5535 } 5536 } 5537 5538 // If the subvector vector is a fixed-length type, we cannot use subregister 5539 // manipulation to simplify the codegen; we don't know which register of a 5540 // LMUL group contains the specific subvector as we only know the minimum 5541 // register size. Therefore we must slide the vector group down the full 5542 // amount. 5543 if (SubVecVT.isFixedLengthVector()) { 5544 // With an index of 0 this is a cast-like subvector, which can be performed 5545 // with subregister operations. 5546 if (OrigIdx == 0) 5547 return Op; 5548 MVT ContainerVT = VecVT; 5549 if (VecVT.isFixedLengthVector()) { 5550 ContainerVT = getContainerForFixedLengthVector(VecVT); 5551 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5552 } 5553 SDValue Mask = 5554 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5555 // Set the vector length to only the number of elements we care about. This 5556 // avoids sliding down elements we're going to discard straight away. 5557 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5558 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5559 SDValue Slidedown = 5560 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5561 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5562 // Now we can use a cast-like subvector extract to get the result. 5563 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5564 DAG.getConstant(0, DL, XLenVT)); 5565 return DAG.getBitcast(Op.getValueType(), Slidedown); 5566 } 5567 5568 unsigned SubRegIdx, RemIdx; 5569 std::tie(SubRegIdx, RemIdx) = 5570 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5571 VecVT, SubVecVT, OrigIdx, TRI); 5572 5573 // If the Idx has been completely eliminated then this is a subvector extract 5574 // which naturally aligns to a vector register. These can easily be handled 5575 // using subregister manipulation. 5576 if (RemIdx == 0) 5577 return Op; 5578 5579 // Else we must shift our vector register directly to extract the subvector. 5580 // Do this using VSLIDEDOWN. 5581 5582 // If the vector type is an LMUL-group type, extract a subvector equal to the 5583 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5584 // instruction. 5585 MVT InterSubVT = VecVT; 5586 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5587 InterSubVT = getLMUL1VT(VecVT); 5588 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5589 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5590 } 5591 5592 // Slide this vector register down by the desired number of elements in order 5593 // to place the desired subvector starting at element 0. 5594 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5595 // For scalable vectors this must be further multiplied by vscale. 5596 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5597 5598 SDValue Mask, VL; 5599 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5600 SDValue Slidedown = 5601 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5602 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5603 5604 // Now the vector is in the right position, extract our final subvector. This 5605 // should resolve to a COPY. 5606 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5607 DAG.getConstant(0, DL, XLenVT)); 5608 5609 // We might have bitcast from a mask type: cast back to the original type if 5610 // required. 5611 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5612 } 5613 5614 // Lower step_vector to the vid instruction. Any non-identity step value must 5615 // be accounted for my manual expansion. 5616 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5617 SelectionDAG &DAG) const { 5618 SDLoc DL(Op); 5619 MVT VT = Op.getSimpleValueType(); 5620 MVT XLenVT = Subtarget.getXLenVT(); 5621 SDValue Mask, VL; 5622 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5623 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5624 uint64_t StepValImm = Op.getConstantOperandVal(0); 5625 if (StepValImm != 1) { 5626 if (isPowerOf2_64(StepValImm)) { 5627 SDValue StepVal = 5628 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5629 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5630 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5631 } else { 5632 SDValue StepVal = lowerScalarSplat( 5633 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5634 VL, VT, DL, DAG, Subtarget); 5635 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5636 } 5637 } 5638 return StepVec; 5639 } 5640 5641 // Implement vector_reverse using vrgather.vv with indices determined by 5642 // subtracting the id of each element from (VLMAX-1). This will convert 5643 // the indices like so: 5644 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5645 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5646 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5647 SelectionDAG &DAG) const { 5648 SDLoc DL(Op); 5649 MVT VecVT = Op.getSimpleValueType(); 5650 unsigned EltSize = VecVT.getScalarSizeInBits(); 5651 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5652 5653 unsigned MaxVLMAX = 0; 5654 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5655 if (VectorBitsMax != 0) 5656 MaxVLMAX = 5657 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5658 5659 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5660 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5661 5662 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5663 // to use vrgatherei16.vv. 5664 // TODO: It's also possible to use vrgatherei16.vv for other types to 5665 // decrease register width for the index calculation. 5666 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5667 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5668 // Reverse each half, then reassemble them in reverse order. 5669 // NOTE: It's also possible that after splitting that VLMAX no longer 5670 // requires vrgatherei16.vv. 5671 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5672 SDValue Lo, Hi; 5673 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5674 EVT LoVT, HiVT; 5675 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5676 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5677 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5678 // Reassemble the low and high pieces reversed. 5679 // FIXME: This is a CONCAT_VECTORS. 5680 SDValue Res = 5681 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5682 DAG.getIntPtrConstant(0, DL)); 5683 return DAG.getNode( 5684 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5685 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5686 } 5687 5688 // Just promote the int type to i16 which will double the LMUL. 5689 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5690 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5691 } 5692 5693 MVT XLenVT = Subtarget.getXLenVT(); 5694 SDValue Mask, VL; 5695 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5696 5697 // Calculate VLMAX-1 for the desired SEW. 5698 unsigned MinElts = VecVT.getVectorMinNumElements(); 5699 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5700 DAG.getConstant(MinElts, DL, XLenVT)); 5701 SDValue VLMinus1 = 5702 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5703 5704 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5705 bool IsRV32E64 = 5706 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5707 SDValue SplatVL; 5708 if (!IsRV32E64) 5709 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5710 else 5711 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5712 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5713 5714 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5715 SDValue Indices = 5716 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5717 5718 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5719 } 5720 5721 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5722 SelectionDAG &DAG) const { 5723 SDLoc DL(Op); 5724 SDValue V1 = Op.getOperand(0); 5725 SDValue V2 = Op.getOperand(1); 5726 MVT XLenVT = Subtarget.getXLenVT(); 5727 MVT VecVT = Op.getSimpleValueType(); 5728 5729 unsigned MinElts = VecVT.getVectorMinNumElements(); 5730 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5731 DAG.getConstant(MinElts, DL, XLenVT)); 5732 5733 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5734 SDValue DownOffset, UpOffset; 5735 if (ImmValue >= 0) { 5736 // The operand is a TargetConstant, we need to rebuild it as a regular 5737 // constant. 5738 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5739 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5740 } else { 5741 // The operand is a TargetConstant, we need to rebuild it as a regular 5742 // constant rather than negating the original operand. 5743 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5744 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5745 } 5746 5747 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5748 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5749 5750 SDValue SlideDown = 5751 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5752 DownOffset, TrueMask, UpOffset); 5753 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5754 TrueMask, 5755 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5756 } 5757 5758 SDValue 5759 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5760 SelectionDAG &DAG) const { 5761 SDLoc DL(Op); 5762 auto *Load = cast<LoadSDNode>(Op); 5763 5764 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5765 Load->getMemoryVT(), 5766 *Load->getMemOperand()) && 5767 "Expecting a correctly-aligned load"); 5768 5769 MVT VT = Op.getSimpleValueType(); 5770 MVT XLenVT = Subtarget.getXLenVT(); 5771 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5772 5773 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5774 5775 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5776 SDValue IntID = DAG.getTargetConstant( 5777 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5778 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5779 if (!IsMaskOp) 5780 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5781 Ops.push_back(Load->getBasePtr()); 5782 Ops.push_back(VL); 5783 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5784 SDValue NewLoad = 5785 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5786 Load->getMemoryVT(), Load->getMemOperand()); 5787 5788 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5789 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5790 } 5791 5792 SDValue 5793 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5794 SelectionDAG &DAG) const { 5795 SDLoc DL(Op); 5796 auto *Store = cast<StoreSDNode>(Op); 5797 5798 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5799 Store->getMemoryVT(), 5800 *Store->getMemOperand()) && 5801 "Expecting a correctly-aligned store"); 5802 5803 SDValue StoreVal = Store->getValue(); 5804 MVT VT = StoreVal.getSimpleValueType(); 5805 MVT XLenVT = Subtarget.getXLenVT(); 5806 5807 // If the size less than a byte, we need to pad with zeros to make a byte. 5808 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5809 VT = MVT::v8i1; 5810 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5811 DAG.getConstant(0, DL, VT), StoreVal, 5812 DAG.getIntPtrConstant(0, DL)); 5813 } 5814 5815 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5816 5817 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5818 5819 SDValue NewValue = 5820 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5821 5822 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5823 SDValue IntID = DAG.getTargetConstant( 5824 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5825 return DAG.getMemIntrinsicNode( 5826 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5827 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5828 Store->getMemoryVT(), Store->getMemOperand()); 5829 } 5830 5831 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5832 SelectionDAG &DAG) const { 5833 SDLoc DL(Op); 5834 MVT VT = Op.getSimpleValueType(); 5835 5836 const auto *MemSD = cast<MemSDNode>(Op); 5837 EVT MemVT = MemSD->getMemoryVT(); 5838 MachineMemOperand *MMO = MemSD->getMemOperand(); 5839 SDValue Chain = MemSD->getChain(); 5840 SDValue BasePtr = MemSD->getBasePtr(); 5841 5842 SDValue Mask, PassThru, VL; 5843 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5844 Mask = VPLoad->getMask(); 5845 PassThru = DAG.getUNDEF(VT); 5846 VL = VPLoad->getVectorLength(); 5847 } else { 5848 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5849 Mask = MLoad->getMask(); 5850 PassThru = MLoad->getPassThru(); 5851 } 5852 5853 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5854 5855 MVT XLenVT = Subtarget.getXLenVT(); 5856 5857 MVT ContainerVT = VT; 5858 if (VT.isFixedLengthVector()) { 5859 ContainerVT = getContainerForFixedLengthVector(VT); 5860 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5861 if (!IsUnmasked) { 5862 MVT MaskVT = 5863 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5864 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5865 } 5866 } 5867 5868 if (!VL) 5869 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5870 5871 unsigned IntID = 5872 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5873 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5874 if (IsUnmasked) 5875 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5876 else 5877 Ops.push_back(PassThru); 5878 Ops.push_back(BasePtr); 5879 if (!IsUnmasked) 5880 Ops.push_back(Mask); 5881 Ops.push_back(VL); 5882 if (!IsUnmasked) 5883 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5884 5885 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5886 5887 SDValue Result = 5888 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5889 Chain = Result.getValue(1); 5890 5891 if (VT.isFixedLengthVector()) 5892 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5893 5894 return DAG.getMergeValues({Result, Chain}, DL); 5895 } 5896 5897 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5898 SelectionDAG &DAG) const { 5899 SDLoc DL(Op); 5900 5901 const auto *MemSD = cast<MemSDNode>(Op); 5902 EVT MemVT = MemSD->getMemoryVT(); 5903 MachineMemOperand *MMO = MemSD->getMemOperand(); 5904 SDValue Chain = MemSD->getChain(); 5905 SDValue BasePtr = MemSD->getBasePtr(); 5906 SDValue Val, Mask, VL; 5907 5908 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5909 Val = VPStore->getValue(); 5910 Mask = VPStore->getMask(); 5911 VL = VPStore->getVectorLength(); 5912 } else { 5913 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5914 Val = MStore->getValue(); 5915 Mask = MStore->getMask(); 5916 } 5917 5918 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5919 5920 MVT VT = Val.getSimpleValueType(); 5921 MVT XLenVT = Subtarget.getXLenVT(); 5922 5923 MVT ContainerVT = VT; 5924 if (VT.isFixedLengthVector()) { 5925 ContainerVT = getContainerForFixedLengthVector(VT); 5926 5927 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5928 if (!IsUnmasked) { 5929 MVT MaskVT = 5930 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5931 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5932 } 5933 } 5934 5935 if (!VL) 5936 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5937 5938 unsigned IntID = 5939 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5940 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5941 Ops.push_back(Val); 5942 Ops.push_back(BasePtr); 5943 if (!IsUnmasked) 5944 Ops.push_back(Mask); 5945 Ops.push_back(VL); 5946 5947 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5948 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5949 } 5950 5951 SDValue 5952 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5953 SelectionDAG &DAG) const { 5954 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5955 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5956 5957 MVT VT = Op.getSimpleValueType(); 5958 5959 SDValue Op1 = 5960 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5961 SDValue Op2 = 5962 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5963 5964 SDLoc DL(Op); 5965 SDValue VL = 5966 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5967 5968 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5969 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5970 5971 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5972 Op.getOperand(2), Mask, VL); 5973 5974 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5975 } 5976 5977 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5978 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5979 MVT VT = Op.getSimpleValueType(); 5980 5981 if (VT.getVectorElementType() == MVT::i1) 5982 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5983 5984 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5985 } 5986 5987 SDValue 5988 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5989 SelectionDAG &DAG) const { 5990 unsigned Opc; 5991 switch (Op.getOpcode()) { 5992 default: llvm_unreachable("Unexpected opcode!"); 5993 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5994 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5995 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5996 } 5997 5998 return lowerToScalableOp(Op, DAG, Opc); 5999 } 6000 6001 // Lower vector ABS to smax(X, sub(0, X)). 6002 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6003 SDLoc DL(Op); 6004 MVT VT = Op.getSimpleValueType(); 6005 SDValue X = Op.getOperand(0); 6006 6007 assert(VT.isFixedLengthVector() && "Unexpected type"); 6008 6009 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6010 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6011 6012 SDValue Mask, VL; 6013 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6014 6015 SDValue SplatZero = DAG.getNode( 6016 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6017 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6018 SDValue NegX = 6019 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6020 SDValue Max = 6021 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6022 6023 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6024 } 6025 6026 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6027 SDValue Op, SelectionDAG &DAG) const { 6028 SDLoc DL(Op); 6029 MVT VT = Op.getSimpleValueType(); 6030 SDValue Mag = Op.getOperand(0); 6031 SDValue Sign = Op.getOperand(1); 6032 assert(Mag.getValueType() == Sign.getValueType() && 6033 "Can only handle COPYSIGN with matching types."); 6034 6035 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6036 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6037 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6038 6039 SDValue Mask, VL; 6040 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6041 6042 SDValue CopySign = 6043 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6044 6045 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6046 } 6047 6048 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6049 SDValue Op, SelectionDAG &DAG) const { 6050 MVT VT = Op.getSimpleValueType(); 6051 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6052 6053 MVT I1ContainerVT = 6054 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6055 6056 SDValue CC = 6057 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6058 SDValue Op1 = 6059 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6060 SDValue Op2 = 6061 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6062 6063 SDLoc DL(Op); 6064 SDValue Mask, VL; 6065 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6066 6067 SDValue Select = 6068 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6069 6070 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6071 } 6072 6073 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6074 unsigned NewOpc, 6075 bool HasMask) const { 6076 MVT VT = Op.getSimpleValueType(); 6077 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6078 6079 // Create list of operands by converting existing ones to scalable types. 6080 SmallVector<SDValue, 6> Ops; 6081 for (const SDValue &V : Op->op_values()) { 6082 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6083 6084 // Pass through non-vector operands. 6085 if (!V.getValueType().isVector()) { 6086 Ops.push_back(V); 6087 continue; 6088 } 6089 6090 // "cast" fixed length vector to a scalable vector. 6091 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6092 "Only fixed length vectors are supported!"); 6093 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6094 } 6095 6096 SDLoc DL(Op); 6097 SDValue Mask, VL; 6098 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6099 if (HasMask) 6100 Ops.push_back(Mask); 6101 Ops.push_back(VL); 6102 6103 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6104 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6105 } 6106 6107 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6108 // * Operands of each node are assumed to be in the same order. 6109 // * The EVL operand is promoted from i32 to i64 on RV64. 6110 // * Fixed-length vectors are converted to their scalable-vector container 6111 // types. 6112 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6113 unsigned RISCVISDOpc) const { 6114 SDLoc DL(Op); 6115 MVT VT = Op.getSimpleValueType(); 6116 SmallVector<SDValue, 4> Ops; 6117 6118 for (const auto &OpIdx : enumerate(Op->ops())) { 6119 SDValue V = OpIdx.value(); 6120 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6121 // Pass through operands which aren't fixed-length vectors. 6122 if (!V.getValueType().isFixedLengthVector()) { 6123 Ops.push_back(V); 6124 continue; 6125 } 6126 // "cast" fixed length vector to a scalable vector. 6127 MVT OpVT = V.getSimpleValueType(); 6128 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6129 assert(useRVVForFixedLengthVectorVT(OpVT) && 6130 "Only fixed length vectors are supported!"); 6131 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6132 } 6133 6134 if (!VT.isFixedLengthVector()) 6135 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6136 6137 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6138 6139 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6140 6141 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6142 } 6143 6144 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6145 unsigned MaskOpc, 6146 unsigned VecOpc) const { 6147 MVT VT = Op.getSimpleValueType(); 6148 if (VT.getVectorElementType() != MVT::i1) 6149 return lowerVPOp(Op, DAG, VecOpc); 6150 6151 // It is safe to drop mask parameter as masked-off elements are undef. 6152 SDValue Op1 = Op->getOperand(0); 6153 SDValue Op2 = Op->getOperand(1); 6154 SDValue VL = Op->getOperand(3); 6155 6156 MVT ContainerVT = VT; 6157 const bool IsFixed = VT.isFixedLengthVector(); 6158 if (IsFixed) { 6159 ContainerVT = getContainerForFixedLengthVector(VT); 6160 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6161 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6162 } 6163 6164 SDLoc DL(Op); 6165 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6166 if (!IsFixed) 6167 return Val; 6168 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6169 } 6170 6171 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6172 // matched to a RVV indexed load. The RVV indexed load instructions only 6173 // support the "unsigned unscaled" addressing mode; indices are implicitly 6174 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6175 // signed or scaled indexing is extended to the XLEN value type and scaled 6176 // accordingly. 6177 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6178 SelectionDAG &DAG) const { 6179 SDLoc DL(Op); 6180 MVT VT = Op.getSimpleValueType(); 6181 6182 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6183 EVT MemVT = MemSD->getMemoryVT(); 6184 MachineMemOperand *MMO = MemSD->getMemOperand(); 6185 SDValue Chain = MemSD->getChain(); 6186 SDValue BasePtr = MemSD->getBasePtr(); 6187 6188 ISD::LoadExtType LoadExtType; 6189 SDValue Index, Mask, PassThru, VL; 6190 6191 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6192 Index = VPGN->getIndex(); 6193 Mask = VPGN->getMask(); 6194 PassThru = DAG.getUNDEF(VT); 6195 VL = VPGN->getVectorLength(); 6196 // VP doesn't support extending loads. 6197 LoadExtType = ISD::NON_EXTLOAD; 6198 } else { 6199 // Else it must be a MGATHER. 6200 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6201 Index = MGN->getIndex(); 6202 Mask = MGN->getMask(); 6203 PassThru = MGN->getPassThru(); 6204 LoadExtType = MGN->getExtensionType(); 6205 } 6206 6207 MVT IndexVT = Index.getSimpleValueType(); 6208 MVT XLenVT = Subtarget.getXLenVT(); 6209 6210 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6211 "Unexpected VTs!"); 6212 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6213 // Targets have to explicitly opt-in for extending vector loads. 6214 assert(LoadExtType == ISD::NON_EXTLOAD && 6215 "Unexpected extending MGATHER/VP_GATHER"); 6216 (void)LoadExtType; 6217 6218 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6219 // the selection of the masked intrinsics doesn't do this for us. 6220 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6221 6222 MVT ContainerVT = VT; 6223 if (VT.isFixedLengthVector()) { 6224 // We need to use the larger of the result and index type to determine the 6225 // scalable type to use so we don't increase LMUL for any operand/result. 6226 if (VT.bitsGE(IndexVT)) { 6227 ContainerVT = getContainerForFixedLengthVector(VT); 6228 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6229 ContainerVT.getVectorElementCount()); 6230 } else { 6231 IndexVT = getContainerForFixedLengthVector(IndexVT); 6232 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6233 IndexVT.getVectorElementCount()); 6234 } 6235 6236 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6237 6238 if (!IsUnmasked) { 6239 MVT MaskVT = 6240 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6241 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6242 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6243 } 6244 } 6245 6246 if (!VL) 6247 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6248 6249 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6250 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6251 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6252 VL); 6253 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6254 TrueMask, VL); 6255 } 6256 6257 unsigned IntID = 6258 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6259 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6260 if (IsUnmasked) 6261 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6262 else 6263 Ops.push_back(PassThru); 6264 Ops.push_back(BasePtr); 6265 Ops.push_back(Index); 6266 if (!IsUnmasked) 6267 Ops.push_back(Mask); 6268 Ops.push_back(VL); 6269 if (!IsUnmasked) 6270 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6271 6272 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6273 SDValue Result = 6274 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6275 Chain = Result.getValue(1); 6276 6277 if (VT.isFixedLengthVector()) 6278 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6279 6280 return DAG.getMergeValues({Result, Chain}, DL); 6281 } 6282 6283 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6284 // matched to a RVV indexed store. The RVV indexed store instructions only 6285 // support the "unsigned unscaled" addressing mode; indices are implicitly 6286 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6287 // signed or scaled indexing is extended to the XLEN value type and scaled 6288 // accordingly. 6289 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6290 SelectionDAG &DAG) const { 6291 SDLoc DL(Op); 6292 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6293 EVT MemVT = MemSD->getMemoryVT(); 6294 MachineMemOperand *MMO = MemSD->getMemOperand(); 6295 SDValue Chain = MemSD->getChain(); 6296 SDValue BasePtr = MemSD->getBasePtr(); 6297 6298 bool IsTruncatingStore = false; 6299 SDValue Index, Mask, Val, VL; 6300 6301 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6302 Index = VPSN->getIndex(); 6303 Mask = VPSN->getMask(); 6304 Val = VPSN->getValue(); 6305 VL = VPSN->getVectorLength(); 6306 // VP doesn't support truncating stores. 6307 IsTruncatingStore = false; 6308 } else { 6309 // Else it must be a MSCATTER. 6310 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6311 Index = MSN->getIndex(); 6312 Mask = MSN->getMask(); 6313 Val = MSN->getValue(); 6314 IsTruncatingStore = MSN->isTruncatingStore(); 6315 } 6316 6317 MVT VT = Val.getSimpleValueType(); 6318 MVT IndexVT = Index.getSimpleValueType(); 6319 MVT XLenVT = Subtarget.getXLenVT(); 6320 6321 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6322 "Unexpected VTs!"); 6323 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6324 // Targets have to explicitly opt-in for extending vector loads and 6325 // truncating vector stores. 6326 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6327 (void)IsTruncatingStore; 6328 6329 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6330 // the selection of the masked intrinsics doesn't do this for us. 6331 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6332 6333 MVT ContainerVT = VT; 6334 if (VT.isFixedLengthVector()) { 6335 // We need to use the larger of the value and index type to determine the 6336 // scalable type to use so we don't increase LMUL for any operand/result. 6337 if (VT.bitsGE(IndexVT)) { 6338 ContainerVT = getContainerForFixedLengthVector(VT); 6339 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6340 ContainerVT.getVectorElementCount()); 6341 } else { 6342 IndexVT = getContainerForFixedLengthVector(IndexVT); 6343 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6344 IndexVT.getVectorElementCount()); 6345 } 6346 6347 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6348 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6349 6350 if (!IsUnmasked) { 6351 MVT MaskVT = 6352 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6353 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6354 } 6355 } 6356 6357 if (!VL) 6358 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6359 6360 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6361 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6362 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6363 VL); 6364 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6365 TrueMask, VL); 6366 } 6367 6368 unsigned IntID = 6369 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6370 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6371 Ops.push_back(Val); 6372 Ops.push_back(BasePtr); 6373 Ops.push_back(Index); 6374 if (!IsUnmasked) 6375 Ops.push_back(Mask); 6376 Ops.push_back(VL); 6377 6378 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6379 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6380 } 6381 6382 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6383 SelectionDAG &DAG) const { 6384 const MVT XLenVT = Subtarget.getXLenVT(); 6385 SDLoc DL(Op); 6386 SDValue Chain = Op->getOperand(0); 6387 SDValue SysRegNo = DAG.getTargetConstant( 6388 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6389 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6390 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6391 6392 // Encoding used for rounding mode in RISCV differs from that used in 6393 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6394 // table, which consists of a sequence of 4-bit fields, each representing 6395 // corresponding FLT_ROUNDS mode. 6396 static const int Table = 6397 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6398 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6399 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6400 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6401 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6402 6403 SDValue Shift = 6404 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6405 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6406 DAG.getConstant(Table, DL, XLenVT), Shift); 6407 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6408 DAG.getConstant(7, DL, XLenVT)); 6409 6410 return DAG.getMergeValues({Masked, Chain}, DL); 6411 } 6412 6413 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6414 SelectionDAG &DAG) const { 6415 const MVT XLenVT = Subtarget.getXLenVT(); 6416 SDLoc DL(Op); 6417 SDValue Chain = Op->getOperand(0); 6418 SDValue RMValue = Op->getOperand(1); 6419 SDValue SysRegNo = DAG.getTargetConstant( 6420 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6421 6422 // Encoding used for rounding mode in RISCV differs from that used in 6423 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6424 // a table, which consists of a sequence of 4-bit fields, each representing 6425 // corresponding RISCV mode. 6426 static const unsigned Table = 6427 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6428 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6429 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6430 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6431 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6432 6433 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6434 DAG.getConstant(2, DL, XLenVT)); 6435 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6436 DAG.getConstant(Table, DL, XLenVT), Shift); 6437 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6438 DAG.getConstant(0x7, DL, XLenVT)); 6439 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6440 RMValue); 6441 } 6442 6443 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6444 switch (IntNo) { 6445 default: 6446 llvm_unreachable("Unexpected Intrinsic"); 6447 case Intrinsic::riscv_bcompress: 6448 return RISCVISD::BCOMPRESSW; 6449 case Intrinsic::riscv_bdecompress: 6450 return RISCVISD::BDECOMPRESSW; 6451 case Intrinsic::riscv_bfp: 6452 return RISCVISD::BFPW; 6453 case Intrinsic::riscv_fsl: 6454 return RISCVISD::FSLW; 6455 case Intrinsic::riscv_fsr: 6456 return RISCVISD::FSRW; 6457 } 6458 } 6459 6460 // Converts the given intrinsic to a i64 operation with any extension. 6461 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6462 unsigned IntNo) { 6463 SDLoc DL(N); 6464 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6465 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6466 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6467 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6468 // ReplaceNodeResults requires we maintain the same type for the return value. 6469 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6470 } 6471 6472 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6473 // form of the given Opcode. 6474 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6475 switch (Opcode) { 6476 default: 6477 llvm_unreachable("Unexpected opcode"); 6478 case ISD::SHL: 6479 return RISCVISD::SLLW; 6480 case ISD::SRA: 6481 return RISCVISD::SRAW; 6482 case ISD::SRL: 6483 return RISCVISD::SRLW; 6484 case ISD::SDIV: 6485 return RISCVISD::DIVW; 6486 case ISD::UDIV: 6487 return RISCVISD::DIVUW; 6488 case ISD::UREM: 6489 return RISCVISD::REMUW; 6490 case ISD::ROTL: 6491 return RISCVISD::ROLW; 6492 case ISD::ROTR: 6493 return RISCVISD::RORW; 6494 } 6495 } 6496 6497 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6498 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6499 // otherwise be promoted to i64, making it difficult to select the 6500 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6501 // type i8/i16/i32 is lost. 6502 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6503 unsigned ExtOpc = ISD::ANY_EXTEND) { 6504 SDLoc DL(N); 6505 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6506 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6507 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6508 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6509 // ReplaceNodeResults requires we maintain the same type for the return value. 6510 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6511 } 6512 6513 // Converts the given 32-bit operation to a i64 operation with signed extension 6514 // semantic to reduce the signed extension instructions. 6515 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6516 SDLoc DL(N); 6517 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6518 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6519 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6520 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6521 DAG.getValueType(MVT::i32)); 6522 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6523 } 6524 6525 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6526 SmallVectorImpl<SDValue> &Results, 6527 SelectionDAG &DAG) const { 6528 SDLoc DL(N); 6529 switch (N->getOpcode()) { 6530 default: 6531 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6532 case ISD::STRICT_FP_TO_SINT: 6533 case ISD::STRICT_FP_TO_UINT: 6534 case ISD::FP_TO_SINT: 6535 case ISD::FP_TO_UINT: { 6536 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6537 "Unexpected custom legalisation"); 6538 bool IsStrict = N->isStrictFPOpcode(); 6539 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6540 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6541 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6542 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6543 TargetLowering::TypeSoftenFloat) { 6544 if (!isTypeLegal(Op0.getValueType())) 6545 return; 6546 if (IsStrict) { 6547 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6548 : RISCVISD::STRICT_FCVT_WU_RV64; 6549 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6550 SDValue Res = DAG.getNode( 6551 Opc, DL, VTs, N->getOperand(0), Op0, 6552 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6553 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6554 Results.push_back(Res.getValue(1)); 6555 return; 6556 } 6557 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6558 SDValue Res = 6559 DAG.getNode(Opc, DL, MVT::i64, Op0, 6560 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6561 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6562 return; 6563 } 6564 // If the FP type needs to be softened, emit a library call using the 'si' 6565 // version. If we left it to default legalization we'd end up with 'di'. If 6566 // the FP type doesn't need to be softened just let generic type 6567 // legalization promote the result type. 6568 RTLIB::Libcall LC; 6569 if (IsSigned) 6570 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6571 else 6572 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6573 MakeLibCallOptions CallOptions; 6574 EVT OpVT = Op0.getValueType(); 6575 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6576 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6577 SDValue Result; 6578 std::tie(Result, Chain) = 6579 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6580 Results.push_back(Result); 6581 if (IsStrict) 6582 Results.push_back(Chain); 6583 break; 6584 } 6585 case ISD::READCYCLECOUNTER: { 6586 assert(!Subtarget.is64Bit() && 6587 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6588 6589 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6590 SDValue RCW = 6591 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6592 6593 Results.push_back( 6594 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6595 Results.push_back(RCW.getValue(2)); 6596 break; 6597 } 6598 case ISD::MUL: { 6599 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6600 unsigned XLen = Subtarget.getXLen(); 6601 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6602 if (Size > XLen) { 6603 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6604 SDValue LHS = N->getOperand(0); 6605 SDValue RHS = N->getOperand(1); 6606 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6607 6608 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6609 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6610 // We need exactly one side to be unsigned. 6611 if (LHSIsU == RHSIsU) 6612 return; 6613 6614 auto MakeMULPair = [&](SDValue S, SDValue U) { 6615 MVT XLenVT = Subtarget.getXLenVT(); 6616 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6617 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6618 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6619 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6620 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6621 }; 6622 6623 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6624 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6625 6626 // The other operand should be signed, but still prefer MULH when 6627 // possible. 6628 if (RHSIsU && LHSIsS && !RHSIsS) 6629 Results.push_back(MakeMULPair(LHS, RHS)); 6630 else if (LHSIsU && RHSIsS && !LHSIsS) 6631 Results.push_back(MakeMULPair(RHS, LHS)); 6632 6633 return; 6634 } 6635 LLVM_FALLTHROUGH; 6636 } 6637 case ISD::ADD: 6638 case ISD::SUB: 6639 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6640 "Unexpected custom legalisation"); 6641 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6642 break; 6643 case ISD::SHL: 6644 case ISD::SRA: 6645 case ISD::SRL: 6646 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6647 "Unexpected custom legalisation"); 6648 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6649 Results.push_back(customLegalizeToWOp(N, DAG)); 6650 break; 6651 } 6652 6653 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6654 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6655 // shift amount. 6656 if (N->getOpcode() == ISD::SHL) { 6657 SDLoc DL(N); 6658 SDValue NewOp0 = 6659 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6660 SDValue NewOp1 = 6661 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6662 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6663 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6664 DAG.getValueType(MVT::i32)); 6665 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6666 } 6667 6668 break; 6669 case ISD::ROTL: 6670 case ISD::ROTR: 6671 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6672 "Unexpected custom legalisation"); 6673 Results.push_back(customLegalizeToWOp(N, DAG)); 6674 break; 6675 case ISD::CTTZ: 6676 case ISD::CTTZ_ZERO_UNDEF: 6677 case ISD::CTLZ: 6678 case ISD::CTLZ_ZERO_UNDEF: { 6679 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6680 "Unexpected custom legalisation"); 6681 6682 SDValue NewOp0 = 6683 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6684 bool IsCTZ = 6685 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6686 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6687 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6688 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6689 return; 6690 } 6691 case ISD::SDIV: 6692 case ISD::UDIV: 6693 case ISD::UREM: { 6694 MVT VT = N->getSimpleValueType(0); 6695 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6696 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6697 "Unexpected custom legalisation"); 6698 // Don't promote division/remainder by constant since we should expand those 6699 // to multiply by magic constant. 6700 // FIXME: What if the expansion is disabled for minsize. 6701 if (N->getOperand(1).getOpcode() == ISD::Constant) 6702 return; 6703 6704 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6705 // the upper 32 bits. For other types we need to sign or zero extend 6706 // based on the opcode. 6707 unsigned ExtOpc = ISD::ANY_EXTEND; 6708 if (VT != MVT::i32) 6709 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6710 : ISD::ZERO_EXTEND; 6711 6712 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6713 break; 6714 } 6715 case ISD::UADDO: 6716 case ISD::USUBO: { 6717 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6718 "Unexpected custom legalisation"); 6719 bool IsAdd = N->getOpcode() == ISD::UADDO; 6720 // Create an ADDW or SUBW. 6721 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6722 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6723 SDValue Res = 6724 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6725 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6726 DAG.getValueType(MVT::i32)); 6727 6728 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6729 // Since the inputs are sign extended from i32, this is equivalent to 6730 // comparing the lower 32 bits. 6731 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6732 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6733 IsAdd ? ISD::SETULT : ISD::SETUGT); 6734 6735 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6736 Results.push_back(Overflow); 6737 return; 6738 } 6739 case ISD::UADDSAT: 6740 case ISD::USUBSAT: { 6741 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6742 "Unexpected custom legalisation"); 6743 if (Subtarget.hasStdExtZbb()) { 6744 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6745 // sign extend allows overflow of the lower 32 bits to be detected on 6746 // the promoted size. 6747 SDValue LHS = 6748 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6749 SDValue RHS = 6750 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6751 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6752 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6753 return; 6754 } 6755 6756 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6757 // promotion for UADDO/USUBO. 6758 Results.push_back(expandAddSubSat(N, DAG)); 6759 return; 6760 } 6761 case ISD::ABS: { 6762 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6763 "Unexpected custom legalisation"); 6764 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6765 6766 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6767 6768 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6769 6770 // Freeze the source so we can increase it's use count. 6771 Src = DAG.getFreeze(Src); 6772 6773 // Copy sign bit to all bits using the sraiw pattern. 6774 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6775 DAG.getValueType(MVT::i32)); 6776 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6777 DAG.getConstant(31, DL, MVT::i64)); 6778 6779 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6780 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6781 6782 // NOTE: The result is only required to be anyextended, but sext is 6783 // consistent with type legalization of sub. 6784 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6785 DAG.getValueType(MVT::i32)); 6786 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6787 return; 6788 } 6789 case ISD::BITCAST: { 6790 EVT VT = N->getValueType(0); 6791 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6792 SDValue Op0 = N->getOperand(0); 6793 EVT Op0VT = Op0.getValueType(); 6794 MVT XLenVT = Subtarget.getXLenVT(); 6795 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6796 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6797 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6798 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6799 Subtarget.hasStdExtF()) { 6800 SDValue FPConv = 6801 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6802 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6803 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6804 isTypeLegal(Op0VT)) { 6805 // Custom-legalize bitcasts from fixed-length vector types to illegal 6806 // scalar types in order to improve codegen. Bitcast the vector to a 6807 // one-element vector type whose element type is the same as the result 6808 // type, and extract the first element. 6809 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6810 if (isTypeLegal(BVT)) { 6811 SDValue BVec = DAG.getBitcast(BVT, Op0); 6812 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6813 DAG.getConstant(0, DL, XLenVT))); 6814 } 6815 } 6816 break; 6817 } 6818 case RISCVISD::GREV: 6819 case RISCVISD::GORC: 6820 case RISCVISD::SHFL: { 6821 MVT VT = N->getSimpleValueType(0); 6822 MVT XLenVT = Subtarget.getXLenVT(); 6823 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 6824 "Unexpected custom legalisation"); 6825 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6826 assert((Subtarget.hasStdExtZbp() || 6827 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 6828 N->getConstantOperandVal(1) == 7)) && 6829 "Unexpected extension"); 6830 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6831 SDValue NewOp1 = 6832 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 6833 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 6834 // ReplaceNodeResults requires we maintain the same type for the return 6835 // value. 6836 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 6837 break; 6838 } 6839 case ISD::BSWAP: 6840 case ISD::BITREVERSE: { 6841 MVT VT = N->getSimpleValueType(0); 6842 MVT XLenVT = Subtarget.getXLenVT(); 6843 assert((VT == MVT::i8 || VT == MVT::i16 || 6844 (VT == MVT::i32 && Subtarget.is64Bit())) && 6845 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6846 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6847 unsigned Imm = VT.getSizeInBits() - 1; 6848 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6849 if (N->getOpcode() == ISD::BSWAP) 6850 Imm &= ~0x7U; 6851 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 6852 DAG.getConstant(Imm, DL, XLenVT)); 6853 // ReplaceNodeResults requires we maintain the same type for the return 6854 // value. 6855 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6856 break; 6857 } 6858 case ISD::FSHL: 6859 case ISD::FSHR: { 6860 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6861 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6862 SDValue NewOp0 = 6863 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6864 SDValue NewOp1 = 6865 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6866 SDValue NewShAmt = 6867 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6868 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6869 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6870 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6871 DAG.getConstant(0x1f, DL, MVT::i64)); 6872 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6873 // instruction use different orders. fshl will return its first operand for 6874 // shift of zero, fshr will return its second operand. fsl and fsr both 6875 // return rs1 so the ISD nodes need to have different operand orders. 6876 // Shift amount is in rs2. 6877 unsigned Opc = RISCVISD::FSLW; 6878 if (N->getOpcode() == ISD::FSHR) { 6879 std::swap(NewOp0, NewOp1); 6880 Opc = RISCVISD::FSRW; 6881 } 6882 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6883 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6884 break; 6885 } 6886 case ISD::EXTRACT_VECTOR_ELT: { 6887 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6888 // type is illegal (currently only vXi64 RV32). 6889 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6890 // transferred to the destination register. We issue two of these from the 6891 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6892 // first element. 6893 SDValue Vec = N->getOperand(0); 6894 SDValue Idx = N->getOperand(1); 6895 6896 // The vector type hasn't been legalized yet so we can't issue target 6897 // specific nodes if it needs legalization. 6898 // FIXME: We would manually legalize if it's important. 6899 if (!isTypeLegal(Vec.getValueType())) 6900 return; 6901 6902 MVT VecVT = Vec.getSimpleValueType(); 6903 6904 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6905 VecVT.getVectorElementType() == MVT::i64 && 6906 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6907 6908 // If this is a fixed vector, we need to convert it to a scalable vector. 6909 MVT ContainerVT = VecVT; 6910 if (VecVT.isFixedLengthVector()) { 6911 ContainerVT = getContainerForFixedLengthVector(VecVT); 6912 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6913 } 6914 6915 MVT XLenVT = Subtarget.getXLenVT(); 6916 6917 // Use a VL of 1 to avoid processing more elements than we need. 6918 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6919 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6920 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6921 6922 // Unless the index is known to be 0, we must slide the vector down to get 6923 // the desired element into index 0. 6924 if (!isNullConstant(Idx)) { 6925 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6926 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6927 } 6928 6929 // Extract the lower XLEN bits of the correct vector element. 6930 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6931 6932 // To extract the upper XLEN bits of the vector element, shift the first 6933 // element right by 32 bits and re-extract the lower XLEN bits. 6934 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6935 DAG.getUNDEF(ContainerVT), 6936 DAG.getConstant(32, DL, XLenVT), VL); 6937 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6938 ThirtyTwoV, Mask, VL); 6939 6940 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6941 6942 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6943 break; 6944 } 6945 case ISD::INTRINSIC_WO_CHAIN: { 6946 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6947 switch (IntNo) { 6948 default: 6949 llvm_unreachable( 6950 "Don't know how to custom type legalize this intrinsic!"); 6951 case Intrinsic::riscv_grev: 6952 case Intrinsic::riscv_gorc: { 6953 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6954 "Unexpected custom legalisation"); 6955 SDValue NewOp1 = 6956 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6957 SDValue NewOp2 = 6958 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6959 unsigned Opc = 6960 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 6961 // If the control is a constant, promote the node by clearing any extra 6962 // bits bits in the control. isel will form greviw/gorciw if the result is 6963 // sign extended. 6964 if (isa<ConstantSDNode>(NewOp2)) { 6965 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6966 DAG.getConstant(0x1f, DL, MVT::i64)); 6967 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 6968 } 6969 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6970 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6971 break; 6972 } 6973 case Intrinsic::riscv_bcompress: 6974 case Intrinsic::riscv_bdecompress: 6975 case Intrinsic::riscv_bfp: { 6976 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6977 "Unexpected custom legalisation"); 6978 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6979 break; 6980 } 6981 case Intrinsic::riscv_fsl: 6982 case Intrinsic::riscv_fsr: { 6983 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6984 "Unexpected custom legalisation"); 6985 SDValue NewOp1 = 6986 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6987 SDValue NewOp2 = 6988 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6989 SDValue NewOp3 = 6990 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6991 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6992 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6993 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6994 break; 6995 } 6996 case Intrinsic::riscv_orc_b: { 6997 // Lower to the GORCI encoding for orc.b with the operand extended. 6998 SDValue NewOp = 6999 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7000 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7001 DAG.getConstant(7, DL, MVT::i64)); 7002 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7003 return; 7004 } 7005 case Intrinsic::riscv_shfl: 7006 case Intrinsic::riscv_unshfl: { 7007 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7008 "Unexpected custom legalisation"); 7009 SDValue NewOp1 = 7010 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7011 SDValue NewOp2 = 7012 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7013 unsigned Opc = 7014 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7015 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7016 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7017 // will be shuffled the same way as the lower 32 bit half, but the two 7018 // halves won't cross. 7019 if (isa<ConstantSDNode>(NewOp2)) { 7020 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7021 DAG.getConstant(0xf, DL, MVT::i64)); 7022 Opc = 7023 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7024 } 7025 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7026 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7027 break; 7028 } 7029 case Intrinsic::riscv_vmv_x_s: { 7030 EVT VT = N->getValueType(0); 7031 MVT XLenVT = Subtarget.getXLenVT(); 7032 if (VT.bitsLT(XLenVT)) { 7033 // Simple case just extract using vmv.x.s and truncate. 7034 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7035 Subtarget.getXLenVT(), N->getOperand(1)); 7036 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7037 return; 7038 } 7039 7040 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7041 "Unexpected custom legalization"); 7042 7043 // We need to do the move in two steps. 7044 SDValue Vec = N->getOperand(1); 7045 MVT VecVT = Vec.getSimpleValueType(); 7046 7047 // First extract the lower XLEN bits of the element. 7048 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7049 7050 // To extract the upper XLEN bits of the vector element, shift the first 7051 // element right by 32 bits and re-extract the lower XLEN bits. 7052 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7053 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7054 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7055 SDValue ThirtyTwoV = 7056 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7057 DAG.getConstant(32, DL, XLenVT), VL); 7058 SDValue LShr32 = 7059 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7060 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7061 7062 Results.push_back( 7063 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7064 break; 7065 } 7066 } 7067 break; 7068 } 7069 case ISD::VECREDUCE_ADD: 7070 case ISD::VECREDUCE_AND: 7071 case ISD::VECREDUCE_OR: 7072 case ISD::VECREDUCE_XOR: 7073 case ISD::VECREDUCE_SMAX: 7074 case ISD::VECREDUCE_UMAX: 7075 case ISD::VECREDUCE_SMIN: 7076 case ISD::VECREDUCE_UMIN: 7077 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7078 Results.push_back(V); 7079 break; 7080 case ISD::VP_REDUCE_ADD: 7081 case ISD::VP_REDUCE_AND: 7082 case ISD::VP_REDUCE_OR: 7083 case ISD::VP_REDUCE_XOR: 7084 case ISD::VP_REDUCE_SMAX: 7085 case ISD::VP_REDUCE_UMAX: 7086 case ISD::VP_REDUCE_SMIN: 7087 case ISD::VP_REDUCE_UMIN: 7088 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7089 Results.push_back(V); 7090 break; 7091 case ISD::FLT_ROUNDS_: { 7092 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7093 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7094 Results.push_back(Res.getValue(0)); 7095 Results.push_back(Res.getValue(1)); 7096 break; 7097 } 7098 } 7099 } 7100 7101 // A structure to hold one of the bit-manipulation patterns below. Together, a 7102 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7103 // (or (and (shl x, 1), 0xAAAAAAAA), 7104 // (and (srl x, 1), 0x55555555)) 7105 struct RISCVBitmanipPat { 7106 SDValue Op; 7107 unsigned ShAmt; 7108 bool IsSHL; 7109 7110 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7111 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7112 } 7113 }; 7114 7115 // Matches patterns of the form 7116 // (and (shl x, C2), (C1 << C2)) 7117 // (and (srl x, C2), C1) 7118 // (shl (and x, C1), C2) 7119 // (srl (and x, (C1 << C2)), C2) 7120 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7121 // The expected masks for each shift amount are specified in BitmanipMasks where 7122 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7123 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7124 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7125 // XLen is 64. 7126 static Optional<RISCVBitmanipPat> 7127 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7128 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7129 "Unexpected number of masks"); 7130 Optional<uint64_t> Mask; 7131 // Optionally consume a mask around the shift operation. 7132 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7133 Mask = Op.getConstantOperandVal(1); 7134 Op = Op.getOperand(0); 7135 } 7136 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7137 return None; 7138 bool IsSHL = Op.getOpcode() == ISD::SHL; 7139 7140 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7141 return None; 7142 uint64_t ShAmt = Op.getConstantOperandVal(1); 7143 7144 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7145 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7146 return None; 7147 // If we don't have enough masks for 64 bit, then we must be trying to 7148 // match SHFL so we're only allowed to shift 1/4 of the width. 7149 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7150 return None; 7151 7152 SDValue Src = Op.getOperand(0); 7153 7154 // The expected mask is shifted left when the AND is found around SHL 7155 // patterns. 7156 // ((x >> 1) & 0x55555555) 7157 // ((x << 1) & 0xAAAAAAAA) 7158 bool SHLExpMask = IsSHL; 7159 7160 if (!Mask) { 7161 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7162 // the mask is all ones: consume that now. 7163 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7164 Mask = Src.getConstantOperandVal(1); 7165 Src = Src.getOperand(0); 7166 // The expected mask is now in fact shifted left for SRL, so reverse the 7167 // decision. 7168 // ((x & 0xAAAAAAAA) >> 1) 7169 // ((x & 0x55555555) << 1) 7170 SHLExpMask = !SHLExpMask; 7171 } else { 7172 // Use a default shifted mask of all-ones if there's no AND, truncated 7173 // down to the expected width. This simplifies the logic later on. 7174 Mask = maskTrailingOnes<uint64_t>(Width); 7175 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7176 } 7177 } 7178 7179 unsigned MaskIdx = Log2_32(ShAmt); 7180 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7181 7182 if (SHLExpMask) 7183 ExpMask <<= ShAmt; 7184 7185 if (Mask != ExpMask) 7186 return None; 7187 7188 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7189 } 7190 7191 // Matches any of the following bit-manipulation patterns: 7192 // (and (shl x, 1), (0x55555555 << 1)) 7193 // (and (srl x, 1), 0x55555555) 7194 // (shl (and x, 0x55555555), 1) 7195 // (srl (and x, (0x55555555 << 1)), 1) 7196 // where the shift amount and mask may vary thus: 7197 // [1] = 0x55555555 / 0xAAAAAAAA 7198 // [2] = 0x33333333 / 0xCCCCCCCC 7199 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7200 // [8] = 0x00FF00FF / 0xFF00FF00 7201 // [16] = 0x0000FFFF / 0xFFFFFFFF 7202 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7203 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7204 // These are the unshifted masks which we use to match bit-manipulation 7205 // patterns. They may be shifted left in certain circumstances. 7206 static const uint64_t BitmanipMasks[] = { 7207 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7208 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7209 7210 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7211 } 7212 7213 // Match the following pattern as a GREVI(W) operation 7214 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7215 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7216 const RISCVSubtarget &Subtarget) { 7217 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7218 EVT VT = Op.getValueType(); 7219 7220 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7221 auto LHS = matchGREVIPat(Op.getOperand(0)); 7222 auto RHS = matchGREVIPat(Op.getOperand(1)); 7223 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7224 SDLoc DL(Op); 7225 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7226 DAG.getConstant(LHS->ShAmt, DL, VT)); 7227 } 7228 } 7229 return SDValue(); 7230 } 7231 7232 // Matches any the following pattern as a GORCI(W) operation 7233 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7234 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7235 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7236 // Note that with the variant of 3., 7237 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7238 // the inner pattern will first be matched as GREVI and then the outer 7239 // pattern will be matched to GORC via the first rule above. 7240 // 4. (or (rotl/rotr x, bitwidth/2), x) 7241 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7242 const RISCVSubtarget &Subtarget) { 7243 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7244 EVT VT = Op.getValueType(); 7245 7246 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7247 SDLoc DL(Op); 7248 SDValue Op0 = Op.getOperand(0); 7249 SDValue Op1 = Op.getOperand(1); 7250 7251 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7252 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7253 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7254 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7255 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7256 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7257 if ((Reverse.getOpcode() == ISD::ROTL || 7258 Reverse.getOpcode() == ISD::ROTR) && 7259 Reverse.getOperand(0) == X && 7260 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7261 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7262 if (RotAmt == (VT.getSizeInBits() / 2)) 7263 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7264 DAG.getConstant(RotAmt, DL, VT)); 7265 } 7266 return SDValue(); 7267 }; 7268 7269 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7270 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7271 return V; 7272 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7273 return V; 7274 7275 // OR is commutable so canonicalize its OR operand to the left 7276 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7277 std::swap(Op0, Op1); 7278 if (Op0.getOpcode() != ISD::OR) 7279 return SDValue(); 7280 SDValue OrOp0 = Op0.getOperand(0); 7281 SDValue OrOp1 = Op0.getOperand(1); 7282 auto LHS = matchGREVIPat(OrOp0); 7283 // OR is commutable so swap the operands and try again: x might have been 7284 // on the left 7285 if (!LHS) { 7286 std::swap(OrOp0, OrOp1); 7287 LHS = matchGREVIPat(OrOp0); 7288 } 7289 auto RHS = matchGREVIPat(Op1); 7290 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7291 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7292 DAG.getConstant(LHS->ShAmt, DL, VT)); 7293 } 7294 } 7295 return SDValue(); 7296 } 7297 7298 // Matches any of the following bit-manipulation patterns: 7299 // (and (shl x, 1), (0x22222222 << 1)) 7300 // (and (srl x, 1), 0x22222222) 7301 // (shl (and x, 0x22222222), 1) 7302 // (srl (and x, (0x22222222 << 1)), 1) 7303 // where the shift amount and mask may vary thus: 7304 // [1] = 0x22222222 / 0x44444444 7305 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7306 // [4] = 0x00F000F0 / 0x0F000F00 7307 // [8] = 0x0000FF00 / 0x00FF0000 7308 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7309 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7310 // These are the unshifted masks which we use to match bit-manipulation 7311 // patterns. They may be shifted left in certain circumstances. 7312 static const uint64_t BitmanipMasks[] = { 7313 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7314 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7315 7316 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7317 } 7318 7319 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7320 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7321 const RISCVSubtarget &Subtarget) { 7322 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7323 EVT VT = Op.getValueType(); 7324 7325 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7326 return SDValue(); 7327 7328 SDValue Op0 = Op.getOperand(0); 7329 SDValue Op1 = Op.getOperand(1); 7330 7331 // Or is commutable so canonicalize the second OR to the LHS. 7332 if (Op0.getOpcode() != ISD::OR) 7333 std::swap(Op0, Op1); 7334 if (Op0.getOpcode() != ISD::OR) 7335 return SDValue(); 7336 7337 // We found an inner OR, so our operands are the operands of the inner OR 7338 // and the other operand of the outer OR. 7339 SDValue A = Op0.getOperand(0); 7340 SDValue B = Op0.getOperand(1); 7341 SDValue C = Op1; 7342 7343 auto Match1 = matchSHFLPat(A); 7344 auto Match2 = matchSHFLPat(B); 7345 7346 // If neither matched, we failed. 7347 if (!Match1 && !Match2) 7348 return SDValue(); 7349 7350 // We had at least one match. if one failed, try the remaining C operand. 7351 if (!Match1) { 7352 std::swap(A, C); 7353 Match1 = matchSHFLPat(A); 7354 if (!Match1) 7355 return SDValue(); 7356 } else if (!Match2) { 7357 std::swap(B, C); 7358 Match2 = matchSHFLPat(B); 7359 if (!Match2) 7360 return SDValue(); 7361 } 7362 assert(Match1 && Match2); 7363 7364 // Make sure our matches pair up. 7365 if (!Match1->formsPairWith(*Match2)) 7366 return SDValue(); 7367 7368 // All the remains is to make sure C is an AND with the same input, that masks 7369 // out the bits that are being shuffled. 7370 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7371 C.getOperand(0) != Match1->Op) 7372 return SDValue(); 7373 7374 uint64_t Mask = C.getConstantOperandVal(1); 7375 7376 static const uint64_t BitmanipMasks[] = { 7377 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7378 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7379 }; 7380 7381 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7382 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7383 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7384 7385 if (Mask != ExpMask) 7386 return SDValue(); 7387 7388 SDLoc DL(Op); 7389 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7390 DAG.getConstant(Match1->ShAmt, DL, VT)); 7391 } 7392 7393 // Optimize (add (shl x, c0), (shl y, c1)) -> 7394 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7395 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7396 const RISCVSubtarget &Subtarget) { 7397 // Perform this optimization only in the zba extension. 7398 if (!Subtarget.hasStdExtZba()) 7399 return SDValue(); 7400 7401 // Skip for vector types and larger types. 7402 EVT VT = N->getValueType(0); 7403 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7404 return SDValue(); 7405 7406 // The two operand nodes must be SHL and have no other use. 7407 SDValue N0 = N->getOperand(0); 7408 SDValue N1 = N->getOperand(1); 7409 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7410 !N0->hasOneUse() || !N1->hasOneUse()) 7411 return SDValue(); 7412 7413 // Check c0 and c1. 7414 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7415 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7416 if (!N0C || !N1C) 7417 return SDValue(); 7418 int64_t C0 = N0C->getSExtValue(); 7419 int64_t C1 = N1C->getSExtValue(); 7420 if (C0 <= 0 || C1 <= 0) 7421 return SDValue(); 7422 7423 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7424 int64_t Bits = std::min(C0, C1); 7425 int64_t Diff = std::abs(C0 - C1); 7426 if (Diff != 1 && Diff != 2 && Diff != 3) 7427 return SDValue(); 7428 7429 // Build nodes. 7430 SDLoc DL(N); 7431 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7432 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7433 SDValue NA0 = 7434 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7435 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7436 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7437 } 7438 7439 // Combine 7440 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7441 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7442 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7443 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7444 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7445 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7446 // The grev patterns represents BSWAP. 7447 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7448 // off the grev. 7449 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7450 const RISCVSubtarget &Subtarget) { 7451 bool IsWInstruction = 7452 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7453 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7454 IsWInstruction) && 7455 "Unexpected opcode!"); 7456 SDValue Src = N->getOperand(0); 7457 EVT VT = N->getValueType(0); 7458 SDLoc DL(N); 7459 7460 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7461 return SDValue(); 7462 7463 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7464 !isa<ConstantSDNode>(Src.getOperand(1))) 7465 return SDValue(); 7466 7467 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7468 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7469 7470 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7471 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7472 unsigned ShAmt1 = N->getConstantOperandVal(1); 7473 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7474 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7475 return SDValue(); 7476 7477 Src = Src.getOperand(0); 7478 7479 // Toggle bit the MSB of the shift. 7480 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7481 if (CombinedShAmt == 0) 7482 return Src; 7483 7484 SDValue Res = DAG.getNode( 7485 RISCVISD::GREV, DL, VT, Src, 7486 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7487 if (!IsWInstruction) 7488 return Res; 7489 7490 // Sign extend the result to match the behavior of the rotate. This will be 7491 // selected to GREVIW in isel. 7492 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7493 DAG.getValueType(MVT::i32)); 7494 } 7495 7496 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7497 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7498 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7499 // not undo itself, but they are redundant. 7500 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7501 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7502 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7503 SDValue Src = N->getOperand(0); 7504 7505 if (Src.getOpcode() != N->getOpcode()) 7506 return SDValue(); 7507 7508 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7509 !isa<ConstantSDNode>(Src.getOperand(1))) 7510 return SDValue(); 7511 7512 unsigned ShAmt1 = N->getConstantOperandVal(1); 7513 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7514 Src = Src.getOperand(0); 7515 7516 unsigned CombinedShAmt; 7517 if (IsGORC) 7518 CombinedShAmt = ShAmt1 | ShAmt2; 7519 else 7520 CombinedShAmt = ShAmt1 ^ ShAmt2; 7521 7522 if (CombinedShAmt == 0) 7523 return Src; 7524 7525 SDLoc DL(N); 7526 return DAG.getNode( 7527 N->getOpcode(), DL, N->getValueType(0), Src, 7528 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7529 } 7530 7531 // Combine a constant select operand into its use: 7532 // 7533 // (and (select cond, -1, c), x) 7534 // -> (select cond, x, (and x, c)) [AllOnes=1] 7535 // (or (select cond, 0, c), x) 7536 // -> (select cond, x, (or x, c)) [AllOnes=0] 7537 // (xor (select cond, 0, c), x) 7538 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7539 // (add (select cond, 0, c), x) 7540 // -> (select cond, x, (add x, c)) [AllOnes=0] 7541 // (sub x, (select cond, 0, c)) 7542 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7543 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7544 SelectionDAG &DAG, bool AllOnes) { 7545 EVT VT = N->getValueType(0); 7546 7547 // Skip vectors. 7548 if (VT.isVector()) 7549 return SDValue(); 7550 7551 if ((Slct.getOpcode() != ISD::SELECT && 7552 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7553 !Slct.hasOneUse()) 7554 return SDValue(); 7555 7556 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7557 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7558 }; 7559 7560 bool SwapSelectOps; 7561 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7562 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7563 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7564 SDValue NonConstantVal; 7565 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7566 SwapSelectOps = false; 7567 NonConstantVal = FalseVal; 7568 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7569 SwapSelectOps = true; 7570 NonConstantVal = TrueVal; 7571 } else 7572 return SDValue(); 7573 7574 // Slct is now know to be the desired identity constant when CC is true. 7575 TrueVal = OtherOp; 7576 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7577 // Unless SwapSelectOps says the condition should be false. 7578 if (SwapSelectOps) 7579 std::swap(TrueVal, FalseVal); 7580 7581 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7582 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7583 {Slct.getOperand(0), Slct.getOperand(1), 7584 Slct.getOperand(2), TrueVal, FalseVal}); 7585 7586 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7587 {Slct.getOperand(0), TrueVal, FalseVal}); 7588 } 7589 7590 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7591 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7592 bool AllOnes) { 7593 SDValue N0 = N->getOperand(0); 7594 SDValue N1 = N->getOperand(1); 7595 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7596 return Result; 7597 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7598 return Result; 7599 return SDValue(); 7600 } 7601 7602 // Transform (add (mul x, c0), c1) -> 7603 // (add (mul (add x, c1/c0), c0), c1%c0). 7604 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7605 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7606 // to an infinite loop in DAGCombine if transformed. 7607 // Or transform (add (mul x, c0), c1) -> 7608 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7609 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7610 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7611 // lead to an infinite loop in DAGCombine if transformed. 7612 // Or transform (add (mul x, c0), c1) -> 7613 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7614 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7615 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7616 // lead to an infinite loop in DAGCombine if transformed. 7617 // Or transform (add (mul x, c0), c1) -> 7618 // (mul (add x, c1/c0), c0). 7619 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7620 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7621 const RISCVSubtarget &Subtarget) { 7622 // Skip for vector types and larger types. 7623 EVT VT = N->getValueType(0); 7624 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7625 return SDValue(); 7626 // The first operand node must be a MUL and has no other use. 7627 SDValue N0 = N->getOperand(0); 7628 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7629 return SDValue(); 7630 // Check if c0 and c1 match above conditions. 7631 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7632 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7633 if (!N0C || !N1C) 7634 return SDValue(); 7635 // If N0C has multiple uses it's possible one of the cases in 7636 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7637 // in an infinite loop. 7638 if (!N0C->hasOneUse()) 7639 return SDValue(); 7640 int64_t C0 = N0C->getSExtValue(); 7641 int64_t C1 = N1C->getSExtValue(); 7642 int64_t CA, CB; 7643 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7644 return SDValue(); 7645 // Search for proper CA (non-zero) and CB that both are simm12. 7646 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7647 !isInt<12>(C0 * (C1 / C0))) { 7648 CA = C1 / C0; 7649 CB = C1 % C0; 7650 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7651 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7652 CA = C1 / C0 + 1; 7653 CB = C1 % C0 - C0; 7654 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7655 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7656 CA = C1 / C0 - 1; 7657 CB = C1 % C0 + C0; 7658 } else 7659 return SDValue(); 7660 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7661 SDLoc DL(N); 7662 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7663 DAG.getConstant(CA, DL, VT)); 7664 SDValue New1 = 7665 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7666 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7667 } 7668 7669 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7670 const RISCVSubtarget &Subtarget) { 7671 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7672 return V; 7673 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7674 return V; 7675 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7676 // (select lhs, rhs, cc, x, (add x, y)) 7677 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7678 } 7679 7680 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7681 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7682 // (select lhs, rhs, cc, x, (sub x, y)) 7683 SDValue N0 = N->getOperand(0); 7684 SDValue N1 = N->getOperand(1); 7685 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7686 } 7687 7688 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7689 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7690 // (select lhs, rhs, cc, x, (and x, y)) 7691 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7692 } 7693 7694 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7695 const RISCVSubtarget &Subtarget) { 7696 if (Subtarget.hasStdExtZbp()) { 7697 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7698 return GREV; 7699 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7700 return GORC; 7701 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7702 return SHFL; 7703 } 7704 7705 // fold (or (select cond, 0, y), x) -> 7706 // (select cond, x, (or x, y)) 7707 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7708 } 7709 7710 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7711 // fold (xor (select cond, 0, y), x) -> 7712 // (select cond, x, (xor x, y)) 7713 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7714 } 7715 7716 static SDValue 7717 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7718 const RISCVSubtarget &Subtarget) { 7719 SDValue Src = N->getOperand(0); 7720 EVT VT = N->getValueType(0); 7721 7722 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7723 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7724 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7725 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7726 Src.getOperand(0)); 7727 7728 // Fold (i64 (sext_inreg (abs X), i32)) -> 7729 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7730 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7731 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7732 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7733 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7734 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7735 // may get combined into an earlier operation so we need to use 7736 // ComputeNumSignBits. 7737 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7738 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7739 // we can't assume that X has 33 sign bits. We must check. 7740 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7741 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7742 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7743 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7744 SDLoc DL(N); 7745 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7746 SDValue Neg = 7747 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7748 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7749 DAG.getValueType(MVT::i32)); 7750 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7751 } 7752 7753 return SDValue(); 7754 } 7755 7756 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7757 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7758 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7759 bool Commute = false) { 7760 assert((N->getOpcode() == RISCVISD::ADD_VL || 7761 N->getOpcode() == RISCVISD::SUB_VL) && 7762 "Unexpected opcode"); 7763 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7764 SDValue Op0 = N->getOperand(0); 7765 SDValue Op1 = N->getOperand(1); 7766 if (Commute) 7767 std::swap(Op0, Op1); 7768 7769 MVT VT = N->getSimpleValueType(0); 7770 7771 // Determine the narrow size for a widening add/sub. 7772 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7773 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7774 VT.getVectorElementCount()); 7775 7776 SDValue Mask = N->getOperand(2); 7777 SDValue VL = N->getOperand(3); 7778 7779 SDLoc DL(N); 7780 7781 // If the RHS is a sext or zext, we can form a widening op. 7782 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7783 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7784 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7785 unsigned ExtOpc = Op1.getOpcode(); 7786 Op1 = Op1.getOperand(0); 7787 // Re-introduce narrower extends if needed. 7788 if (Op1.getValueType() != NarrowVT) 7789 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7790 7791 unsigned WOpc; 7792 if (ExtOpc == RISCVISD::VSEXT_VL) 7793 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7794 else 7795 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7796 7797 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7798 } 7799 7800 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7801 // sext/zext? 7802 7803 return SDValue(); 7804 } 7805 7806 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7807 // vwsub(u).vv/vx. 7808 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7809 SDValue Op0 = N->getOperand(0); 7810 SDValue Op1 = N->getOperand(1); 7811 SDValue Mask = N->getOperand(2); 7812 SDValue VL = N->getOperand(3); 7813 7814 MVT VT = N->getSimpleValueType(0); 7815 MVT NarrowVT = Op1.getSimpleValueType(); 7816 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7817 7818 unsigned VOpc; 7819 switch (N->getOpcode()) { 7820 default: llvm_unreachable("Unexpected opcode"); 7821 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7822 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7823 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7824 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7825 } 7826 7827 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7828 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7829 7830 SDLoc DL(N); 7831 7832 // If the LHS is a sext or zext, we can narrow this op to the same size as 7833 // the RHS. 7834 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7835 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7836 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7837 unsigned ExtOpc = Op0.getOpcode(); 7838 Op0 = Op0.getOperand(0); 7839 // Re-introduce narrower extends if needed. 7840 if (Op0.getValueType() != NarrowVT) 7841 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7842 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7843 } 7844 7845 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7846 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7847 7848 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7849 // to commute and use a vwadd(u).vx instead. 7850 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7851 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7852 Op0 = Op0.getOperand(1); 7853 7854 // See if have enough sign bits or zero bits in the scalar to use a 7855 // widening add/sub by splatting to smaller element size. 7856 unsigned EltBits = VT.getScalarSizeInBits(); 7857 unsigned ScalarBits = Op0.getValueSizeInBits(); 7858 // Make sure we're getting all element bits from the scalar register. 7859 // FIXME: Support implicit sign extension of vmv.v.x? 7860 if (ScalarBits < EltBits) 7861 return SDValue(); 7862 7863 if (IsSigned) { 7864 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7865 return SDValue(); 7866 } else { 7867 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7868 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7869 return SDValue(); 7870 } 7871 7872 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7873 DAG.getUNDEF(NarrowVT), Op0, VL); 7874 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7875 } 7876 7877 return SDValue(); 7878 } 7879 7880 // Try to form VWMUL, VWMULU or VWMULSU. 7881 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7882 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7883 bool Commute) { 7884 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7885 SDValue Op0 = N->getOperand(0); 7886 SDValue Op1 = N->getOperand(1); 7887 if (Commute) 7888 std::swap(Op0, Op1); 7889 7890 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7891 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7892 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7893 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7894 return SDValue(); 7895 7896 SDValue Mask = N->getOperand(2); 7897 SDValue VL = N->getOperand(3); 7898 7899 // Make sure the mask and VL match. 7900 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7901 return SDValue(); 7902 7903 MVT VT = N->getSimpleValueType(0); 7904 7905 // Determine the narrow size for a widening multiply. 7906 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7907 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7908 VT.getVectorElementCount()); 7909 7910 SDLoc DL(N); 7911 7912 // See if the other operand is the same opcode. 7913 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7914 if (!Op1.hasOneUse()) 7915 return SDValue(); 7916 7917 // Make sure the mask and VL match. 7918 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7919 return SDValue(); 7920 7921 Op1 = Op1.getOperand(0); 7922 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7923 // The operand is a splat of a scalar. 7924 7925 // The pasthru must be undef for tail agnostic 7926 if (!Op1.getOperand(0).isUndef()) 7927 return SDValue(); 7928 // The VL must be the same. 7929 if (Op1.getOperand(2) != VL) 7930 return SDValue(); 7931 7932 // Get the scalar value. 7933 Op1 = Op1.getOperand(1); 7934 7935 // See if have enough sign bits or zero bits in the scalar to use a 7936 // widening multiply by splatting to smaller element size. 7937 unsigned EltBits = VT.getScalarSizeInBits(); 7938 unsigned ScalarBits = Op1.getValueSizeInBits(); 7939 // Make sure we're getting all element bits from the scalar register. 7940 // FIXME: Support implicit sign extension of vmv.v.x? 7941 if (ScalarBits < EltBits) 7942 return SDValue(); 7943 7944 // If the LHS is a sign extend, try to use vwmul. 7945 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7946 // Can use vwmul. 7947 } else { 7948 // Otherwise try to use vwmulu or vwmulsu. 7949 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7950 if (DAG.MaskedValueIsZero(Op1, Mask)) 7951 IsVWMULSU = IsSignExt; 7952 else 7953 return SDValue(); 7954 } 7955 7956 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7957 DAG.getUNDEF(NarrowVT), Op1, VL); 7958 } else 7959 return SDValue(); 7960 7961 Op0 = Op0.getOperand(0); 7962 7963 // Re-introduce narrower extends if needed. 7964 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7965 if (Op0.getValueType() != NarrowVT) 7966 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7967 // vwmulsu requires second operand to be zero extended. 7968 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7969 if (Op1.getValueType() != NarrowVT) 7970 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7971 7972 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7973 if (!IsVWMULSU) 7974 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7975 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7976 } 7977 7978 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7979 switch (Op.getOpcode()) { 7980 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7981 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7982 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7983 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7984 case ISD::FROUND: return RISCVFPRndMode::RMM; 7985 } 7986 7987 return RISCVFPRndMode::Invalid; 7988 } 7989 7990 // Fold 7991 // (fp_to_int (froundeven X)) -> fcvt X, rne 7992 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7993 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7994 // (fp_to_int (fceil X)) -> fcvt X, rup 7995 // (fp_to_int (fround X)) -> fcvt X, rmm 7996 static SDValue performFP_TO_INTCombine(SDNode *N, 7997 TargetLowering::DAGCombinerInfo &DCI, 7998 const RISCVSubtarget &Subtarget) { 7999 SelectionDAG &DAG = DCI.DAG; 8000 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8001 MVT XLenVT = Subtarget.getXLenVT(); 8002 8003 // Only handle XLen or i32 types. Other types narrower than XLen will 8004 // eventually be legalized to XLenVT. 8005 EVT VT = N->getValueType(0); 8006 if (VT != MVT::i32 && VT != XLenVT) 8007 return SDValue(); 8008 8009 SDValue Src = N->getOperand(0); 8010 8011 // Ensure the FP type is also legal. 8012 if (!TLI.isTypeLegal(Src.getValueType())) 8013 return SDValue(); 8014 8015 // Don't do this for f16 with Zfhmin and not Zfh. 8016 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8017 return SDValue(); 8018 8019 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8020 if (FRM == RISCVFPRndMode::Invalid) 8021 return SDValue(); 8022 8023 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8024 8025 unsigned Opc; 8026 if (VT == XLenVT) 8027 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8028 else 8029 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8030 8031 SDLoc DL(N); 8032 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8033 DAG.getTargetConstant(FRM, DL, XLenVT)); 8034 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8035 } 8036 8037 // Fold 8038 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8039 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8040 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8041 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8042 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8043 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8044 TargetLowering::DAGCombinerInfo &DCI, 8045 const RISCVSubtarget &Subtarget) { 8046 SelectionDAG &DAG = DCI.DAG; 8047 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8048 MVT XLenVT = Subtarget.getXLenVT(); 8049 8050 // Only handle XLen types. Other types narrower than XLen will eventually be 8051 // legalized to XLenVT. 8052 EVT DstVT = N->getValueType(0); 8053 if (DstVT != XLenVT) 8054 return SDValue(); 8055 8056 SDValue Src = N->getOperand(0); 8057 8058 // Ensure the FP type is also legal. 8059 if (!TLI.isTypeLegal(Src.getValueType())) 8060 return SDValue(); 8061 8062 // Don't do this for f16 with Zfhmin and not Zfh. 8063 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8064 return SDValue(); 8065 8066 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8067 8068 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8069 if (FRM == RISCVFPRndMode::Invalid) 8070 return SDValue(); 8071 8072 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8073 8074 unsigned Opc; 8075 if (SatVT == DstVT) 8076 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8077 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8078 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8079 else 8080 return SDValue(); 8081 // FIXME: Support other SatVTs by clamping before or after the conversion. 8082 8083 Src = Src.getOperand(0); 8084 8085 SDLoc DL(N); 8086 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8087 DAG.getTargetConstant(FRM, DL, XLenVT)); 8088 8089 // RISCV FP-to-int conversions saturate to the destination register size, but 8090 // don't produce 0 for nan. 8091 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8092 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8093 } 8094 8095 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8096 // smaller than XLenVT. 8097 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8098 const RISCVSubtarget &Subtarget) { 8099 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8100 8101 SDValue Src = N->getOperand(0); 8102 if (Src.getOpcode() != ISD::BSWAP) 8103 return SDValue(); 8104 8105 EVT VT = N->getValueType(0); 8106 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8107 !isPowerOf2_32(VT.getSizeInBits())) 8108 return SDValue(); 8109 8110 SDLoc DL(N); 8111 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8112 DAG.getConstant(7, DL, VT)); 8113 } 8114 8115 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8116 DAGCombinerInfo &DCI) const { 8117 SelectionDAG &DAG = DCI.DAG; 8118 8119 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8120 // bits are demanded. N will be added to the Worklist if it was not deleted. 8121 // Caller should return SDValue(N, 0) if this returns true. 8122 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8123 SDValue Op = N->getOperand(OpNo); 8124 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8125 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8126 return false; 8127 8128 if (N->getOpcode() != ISD::DELETED_NODE) 8129 DCI.AddToWorklist(N); 8130 return true; 8131 }; 8132 8133 switch (N->getOpcode()) { 8134 default: 8135 break; 8136 case RISCVISD::SplitF64: { 8137 SDValue Op0 = N->getOperand(0); 8138 // If the input to SplitF64 is just BuildPairF64 then the operation is 8139 // redundant. Instead, use BuildPairF64's operands directly. 8140 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8141 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8142 8143 if (Op0->isUndef()) { 8144 SDValue Lo = DAG.getUNDEF(MVT::i32); 8145 SDValue Hi = DAG.getUNDEF(MVT::i32); 8146 return DCI.CombineTo(N, Lo, Hi); 8147 } 8148 8149 SDLoc DL(N); 8150 8151 // It's cheaper to materialise two 32-bit integers than to load a double 8152 // from the constant pool and transfer it to integer registers through the 8153 // stack. 8154 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8155 APInt V = C->getValueAPF().bitcastToAPInt(); 8156 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8157 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8158 return DCI.CombineTo(N, Lo, Hi); 8159 } 8160 8161 // This is a target-specific version of a DAGCombine performed in 8162 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8163 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8164 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8165 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8166 !Op0.getNode()->hasOneUse()) 8167 break; 8168 SDValue NewSplitF64 = 8169 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8170 Op0.getOperand(0)); 8171 SDValue Lo = NewSplitF64.getValue(0); 8172 SDValue Hi = NewSplitF64.getValue(1); 8173 APInt SignBit = APInt::getSignMask(32); 8174 if (Op0.getOpcode() == ISD::FNEG) { 8175 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8176 DAG.getConstant(SignBit, DL, MVT::i32)); 8177 return DCI.CombineTo(N, Lo, NewHi); 8178 } 8179 assert(Op0.getOpcode() == ISD::FABS); 8180 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8181 DAG.getConstant(~SignBit, DL, MVT::i32)); 8182 return DCI.CombineTo(N, Lo, NewHi); 8183 } 8184 case RISCVISD::SLLW: 8185 case RISCVISD::SRAW: 8186 case RISCVISD::SRLW: { 8187 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8188 if (SimplifyDemandedLowBitsHelper(0, 32) || 8189 SimplifyDemandedLowBitsHelper(1, 5)) 8190 return SDValue(N, 0); 8191 8192 break; 8193 } 8194 case ISD::ROTR: 8195 case ISD::ROTL: 8196 case RISCVISD::RORW: 8197 case RISCVISD::ROLW: { 8198 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8199 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8200 if (SimplifyDemandedLowBitsHelper(0, 32) || 8201 SimplifyDemandedLowBitsHelper(1, 5)) 8202 return SDValue(N, 0); 8203 } 8204 8205 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8206 } 8207 case RISCVISD::CLZW: 8208 case RISCVISD::CTZW: { 8209 // Only the lower 32 bits of the first operand are read 8210 if (SimplifyDemandedLowBitsHelper(0, 32)) 8211 return SDValue(N, 0); 8212 break; 8213 } 8214 case RISCVISD::GREV: 8215 case RISCVISD::GORC: { 8216 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8217 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8218 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8219 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8220 return SDValue(N, 0); 8221 8222 return combineGREVI_GORCI(N, DAG); 8223 } 8224 case RISCVISD::GREVW: 8225 case RISCVISD::GORCW: { 8226 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8227 if (SimplifyDemandedLowBitsHelper(0, 32) || 8228 SimplifyDemandedLowBitsHelper(1, 5)) 8229 return SDValue(N, 0); 8230 8231 break; 8232 } 8233 case RISCVISD::SHFL: 8234 case RISCVISD::UNSHFL: { 8235 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8236 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8237 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8238 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8239 return SDValue(N, 0); 8240 8241 break; 8242 } 8243 case RISCVISD::SHFLW: 8244 case RISCVISD::UNSHFLW: { 8245 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8246 if (SimplifyDemandedLowBitsHelper(0, 32) || 8247 SimplifyDemandedLowBitsHelper(1, 4)) 8248 return SDValue(N, 0); 8249 8250 break; 8251 } 8252 case RISCVISD::BCOMPRESSW: 8253 case RISCVISD::BDECOMPRESSW: { 8254 // Only the lower 32 bits of LHS and RHS are read. 8255 if (SimplifyDemandedLowBitsHelper(0, 32) || 8256 SimplifyDemandedLowBitsHelper(1, 32)) 8257 return SDValue(N, 0); 8258 8259 break; 8260 } 8261 case RISCVISD::FSR: 8262 case RISCVISD::FSL: 8263 case RISCVISD::FSRW: 8264 case RISCVISD::FSLW: { 8265 bool IsWInstruction = 8266 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8267 unsigned BitWidth = 8268 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8269 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8270 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8271 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8272 return SDValue(N, 0); 8273 8274 break; 8275 } 8276 case RISCVISD::FMV_X_ANYEXTH: 8277 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8278 SDLoc DL(N); 8279 SDValue Op0 = N->getOperand(0); 8280 MVT VT = N->getSimpleValueType(0); 8281 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8282 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8283 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8284 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8285 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8286 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8287 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8288 assert(Op0.getOperand(0).getValueType() == VT && 8289 "Unexpected value type!"); 8290 return Op0.getOperand(0); 8291 } 8292 8293 // This is a target-specific version of a DAGCombine performed in 8294 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8295 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8296 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8297 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8298 !Op0.getNode()->hasOneUse()) 8299 break; 8300 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8301 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8302 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8303 if (Op0.getOpcode() == ISD::FNEG) 8304 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8305 DAG.getConstant(SignBit, DL, VT)); 8306 8307 assert(Op0.getOpcode() == ISD::FABS); 8308 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8309 DAG.getConstant(~SignBit, DL, VT)); 8310 } 8311 case ISD::ADD: 8312 return performADDCombine(N, DAG, Subtarget); 8313 case ISD::SUB: 8314 return performSUBCombine(N, DAG); 8315 case ISD::AND: 8316 return performANDCombine(N, DAG); 8317 case ISD::OR: 8318 return performORCombine(N, DAG, Subtarget); 8319 case ISD::XOR: 8320 return performXORCombine(N, DAG); 8321 case ISD::SIGN_EXTEND_INREG: 8322 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8323 case ISD::ZERO_EXTEND: 8324 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8325 // type legalization. This is safe because fp_to_uint produces poison if 8326 // it overflows. 8327 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8328 SDValue Src = N->getOperand(0); 8329 if (Src.getOpcode() == ISD::FP_TO_UINT && 8330 isTypeLegal(Src.getOperand(0).getValueType())) 8331 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8332 Src.getOperand(0)); 8333 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8334 isTypeLegal(Src.getOperand(1).getValueType())) { 8335 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8336 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8337 Src.getOperand(0), Src.getOperand(1)); 8338 DCI.CombineTo(N, Res); 8339 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8340 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8341 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8342 } 8343 } 8344 return SDValue(); 8345 case RISCVISD::SELECT_CC: { 8346 // Transform 8347 SDValue LHS = N->getOperand(0); 8348 SDValue RHS = N->getOperand(1); 8349 SDValue TrueV = N->getOperand(3); 8350 SDValue FalseV = N->getOperand(4); 8351 8352 // If the True and False values are the same, we don't need a select_cc. 8353 if (TrueV == FalseV) 8354 return TrueV; 8355 8356 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8357 if (!ISD::isIntEqualitySetCC(CCVal)) 8358 break; 8359 8360 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8361 // (select_cc X, Y, lt, trueV, falseV) 8362 // Sometimes the setcc is introduced after select_cc has been formed. 8363 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8364 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8365 // If we're looking for eq 0 instead of ne 0, we need to invert the 8366 // condition. 8367 bool Invert = CCVal == ISD::SETEQ; 8368 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8369 if (Invert) 8370 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8371 8372 SDLoc DL(N); 8373 RHS = LHS.getOperand(1); 8374 LHS = LHS.getOperand(0); 8375 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8376 8377 SDValue TargetCC = DAG.getCondCode(CCVal); 8378 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8379 {LHS, RHS, TargetCC, TrueV, FalseV}); 8380 } 8381 8382 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8383 // (select_cc X, Y, eq/ne, trueV, falseV) 8384 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8385 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8386 {LHS.getOperand(0), LHS.getOperand(1), 8387 N->getOperand(2), TrueV, FalseV}); 8388 // (select_cc X, 1, setne, trueV, falseV) -> 8389 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8390 // This can occur when legalizing some floating point comparisons. 8391 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8392 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8393 SDLoc DL(N); 8394 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8395 SDValue TargetCC = DAG.getCondCode(CCVal); 8396 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8397 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8398 {LHS, RHS, TargetCC, TrueV, FalseV}); 8399 } 8400 8401 break; 8402 } 8403 case RISCVISD::BR_CC: { 8404 SDValue LHS = N->getOperand(1); 8405 SDValue RHS = N->getOperand(2); 8406 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8407 if (!ISD::isIntEqualitySetCC(CCVal)) 8408 break; 8409 8410 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8411 // (br_cc X, Y, lt, dest) 8412 // Sometimes the setcc is introduced after br_cc has been formed. 8413 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8414 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8415 // If we're looking for eq 0 instead of ne 0, we need to invert the 8416 // condition. 8417 bool Invert = CCVal == ISD::SETEQ; 8418 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8419 if (Invert) 8420 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8421 8422 SDLoc DL(N); 8423 RHS = LHS.getOperand(1); 8424 LHS = LHS.getOperand(0); 8425 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8426 8427 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8428 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8429 N->getOperand(4)); 8430 } 8431 8432 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8433 // (br_cc X, Y, eq/ne, trueV, falseV) 8434 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8435 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8436 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8437 N->getOperand(3), N->getOperand(4)); 8438 8439 // (br_cc X, 1, setne, br_cc) -> 8440 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8441 // This can occur when legalizing some floating point comparisons. 8442 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8443 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8444 SDLoc DL(N); 8445 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8446 SDValue TargetCC = DAG.getCondCode(CCVal); 8447 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8448 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8449 N->getOperand(0), LHS, RHS, TargetCC, 8450 N->getOperand(4)); 8451 } 8452 break; 8453 } 8454 case ISD::BITREVERSE: 8455 return performBITREVERSECombine(N, DAG, Subtarget); 8456 case ISD::FP_TO_SINT: 8457 case ISD::FP_TO_UINT: 8458 return performFP_TO_INTCombine(N, DCI, Subtarget); 8459 case ISD::FP_TO_SINT_SAT: 8460 case ISD::FP_TO_UINT_SAT: 8461 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8462 case ISD::FCOPYSIGN: { 8463 EVT VT = N->getValueType(0); 8464 if (!VT.isVector()) 8465 break; 8466 // There is a form of VFSGNJ which injects the negated sign of its second 8467 // operand. Try and bubble any FNEG up after the extend/round to produce 8468 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8469 // TRUNC=1. 8470 SDValue In2 = N->getOperand(1); 8471 // Avoid cases where the extend/round has multiple uses, as duplicating 8472 // those is typically more expensive than removing a fneg. 8473 if (!In2.hasOneUse()) 8474 break; 8475 if (In2.getOpcode() != ISD::FP_EXTEND && 8476 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8477 break; 8478 In2 = In2.getOperand(0); 8479 if (In2.getOpcode() != ISD::FNEG) 8480 break; 8481 SDLoc DL(N); 8482 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8483 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8484 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8485 } 8486 case ISD::MGATHER: 8487 case ISD::MSCATTER: 8488 case ISD::VP_GATHER: 8489 case ISD::VP_SCATTER: { 8490 if (!DCI.isBeforeLegalize()) 8491 break; 8492 SDValue Index, ScaleOp; 8493 bool IsIndexScaled = false; 8494 bool IsIndexSigned = false; 8495 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8496 Index = VPGSN->getIndex(); 8497 ScaleOp = VPGSN->getScale(); 8498 IsIndexScaled = VPGSN->isIndexScaled(); 8499 IsIndexSigned = VPGSN->isIndexSigned(); 8500 } else { 8501 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8502 Index = MGSN->getIndex(); 8503 ScaleOp = MGSN->getScale(); 8504 IsIndexScaled = MGSN->isIndexScaled(); 8505 IsIndexSigned = MGSN->isIndexSigned(); 8506 } 8507 EVT IndexVT = Index.getValueType(); 8508 MVT XLenVT = Subtarget.getXLenVT(); 8509 // RISCV indexed loads only support the "unsigned unscaled" addressing 8510 // mode, so anything else must be manually legalized. 8511 bool NeedsIdxLegalization = 8512 IsIndexScaled || 8513 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8514 if (!NeedsIdxLegalization) 8515 break; 8516 8517 SDLoc DL(N); 8518 8519 // Any index legalization should first promote to XLenVT, so we don't lose 8520 // bits when scaling. This may create an illegal index type so we let 8521 // LLVM's legalization take care of the splitting. 8522 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8523 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8524 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8525 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8526 DL, IndexVT, Index); 8527 } 8528 8529 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8530 if (IsIndexScaled && Scale != 1) { 8531 // Manually scale the indices by the element size. 8532 // TODO: Sanitize the scale operand here? 8533 // TODO: For VP nodes, should we use VP_SHL here? 8534 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8535 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8536 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8537 } 8538 8539 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8540 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8541 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8542 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8543 VPGN->getScale(), VPGN->getMask(), 8544 VPGN->getVectorLength()}, 8545 VPGN->getMemOperand(), NewIndexTy); 8546 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8547 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8548 {VPSN->getChain(), VPSN->getValue(), 8549 VPSN->getBasePtr(), Index, VPSN->getScale(), 8550 VPSN->getMask(), VPSN->getVectorLength()}, 8551 VPSN->getMemOperand(), NewIndexTy); 8552 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8553 return DAG.getMaskedGather( 8554 N->getVTList(), MGN->getMemoryVT(), DL, 8555 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8556 MGN->getBasePtr(), Index, MGN->getScale()}, 8557 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8558 const auto *MSN = cast<MaskedScatterSDNode>(N); 8559 return DAG.getMaskedScatter( 8560 N->getVTList(), MSN->getMemoryVT(), DL, 8561 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8562 Index, MSN->getScale()}, 8563 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8564 } 8565 case RISCVISD::SRA_VL: 8566 case RISCVISD::SRL_VL: 8567 case RISCVISD::SHL_VL: { 8568 SDValue ShAmt = N->getOperand(1); 8569 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8570 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8571 SDLoc DL(N); 8572 SDValue VL = N->getOperand(3); 8573 EVT VT = N->getValueType(0); 8574 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8575 ShAmt.getOperand(1), VL); 8576 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8577 N->getOperand(2), N->getOperand(3)); 8578 } 8579 break; 8580 } 8581 case ISD::SRA: 8582 case ISD::SRL: 8583 case ISD::SHL: { 8584 SDValue ShAmt = N->getOperand(1); 8585 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8586 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8587 SDLoc DL(N); 8588 EVT VT = N->getValueType(0); 8589 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8590 ShAmt.getOperand(1), 8591 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8592 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8593 } 8594 break; 8595 } 8596 case RISCVISD::ADD_VL: 8597 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8598 return V; 8599 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8600 case RISCVISD::SUB_VL: 8601 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8602 case RISCVISD::VWADD_W_VL: 8603 case RISCVISD::VWADDU_W_VL: 8604 case RISCVISD::VWSUB_W_VL: 8605 case RISCVISD::VWSUBU_W_VL: 8606 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8607 case RISCVISD::MUL_VL: 8608 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8609 return V; 8610 // Mul is commutative. 8611 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8612 case ISD::STORE: { 8613 auto *Store = cast<StoreSDNode>(N); 8614 SDValue Val = Store->getValue(); 8615 // Combine store of vmv.x.s to vse with VL of 1. 8616 // FIXME: Support FP. 8617 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8618 SDValue Src = Val.getOperand(0); 8619 EVT VecVT = Src.getValueType(); 8620 EVT MemVT = Store->getMemoryVT(); 8621 // The memory VT and the element type must match. 8622 if (VecVT.getVectorElementType() == MemVT) { 8623 SDLoc DL(N); 8624 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8625 return DAG.getStoreVP( 8626 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8627 DAG.getConstant(1, DL, MaskVT), 8628 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8629 Store->getMemOperand(), Store->getAddressingMode(), 8630 Store->isTruncatingStore(), /*IsCompress*/ false); 8631 } 8632 } 8633 8634 break; 8635 } 8636 case ISD::SPLAT_VECTOR: { 8637 EVT VT = N->getValueType(0); 8638 // Only perform this combine on legal MVT types. 8639 if (!isTypeLegal(VT)) 8640 break; 8641 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8642 DAG, Subtarget)) 8643 return Gather; 8644 break; 8645 } 8646 case RISCVISD::VMV_V_X_VL: { 8647 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8648 // scalar input. 8649 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8650 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8651 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8652 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8653 return SDValue(N, 0); 8654 8655 break; 8656 } 8657 case ISD::INTRINSIC_WO_CHAIN: { 8658 unsigned IntNo = N->getConstantOperandVal(0); 8659 switch (IntNo) { 8660 // By default we do not combine any intrinsic. 8661 default: 8662 return SDValue(); 8663 case Intrinsic::riscv_vcpop: 8664 case Intrinsic::riscv_vcpop_mask: 8665 case Intrinsic::riscv_vfirst: 8666 case Intrinsic::riscv_vfirst_mask: { 8667 SDValue VL = N->getOperand(2); 8668 if (IntNo == Intrinsic::riscv_vcpop_mask || 8669 IntNo == Intrinsic::riscv_vfirst_mask) 8670 VL = N->getOperand(3); 8671 if (!isNullConstant(VL)) 8672 return SDValue(); 8673 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8674 SDLoc DL(N); 8675 EVT VT = N->getValueType(0); 8676 if (IntNo == Intrinsic::riscv_vfirst || 8677 IntNo == Intrinsic::riscv_vfirst_mask) 8678 return DAG.getConstant(-1, DL, VT); 8679 return DAG.getConstant(0, DL, VT); 8680 } 8681 } 8682 } 8683 } 8684 8685 return SDValue(); 8686 } 8687 8688 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8689 const SDNode *N, CombineLevel Level) const { 8690 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8691 // materialised in fewer instructions than `(OP _, c1)`: 8692 // 8693 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8694 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8695 SDValue N0 = N->getOperand(0); 8696 EVT Ty = N0.getValueType(); 8697 if (Ty.isScalarInteger() && 8698 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8699 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8700 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8701 if (C1 && C2) { 8702 const APInt &C1Int = C1->getAPIntValue(); 8703 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8704 8705 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8706 // and the combine should happen, to potentially allow further combines 8707 // later. 8708 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8709 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8710 return true; 8711 8712 // We can materialise `c1` in an add immediate, so it's "free", and the 8713 // combine should be prevented. 8714 if (C1Int.getMinSignedBits() <= 64 && 8715 isLegalAddImmediate(C1Int.getSExtValue())) 8716 return false; 8717 8718 // Neither constant will fit into an immediate, so find materialisation 8719 // costs. 8720 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8721 Subtarget.getFeatureBits(), 8722 /*CompressionCost*/true); 8723 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8724 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8725 /*CompressionCost*/true); 8726 8727 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8728 // combine should be prevented. 8729 if (C1Cost < ShiftedC1Cost) 8730 return false; 8731 } 8732 } 8733 return true; 8734 } 8735 8736 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8737 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8738 TargetLoweringOpt &TLO) const { 8739 // Delay this optimization as late as possible. 8740 if (!TLO.LegalOps) 8741 return false; 8742 8743 EVT VT = Op.getValueType(); 8744 if (VT.isVector()) 8745 return false; 8746 8747 // Only handle AND for now. 8748 if (Op.getOpcode() != ISD::AND) 8749 return false; 8750 8751 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8752 if (!C) 8753 return false; 8754 8755 const APInt &Mask = C->getAPIntValue(); 8756 8757 // Clear all non-demanded bits initially. 8758 APInt ShrunkMask = Mask & DemandedBits; 8759 8760 // Try to make a smaller immediate by setting undemanded bits. 8761 8762 APInt ExpandedMask = Mask | ~DemandedBits; 8763 8764 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8765 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8766 }; 8767 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8768 if (NewMask == Mask) 8769 return true; 8770 SDLoc DL(Op); 8771 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8772 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8773 return TLO.CombineTo(Op, NewOp); 8774 }; 8775 8776 // If the shrunk mask fits in sign extended 12 bits, let the target 8777 // independent code apply it. 8778 if (ShrunkMask.isSignedIntN(12)) 8779 return false; 8780 8781 // Preserve (and X, 0xffff) when zext.h is supported. 8782 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8783 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8784 if (IsLegalMask(NewMask)) 8785 return UseMask(NewMask); 8786 } 8787 8788 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8789 if (VT == MVT::i64) { 8790 APInt NewMask = APInt(64, 0xffffffff); 8791 if (IsLegalMask(NewMask)) 8792 return UseMask(NewMask); 8793 } 8794 8795 // For the remaining optimizations, we need to be able to make a negative 8796 // number through a combination of mask and undemanded bits. 8797 if (!ExpandedMask.isNegative()) 8798 return false; 8799 8800 // What is the fewest number of bits we need to represent the negative number. 8801 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8802 8803 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8804 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8805 APInt NewMask = ShrunkMask; 8806 if (MinSignedBits <= 12) 8807 NewMask.setBitsFrom(11); 8808 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8809 NewMask.setBitsFrom(31); 8810 else 8811 return false; 8812 8813 // Check that our new mask is a subset of the demanded mask. 8814 assert(IsLegalMask(NewMask)); 8815 return UseMask(NewMask); 8816 } 8817 8818 static void computeGREV(APInt &Src, unsigned ShAmt) { 8819 ShAmt &= Src.getBitWidth() - 1; 8820 uint64_t x = Src.getZExtValue(); 8821 if (ShAmt & 1) 8822 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8823 if (ShAmt & 2) 8824 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8825 if (ShAmt & 4) 8826 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8827 if (ShAmt & 8) 8828 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8829 if (ShAmt & 16) 8830 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8831 if (ShAmt & 32) 8832 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8833 Src = x; 8834 } 8835 8836 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8837 KnownBits &Known, 8838 const APInt &DemandedElts, 8839 const SelectionDAG &DAG, 8840 unsigned Depth) const { 8841 unsigned BitWidth = Known.getBitWidth(); 8842 unsigned Opc = Op.getOpcode(); 8843 assert((Opc >= ISD::BUILTIN_OP_END || 8844 Opc == ISD::INTRINSIC_WO_CHAIN || 8845 Opc == ISD::INTRINSIC_W_CHAIN || 8846 Opc == ISD::INTRINSIC_VOID) && 8847 "Should use MaskedValueIsZero if you don't know whether Op" 8848 " is a target node!"); 8849 8850 Known.resetAll(); 8851 switch (Opc) { 8852 default: break; 8853 case RISCVISD::SELECT_CC: { 8854 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8855 // If we don't know any bits, early out. 8856 if (Known.isUnknown()) 8857 break; 8858 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8859 8860 // Only known if known in both the LHS and RHS. 8861 Known = KnownBits::commonBits(Known, Known2); 8862 break; 8863 } 8864 case RISCVISD::REMUW: { 8865 KnownBits Known2; 8866 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8867 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8868 // We only care about the lower 32 bits. 8869 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8870 // Restore the original width by sign extending. 8871 Known = Known.sext(BitWidth); 8872 break; 8873 } 8874 case RISCVISD::DIVUW: { 8875 KnownBits Known2; 8876 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8877 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8878 // We only care about the lower 32 bits. 8879 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8880 // Restore the original width by sign extending. 8881 Known = Known.sext(BitWidth); 8882 break; 8883 } 8884 case RISCVISD::CTZW: { 8885 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8886 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8887 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8888 Known.Zero.setBitsFrom(LowBits); 8889 break; 8890 } 8891 case RISCVISD::CLZW: { 8892 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8893 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8894 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8895 Known.Zero.setBitsFrom(LowBits); 8896 break; 8897 } 8898 case RISCVISD::GREV: { 8899 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8900 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8901 unsigned ShAmt = C->getZExtValue(); 8902 computeGREV(Known.Zero, ShAmt); 8903 computeGREV(Known.One, ShAmt); 8904 } 8905 break; 8906 } 8907 case RISCVISD::READ_VLENB: { 8908 // If we know the minimum VLen from Zvl extensions, we can use that to 8909 // determine the trailing zeros of VLENB. 8910 // FIXME: Limit to 128 bit vectors until we have more testing. 8911 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8912 if (MinVLenB > 0) 8913 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8914 // We assume VLENB is no more than 65536 / 8 bytes. 8915 Known.Zero.setBitsFrom(14); 8916 break; 8917 } 8918 case ISD::INTRINSIC_W_CHAIN: 8919 case ISD::INTRINSIC_WO_CHAIN: { 8920 unsigned IntNo = 8921 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8922 switch (IntNo) { 8923 default: 8924 // We can't do anything for most intrinsics. 8925 break; 8926 case Intrinsic::riscv_vsetvli: 8927 case Intrinsic::riscv_vsetvlimax: 8928 case Intrinsic::riscv_vsetvli_opt: 8929 case Intrinsic::riscv_vsetvlimax_opt: 8930 // Assume that VL output is positive and would fit in an int32_t. 8931 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8932 if (BitWidth >= 32) 8933 Known.Zero.setBitsFrom(31); 8934 break; 8935 } 8936 break; 8937 } 8938 } 8939 } 8940 8941 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8942 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8943 unsigned Depth) const { 8944 switch (Op.getOpcode()) { 8945 default: 8946 break; 8947 case RISCVISD::SELECT_CC: { 8948 unsigned Tmp = 8949 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8950 if (Tmp == 1) return 1; // Early out. 8951 unsigned Tmp2 = 8952 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8953 return std::min(Tmp, Tmp2); 8954 } 8955 case RISCVISD::SLLW: 8956 case RISCVISD::SRAW: 8957 case RISCVISD::SRLW: 8958 case RISCVISD::DIVW: 8959 case RISCVISD::DIVUW: 8960 case RISCVISD::REMUW: 8961 case RISCVISD::ROLW: 8962 case RISCVISD::RORW: 8963 case RISCVISD::GREVW: 8964 case RISCVISD::GORCW: 8965 case RISCVISD::FSLW: 8966 case RISCVISD::FSRW: 8967 case RISCVISD::SHFLW: 8968 case RISCVISD::UNSHFLW: 8969 case RISCVISD::BCOMPRESSW: 8970 case RISCVISD::BDECOMPRESSW: 8971 case RISCVISD::BFPW: 8972 case RISCVISD::FCVT_W_RV64: 8973 case RISCVISD::FCVT_WU_RV64: 8974 case RISCVISD::STRICT_FCVT_W_RV64: 8975 case RISCVISD::STRICT_FCVT_WU_RV64: 8976 // TODO: As the result is sign-extended, this is conservatively correct. A 8977 // more precise answer could be calculated for SRAW depending on known 8978 // bits in the shift amount. 8979 return 33; 8980 case RISCVISD::SHFL: 8981 case RISCVISD::UNSHFL: { 8982 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8983 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8984 // will stay within the upper 32 bits. If there were more than 32 sign bits 8985 // before there will be at least 33 sign bits after. 8986 if (Op.getValueType() == MVT::i64 && 8987 isa<ConstantSDNode>(Op.getOperand(1)) && 8988 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8989 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8990 if (Tmp > 32) 8991 return 33; 8992 } 8993 break; 8994 } 8995 case RISCVISD::VMV_X_S: { 8996 // The number of sign bits of the scalar result is computed by obtaining the 8997 // element type of the input vector operand, subtracting its width from the 8998 // XLEN, and then adding one (sign bit within the element type). If the 8999 // element type is wider than XLen, the least-significant XLEN bits are 9000 // taken. 9001 unsigned XLen = Subtarget.getXLen(); 9002 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9003 if (EltBits <= XLen) 9004 return XLen - EltBits + 1; 9005 break; 9006 } 9007 } 9008 9009 return 1; 9010 } 9011 9012 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9013 MachineBasicBlock *BB) { 9014 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9015 9016 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9017 // Should the count have wrapped while it was being read, we need to try 9018 // again. 9019 // ... 9020 // read: 9021 // rdcycleh x3 # load high word of cycle 9022 // rdcycle x2 # load low word of cycle 9023 // rdcycleh x4 # load high word of cycle 9024 // bne x3, x4, read # check if high word reads match, otherwise try again 9025 // ... 9026 9027 MachineFunction &MF = *BB->getParent(); 9028 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9029 MachineFunction::iterator It = ++BB->getIterator(); 9030 9031 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9032 MF.insert(It, LoopMBB); 9033 9034 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9035 MF.insert(It, DoneMBB); 9036 9037 // Transfer the remainder of BB and its successor edges to DoneMBB. 9038 DoneMBB->splice(DoneMBB->begin(), BB, 9039 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9040 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9041 9042 BB->addSuccessor(LoopMBB); 9043 9044 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9045 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9046 Register LoReg = MI.getOperand(0).getReg(); 9047 Register HiReg = MI.getOperand(1).getReg(); 9048 DebugLoc DL = MI.getDebugLoc(); 9049 9050 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9051 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9052 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9053 .addReg(RISCV::X0); 9054 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9055 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9056 .addReg(RISCV::X0); 9057 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9058 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9059 .addReg(RISCV::X0); 9060 9061 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9062 .addReg(HiReg) 9063 .addReg(ReadAgainReg) 9064 .addMBB(LoopMBB); 9065 9066 LoopMBB->addSuccessor(LoopMBB); 9067 LoopMBB->addSuccessor(DoneMBB); 9068 9069 MI.eraseFromParent(); 9070 9071 return DoneMBB; 9072 } 9073 9074 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9075 MachineBasicBlock *BB) { 9076 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9077 9078 MachineFunction &MF = *BB->getParent(); 9079 DebugLoc DL = MI.getDebugLoc(); 9080 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9081 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9082 Register LoReg = MI.getOperand(0).getReg(); 9083 Register HiReg = MI.getOperand(1).getReg(); 9084 Register SrcReg = MI.getOperand(2).getReg(); 9085 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9086 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9087 9088 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9089 RI); 9090 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9091 MachineMemOperand *MMOLo = 9092 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9093 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9094 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9095 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9096 .addFrameIndex(FI) 9097 .addImm(0) 9098 .addMemOperand(MMOLo); 9099 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9100 .addFrameIndex(FI) 9101 .addImm(4) 9102 .addMemOperand(MMOHi); 9103 MI.eraseFromParent(); // The pseudo instruction is gone now. 9104 return BB; 9105 } 9106 9107 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9108 MachineBasicBlock *BB) { 9109 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9110 "Unexpected instruction"); 9111 9112 MachineFunction &MF = *BB->getParent(); 9113 DebugLoc DL = MI.getDebugLoc(); 9114 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9115 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9116 Register DstReg = MI.getOperand(0).getReg(); 9117 Register LoReg = MI.getOperand(1).getReg(); 9118 Register HiReg = MI.getOperand(2).getReg(); 9119 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9120 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9121 9122 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9123 MachineMemOperand *MMOLo = 9124 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9125 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9126 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9127 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9128 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9129 .addFrameIndex(FI) 9130 .addImm(0) 9131 .addMemOperand(MMOLo); 9132 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9133 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9134 .addFrameIndex(FI) 9135 .addImm(4) 9136 .addMemOperand(MMOHi); 9137 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9138 MI.eraseFromParent(); // The pseudo instruction is gone now. 9139 return BB; 9140 } 9141 9142 static bool isSelectPseudo(MachineInstr &MI) { 9143 switch (MI.getOpcode()) { 9144 default: 9145 return false; 9146 case RISCV::Select_GPR_Using_CC_GPR: 9147 case RISCV::Select_FPR16_Using_CC_GPR: 9148 case RISCV::Select_FPR32_Using_CC_GPR: 9149 case RISCV::Select_FPR64_Using_CC_GPR: 9150 return true; 9151 } 9152 } 9153 9154 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9155 unsigned RelOpcode, unsigned EqOpcode, 9156 const RISCVSubtarget &Subtarget) { 9157 DebugLoc DL = MI.getDebugLoc(); 9158 Register DstReg = MI.getOperand(0).getReg(); 9159 Register Src1Reg = MI.getOperand(1).getReg(); 9160 Register Src2Reg = MI.getOperand(2).getReg(); 9161 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9162 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9163 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9164 9165 // Save the current FFLAGS. 9166 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9167 9168 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9169 .addReg(Src1Reg) 9170 .addReg(Src2Reg); 9171 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9172 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9173 9174 // Restore the FFLAGS. 9175 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9176 .addReg(SavedFFlags, RegState::Kill); 9177 9178 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9179 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9180 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9181 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9182 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9183 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9184 9185 // Erase the pseudoinstruction. 9186 MI.eraseFromParent(); 9187 return BB; 9188 } 9189 9190 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9191 MachineBasicBlock *BB, 9192 const RISCVSubtarget &Subtarget) { 9193 // To "insert" Select_* instructions, we actually have to insert the triangle 9194 // control-flow pattern. The incoming instructions know the destination vreg 9195 // to set, the condition code register to branch on, the true/false values to 9196 // select between, and the condcode to use to select the appropriate branch. 9197 // 9198 // We produce the following control flow: 9199 // HeadMBB 9200 // | \ 9201 // | IfFalseMBB 9202 // | / 9203 // TailMBB 9204 // 9205 // When we find a sequence of selects we attempt to optimize their emission 9206 // by sharing the control flow. Currently we only handle cases where we have 9207 // multiple selects with the exact same condition (same LHS, RHS and CC). 9208 // The selects may be interleaved with other instructions if the other 9209 // instructions meet some requirements we deem safe: 9210 // - They are debug instructions. Otherwise, 9211 // - They do not have side-effects, do not access memory and their inputs do 9212 // not depend on the results of the select pseudo-instructions. 9213 // The TrueV/FalseV operands of the selects cannot depend on the result of 9214 // previous selects in the sequence. 9215 // These conditions could be further relaxed. See the X86 target for a 9216 // related approach and more information. 9217 Register LHS = MI.getOperand(1).getReg(); 9218 Register RHS = MI.getOperand(2).getReg(); 9219 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9220 9221 SmallVector<MachineInstr *, 4> SelectDebugValues; 9222 SmallSet<Register, 4> SelectDests; 9223 SelectDests.insert(MI.getOperand(0).getReg()); 9224 9225 MachineInstr *LastSelectPseudo = &MI; 9226 9227 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9228 SequenceMBBI != E; ++SequenceMBBI) { 9229 if (SequenceMBBI->isDebugInstr()) 9230 continue; 9231 else if (isSelectPseudo(*SequenceMBBI)) { 9232 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9233 SequenceMBBI->getOperand(2).getReg() != RHS || 9234 SequenceMBBI->getOperand(3).getImm() != CC || 9235 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9236 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9237 break; 9238 LastSelectPseudo = &*SequenceMBBI; 9239 SequenceMBBI->collectDebugValues(SelectDebugValues); 9240 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9241 } else { 9242 if (SequenceMBBI->hasUnmodeledSideEffects() || 9243 SequenceMBBI->mayLoadOrStore()) 9244 break; 9245 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9246 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9247 })) 9248 break; 9249 } 9250 } 9251 9252 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9253 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9254 DebugLoc DL = MI.getDebugLoc(); 9255 MachineFunction::iterator I = ++BB->getIterator(); 9256 9257 MachineBasicBlock *HeadMBB = BB; 9258 MachineFunction *F = BB->getParent(); 9259 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9260 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9261 9262 F->insert(I, IfFalseMBB); 9263 F->insert(I, TailMBB); 9264 9265 // Transfer debug instructions associated with the selects to TailMBB. 9266 for (MachineInstr *DebugInstr : SelectDebugValues) { 9267 TailMBB->push_back(DebugInstr->removeFromParent()); 9268 } 9269 9270 // Move all instructions after the sequence to TailMBB. 9271 TailMBB->splice(TailMBB->end(), HeadMBB, 9272 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9273 // Update machine-CFG edges by transferring all successors of the current 9274 // block to the new block which will contain the Phi nodes for the selects. 9275 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9276 // Set the successors for HeadMBB. 9277 HeadMBB->addSuccessor(IfFalseMBB); 9278 HeadMBB->addSuccessor(TailMBB); 9279 9280 // Insert appropriate branch. 9281 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9282 .addReg(LHS) 9283 .addReg(RHS) 9284 .addMBB(TailMBB); 9285 9286 // IfFalseMBB just falls through to TailMBB. 9287 IfFalseMBB->addSuccessor(TailMBB); 9288 9289 // Create PHIs for all of the select pseudo-instructions. 9290 auto SelectMBBI = MI.getIterator(); 9291 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9292 auto InsertionPoint = TailMBB->begin(); 9293 while (SelectMBBI != SelectEnd) { 9294 auto Next = std::next(SelectMBBI); 9295 if (isSelectPseudo(*SelectMBBI)) { 9296 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9297 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9298 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9299 .addReg(SelectMBBI->getOperand(4).getReg()) 9300 .addMBB(HeadMBB) 9301 .addReg(SelectMBBI->getOperand(5).getReg()) 9302 .addMBB(IfFalseMBB); 9303 SelectMBBI->eraseFromParent(); 9304 } 9305 SelectMBBI = Next; 9306 } 9307 9308 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9309 return TailMBB; 9310 } 9311 9312 MachineBasicBlock * 9313 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9314 MachineBasicBlock *BB) const { 9315 switch (MI.getOpcode()) { 9316 default: 9317 llvm_unreachable("Unexpected instr type to insert"); 9318 case RISCV::ReadCycleWide: 9319 assert(!Subtarget.is64Bit() && 9320 "ReadCycleWrite is only to be used on riscv32"); 9321 return emitReadCycleWidePseudo(MI, BB); 9322 case RISCV::Select_GPR_Using_CC_GPR: 9323 case RISCV::Select_FPR16_Using_CC_GPR: 9324 case RISCV::Select_FPR32_Using_CC_GPR: 9325 case RISCV::Select_FPR64_Using_CC_GPR: 9326 return emitSelectPseudo(MI, BB, Subtarget); 9327 case RISCV::BuildPairF64Pseudo: 9328 return emitBuildPairF64Pseudo(MI, BB); 9329 case RISCV::SplitF64Pseudo: 9330 return emitSplitF64Pseudo(MI, BB); 9331 case RISCV::PseudoQuietFLE_H: 9332 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9333 case RISCV::PseudoQuietFLT_H: 9334 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9335 case RISCV::PseudoQuietFLE_S: 9336 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9337 case RISCV::PseudoQuietFLT_S: 9338 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9339 case RISCV::PseudoQuietFLE_D: 9340 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9341 case RISCV::PseudoQuietFLT_D: 9342 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9343 } 9344 } 9345 9346 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9347 SDNode *Node) const { 9348 // Add FRM dependency to any instructions with dynamic rounding mode. 9349 unsigned Opc = MI.getOpcode(); 9350 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9351 if (Idx < 0) 9352 return; 9353 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9354 return; 9355 // If the instruction already reads FRM, don't add another read. 9356 if (MI.readsRegister(RISCV::FRM)) 9357 return; 9358 MI.addOperand( 9359 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9360 } 9361 9362 // Calling Convention Implementation. 9363 // The expectations for frontend ABI lowering vary from target to target. 9364 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9365 // details, but this is a longer term goal. For now, we simply try to keep the 9366 // role of the frontend as simple and well-defined as possible. The rules can 9367 // be summarised as: 9368 // * Never split up large scalar arguments. We handle them here. 9369 // * If a hardfloat calling convention is being used, and the struct may be 9370 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9371 // available, then pass as two separate arguments. If either the GPRs or FPRs 9372 // are exhausted, then pass according to the rule below. 9373 // * If a struct could never be passed in registers or directly in a stack 9374 // slot (as it is larger than 2*XLEN and the floating point rules don't 9375 // apply), then pass it using a pointer with the byval attribute. 9376 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9377 // word-sized array or a 2*XLEN scalar (depending on alignment). 9378 // * The frontend can determine whether a struct is returned by reference or 9379 // not based on its size and fields. If it will be returned by reference, the 9380 // frontend must modify the prototype so a pointer with the sret annotation is 9381 // passed as the first argument. This is not necessary for large scalar 9382 // returns. 9383 // * Struct return values and varargs should be coerced to structs containing 9384 // register-size fields in the same situations they would be for fixed 9385 // arguments. 9386 9387 static const MCPhysReg ArgGPRs[] = { 9388 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9389 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9390 }; 9391 static const MCPhysReg ArgFPR16s[] = { 9392 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9393 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9394 }; 9395 static const MCPhysReg ArgFPR32s[] = { 9396 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9397 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9398 }; 9399 static const MCPhysReg ArgFPR64s[] = { 9400 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9401 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9402 }; 9403 // This is an interim calling convention and it may be changed in the future. 9404 static const MCPhysReg ArgVRs[] = { 9405 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9406 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9407 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9408 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9409 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9410 RISCV::V20M2, RISCV::V22M2}; 9411 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9412 RISCV::V20M4}; 9413 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9414 9415 // Pass a 2*XLEN argument that has been split into two XLEN values through 9416 // registers or the stack as necessary. 9417 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9418 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9419 MVT ValVT2, MVT LocVT2, 9420 ISD::ArgFlagsTy ArgFlags2) { 9421 unsigned XLenInBytes = XLen / 8; 9422 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9423 // At least one half can be passed via register. 9424 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9425 VA1.getLocVT(), CCValAssign::Full)); 9426 } else { 9427 // Both halves must be passed on the stack, with proper alignment. 9428 Align StackAlign = 9429 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9430 State.addLoc( 9431 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9432 State.AllocateStack(XLenInBytes, StackAlign), 9433 VA1.getLocVT(), CCValAssign::Full)); 9434 State.addLoc(CCValAssign::getMem( 9435 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9436 LocVT2, CCValAssign::Full)); 9437 return false; 9438 } 9439 9440 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9441 // The second half can also be passed via register. 9442 State.addLoc( 9443 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9444 } else { 9445 // The second half is passed via the stack, without additional alignment. 9446 State.addLoc(CCValAssign::getMem( 9447 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9448 LocVT2, CCValAssign::Full)); 9449 } 9450 9451 return false; 9452 } 9453 9454 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9455 Optional<unsigned> FirstMaskArgument, 9456 CCState &State, const RISCVTargetLowering &TLI) { 9457 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9458 if (RC == &RISCV::VRRegClass) { 9459 // Assign the first mask argument to V0. 9460 // This is an interim calling convention and it may be changed in the 9461 // future. 9462 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9463 return State.AllocateReg(RISCV::V0); 9464 return State.AllocateReg(ArgVRs); 9465 } 9466 if (RC == &RISCV::VRM2RegClass) 9467 return State.AllocateReg(ArgVRM2s); 9468 if (RC == &RISCV::VRM4RegClass) 9469 return State.AllocateReg(ArgVRM4s); 9470 if (RC == &RISCV::VRM8RegClass) 9471 return State.AllocateReg(ArgVRM8s); 9472 llvm_unreachable("Unhandled register class for ValueType"); 9473 } 9474 9475 // Implements the RISC-V calling convention. Returns true upon failure. 9476 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9477 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9478 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9479 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9480 Optional<unsigned> FirstMaskArgument) { 9481 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9482 assert(XLen == 32 || XLen == 64); 9483 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9484 9485 // Any return value split in to more than two values can't be returned 9486 // directly. Vectors are returned via the available vector registers. 9487 if (!LocVT.isVector() && IsRet && ValNo > 1) 9488 return true; 9489 9490 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9491 // variadic argument, or if no F16/F32 argument registers are available. 9492 bool UseGPRForF16_F32 = true; 9493 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9494 // variadic argument, or if no F64 argument registers are available. 9495 bool UseGPRForF64 = true; 9496 9497 switch (ABI) { 9498 default: 9499 llvm_unreachable("Unexpected ABI"); 9500 case RISCVABI::ABI_ILP32: 9501 case RISCVABI::ABI_LP64: 9502 break; 9503 case RISCVABI::ABI_ILP32F: 9504 case RISCVABI::ABI_LP64F: 9505 UseGPRForF16_F32 = !IsFixed; 9506 break; 9507 case RISCVABI::ABI_ILP32D: 9508 case RISCVABI::ABI_LP64D: 9509 UseGPRForF16_F32 = !IsFixed; 9510 UseGPRForF64 = !IsFixed; 9511 break; 9512 } 9513 9514 // FPR16, FPR32, and FPR64 alias each other. 9515 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9516 UseGPRForF16_F32 = true; 9517 UseGPRForF64 = true; 9518 } 9519 9520 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9521 // similar local variables rather than directly checking against the target 9522 // ABI. 9523 9524 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9525 LocVT = XLenVT; 9526 LocInfo = CCValAssign::BCvt; 9527 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9528 LocVT = MVT::i64; 9529 LocInfo = CCValAssign::BCvt; 9530 } 9531 9532 // If this is a variadic argument, the RISC-V calling convention requires 9533 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9534 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9535 // be used regardless of whether the original argument was split during 9536 // legalisation or not. The argument will not be passed by registers if the 9537 // original type is larger than 2*XLEN, so the register alignment rule does 9538 // not apply. 9539 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9540 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9541 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9542 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9543 // Skip 'odd' register if necessary. 9544 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9545 State.AllocateReg(ArgGPRs); 9546 } 9547 9548 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9549 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9550 State.getPendingArgFlags(); 9551 9552 assert(PendingLocs.size() == PendingArgFlags.size() && 9553 "PendingLocs and PendingArgFlags out of sync"); 9554 9555 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9556 // registers are exhausted. 9557 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9558 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9559 "Can't lower f64 if it is split"); 9560 // Depending on available argument GPRS, f64 may be passed in a pair of 9561 // GPRs, split between a GPR and the stack, or passed completely on the 9562 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9563 // cases. 9564 Register Reg = State.AllocateReg(ArgGPRs); 9565 LocVT = MVT::i32; 9566 if (!Reg) { 9567 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9568 State.addLoc( 9569 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9570 return false; 9571 } 9572 if (!State.AllocateReg(ArgGPRs)) 9573 State.AllocateStack(4, Align(4)); 9574 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9575 return false; 9576 } 9577 9578 // Fixed-length vectors are located in the corresponding scalable-vector 9579 // container types. 9580 if (ValVT.isFixedLengthVector()) 9581 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9582 9583 // Split arguments might be passed indirectly, so keep track of the pending 9584 // values. Split vectors are passed via a mix of registers and indirectly, so 9585 // treat them as we would any other argument. 9586 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9587 LocVT = XLenVT; 9588 LocInfo = CCValAssign::Indirect; 9589 PendingLocs.push_back( 9590 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9591 PendingArgFlags.push_back(ArgFlags); 9592 if (!ArgFlags.isSplitEnd()) { 9593 return false; 9594 } 9595 } 9596 9597 // If the split argument only had two elements, it should be passed directly 9598 // in registers or on the stack. 9599 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9600 PendingLocs.size() <= 2) { 9601 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9602 // Apply the normal calling convention rules to the first half of the 9603 // split argument. 9604 CCValAssign VA = PendingLocs[0]; 9605 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9606 PendingLocs.clear(); 9607 PendingArgFlags.clear(); 9608 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9609 ArgFlags); 9610 } 9611 9612 // Allocate to a register if possible, or else a stack slot. 9613 Register Reg; 9614 unsigned StoreSizeBytes = XLen / 8; 9615 Align StackAlign = Align(XLen / 8); 9616 9617 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9618 Reg = State.AllocateReg(ArgFPR16s); 9619 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9620 Reg = State.AllocateReg(ArgFPR32s); 9621 else if (ValVT == MVT::f64 && !UseGPRForF64) 9622 Reg = State.AllocateReg(ArgFPR64s); 9623 else if (ValVT.isVector()) { 9624 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9625 if (!Reg) { 9626 // For return values, the vector must be passed fully via registers or 9627 // via the stack. 9628 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9629 // but we're using all of them. 9630 if (IsRet) 9631 return true; 9632 // Try using a GPR to pass the address 9633 if ((Reg = State.AllocateReg(ArgGPRs))) { 9634 LocVT = XLenVT; 9635 LocInfo = CCValAssign::Indirect; 9636 } else if (ValVT.isScalableVector()) { 9637 LocVT = XLenVT; 9638 LocInfo = CCValAssign::Indirect; 9639 } else { 9640 // Pass fixed-length vectors on the stack. 9641 LocVT = ValVT; 9642 StoreSizeBytes = ValVT.getStoreSize(); 9643 // Align vectors to their element sizes, being careful for vXi1 9644 // vectors. 9645 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9646 } 9647 } 9648 } else { 9649 Reg = State.AllocateReg(ArgGPRs); 9650 } 9651 9652 unsigned StackOffset = 9653 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9654 9655 // If we reach this point and PendingLocs is non-empty, we must be at the 9656 // end of a split argument that must be passed indirectly. 9657 if (!PendingLocs.empty()) { 9658 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9659 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9660 9661 for (auto &It : PendingLocs) { 9662 if (Reg) 9663 It.convertToReg(Reg); 9664 else 9665 It.convertToMem(StackOffset); 9666 State.addLoc(It); 9667 } 9668 PendingLocs.clear(); 9669 PendingArgFlags.clear(); 9670 return false; 9671 } 9672 9673 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9674 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9675 "Expected an XLenVT or vector types at this stage"); 9676 9677 if (Reg) { 9678 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9679 return false; 9680 } 9681 9682 // When a floating-point value is passed on the stack, no bit-conversion is 9683 // needed. 9684 if (ValVT.isFloatingPoint()) { 9685 LocVT = ValVT; 9686 LocInfo = CCValAssign::Full; 9687 } 9688 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9689 return false; 9690 } 9691 9692 template <typename ArgTy> 9693 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9694 for (const auto &ArgIdx : enumerate(Args)) { 9695 MVT ArgVT = ArgIdx.value().VT; 9696 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9697 return ArgIdx.index(); 9698 } 9699 return None; 9700 } 9701 9702 void RISCVTargetLowering::analyzeInputArgs( 9703 MachineFunction &MF, CCState &CCInfo, 9704 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9705 RISCVCCAssignFn Fn) const { 9706 unsigned NumArgs = Ins.size(); 9707 FunctionType *FType = MF.getFunction().getFunctionType(); 9708 9709 Optional<unsigned> FirstMaskArgument; 9710 if (Subtarget.hasVInstructions()) 9711 FirstMaskArgument = preAssignMask(Ins); 9712 9713 for (unsigned i = 0; i != NumArgs; ++i) { 9714 MVT ArgVT = Ins[i].VT; 9715 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9716 9717 Type *ArgTy = nullptr; 9718 if (IsRet) 9719 ArgTy = FType->getReturnType(); 9720 else if (Ins[i].isOrigArg()) 9721 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9722 9723 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9724 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9725 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9726 FirstMaskArgument)) { 9727 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9728 << EVT(ArgVT).getEVTString() << '\n'); 9729 llvm_unreachable(nullptr); 9730 } 9731 } 9732 } 9733 9734 void RISCVTargetLowering::analyzeOutputArgs( 9735 MachineFunction &MF, CCState &CCInfo, 9736 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9737 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9738 unsigned NumArgs = Outs.size(); 9739 9740 Optional<unsigned> FirstMaskArgument; 9741 if (Subtarget.hasVInstructions()) 9742 FirstMaskArgument = preAssignMask(Outs); 9743 9744 for (unsigned i = 0; i != NumArgs; i++) { 9745 MVT ArgVT = Outs[i].VT; 9746 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9747 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9748 9749 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9750 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9751 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9752 FirstMaskArgument)) { 9753 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9754 << EVT(ArgVT).getEVTString() << "\n"); 9755 llvm_unreachable(nullptr); 9756 } 9757 } 9758 } 9759 9760 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9761 // values. 9762 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9763 const CCValAssign &VA, const SDLoc &DL, 9764 const RISCVSubtarget &Subtarget) { 9765 switch (VA.getLocInfo()) { 9766 default: 9767 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9768 case CCValAssign::Full: 9769 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9770 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9771 break; 9772 case CCValAssign::BCvt: 9773 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9774 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9775 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9776 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9777 else 9778 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9779 break; 9780 } 9781 return Val; 9782 } 9783 9784 // The caller is responsible for loading the full value if the argument is 9785 // passed with CCValAssign::Indirect. 9786 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9787 const CCValAssign &VA, const SDLoc &DL, 9788 const RISCVTargetLowering &TLI) { 9789 MachineFunction &MF = DAG.getMachineFunction(); 9790 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9791 EVT LocVT = VA.getLocVT(); 9792 SDValue Val; 9793 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9794 Register VReg = RegInfo.createVirtualRegister(RC); 9795 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9796 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9797 9798 if (VA.getLocInfo() == CCValAssign::Indirect) 9799 return Val; 9800 9801 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9802 } 9803 9804 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9805 const CCValAssign &VA, const SDLoc &DL, 9806 const RISCVSubtarget &Subtarget) { 9807 EVT LocVT = VA.getLocVT(); 9808 9809 switch (VA.getLocInfo()) { 9810 default: 9811 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9812 case CCValAssign::Full: 9813 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9814 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9815 break; 9816 case CCValAssign::BCvt: 9817 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9818 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9819 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9820 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9821 else 9822 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9823 break; 9824 } 9825 return Val; 9826 } 9827 9828 // The caller is responsible for loading the full value if the argument is 9829 // passed with CCValAssign::Indirect. 9830 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9831 const CCValAssign &VA, const SDLoc &DL) { 9832 MachineFunction &MF = DAG.getMachineFunction(); 9833 MachineFrameInfo &MFI = MF.getFrameInfo(); 9834 EVT LocVT = VA.getLocVT(); 9835 EVT ValVT = VA.getValVT(); 9836 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9837 if (ValVT.isScalableVector()) { 9838 // When the value is a scalable vector, we save the pointer which points to 9839 // the scalable vector value in the stack. The ValVT will be the pointer 9840 // type, instead of the scalable vector type. 9841 ValVT = LocVT; 9842 } 9843 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9844 /*IsImmutable=*/true); 9845 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9846 SDValue Val; 9847 9848 ISD::LoadExtType ExtType; 9849 switch (VA.getLocInfo()) { 9850 default: 9851 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9852 case CCValAssign::Full: 9853 case CCValAssign::Indirect: 9854 case CCValAssign::BCvt: 9855 ExtType = ISD::NON_EXTLOAD; 9856 break; 9857 } 9858 Val = DAG.getExtLoad( 9859 ExtType, DL, LocVT, Chain, FIN, 9860 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9861 return Val; 9862 } 9863 9864 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9865 const CCValAssign &VA, const SDLoc &DL) { 9866 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9867 "Unexpected VA"); 9868 MachineFunction &MF = DAG.getMachineFunction(); 9869 MachineFrameInfo &MFI = MF.getFrameInfo(); 9870 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9871 9872 if (VA.isMemLoc()) { 9873 // f64 is passed on the stack. 9874 int FI = 9875 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9876 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9877 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9878 MachinePointerInfo::getFixedStack(MF, FI)); 9879 } 9880 9881 assert(VA.isRegLoc() && "Expected register VA assignment"); 9882 9883 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9884 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9885 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9886 SDValue Hi; 9887 if (VA.getLocReg() == RISCV::X17) { 9888 // Second half of f64 is passed on the stack. 9889 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9890 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9891 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9892 MachinePointerInfo::getFixedStack(MF, FI)); 9893 } else { 9894 // Second half of f64 is passed in another GPR. 9895 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9896 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9897 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9898 } 9899 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9900 } 9901 9902 // FastCC has less than 1% performance improvement for some particular 9903 // benchmark. But theoretically, it may has benenfit for some cases. 9904 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9905 unsigned ValNo, MVT ValVT, MVT LocVT, 9906 CCValAssign::LocInfo LocInfo, 9907 ISD::ArgFlagsTy ArgFlags, CCState &State, 9908 bool IsFixed, bool IsRet, Type *OrigTy, 9909 const RISCVTargetLowering &TLI, 9910 Optional<unsigned> FirstMaskArgument) { 9911 9912 // X5 and X6 might be used for save-restore libcall. 9913 static const MCPhysReg GPRList[] = { 9914 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9915 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9916 RISCV::X29, RISCV::X30, RISCV::X31}; 9917 9918 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9919 if (unsigned Reg = State.AllocateReg(GPRList)) { 9920 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9921 return false; 9922 } 9923 } 9924 9925 if (LocVT == MVT::f16) { 9926 static const MCPhysReg FPR16List[] = { 9927 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9928 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9929 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9930 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9931 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9932 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9933 return false; 9934 } 9935 } 9936 9937 if (LocVT == MVT::f32) { 9938 static const MCPhysReg FPR32List[] = { 9939 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9940 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9941 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9942 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9943 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9944 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9945 return false; 9946 } 9947 } 9948 9949 if (LocVT == MVT::f64) { 9950 static const MCPhysReg FPR64List[] = { 9951 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9952 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9953 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9954 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9955 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9956 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9957 return false; 9958 } 9959 } 9960 9961 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9962 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9963 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9964 return false; 9965 } 9966 9967 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9968 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9969 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9970 return false; 9971 } 9972 9973 if (LocVT.isVector()) { 9974 if (unsigned Reg = 9975 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9976 // Fixed-length vectors are located in the corresponding scalable-vector 9977 // container types. 9978 if (ValVT.isFixedLengthVector()) 9979 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9980 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9981 } else { 9982 // Try and pass the address via a "fast" GPR. 9983 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9984 LocInfo = CCValAssign::Indirect; 9985 LocVT = TLI.getSubtarget().getXLenVT(); 9986 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9987 } else if (ValVT.isFixedLengthVector()) { 9988 auto StackAlign = 9989 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9990 unsigned StackOffset = 9991 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9992 State.addLoc( 9993 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9994 } else { 9995 // Can't pass scalable vectors on the stack. 9996 return true; 9997 } 9998 } 9999 10000 return false; 10001 } 10002 10003 return true; // CC didn't match. 10004 } 10005 10006 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10007 CCValAssign::LocInfo LocInfo, 10008 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10009 10010 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10011 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10012 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10013 static const MCPhysReg GPRList[] = { 10014 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10015 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10016 if (unsigned Reg = State.AllocateReg(GPRList)) { 10017 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10018 return false; 10019 } 10020 } 10021 10022 if (LocVT == MVT::f32) { 10023 // Pass in STG registers: F1, ..., F6 10024 // fs0 ... fs5 10025 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10026 RISCV::F18_F, RISCV::F19_F, 10027 RISCV::F20_F, RISCV::F21_F}; 10028 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10029 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10030 return false; 10031 } 10032 } 10033 10034 if (LocVT == MVT::f64) { 10035 // Pass in STG registers: D1, ..., D6 10036 // fs6 ... fs11 10037 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10038 RISCV::F24_D, RISCV::F25_D, 10039 RISCV::F26_D, RISCV::F27_D}; 10040 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10041 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10042 return false; 10043 } 10044 } 10045 10046 report_fatal_error("No registers left in GHC calling convention"); 10047 return true; 10048 } 10049 10050 // Transform physical registers into virtual registers. 10051 SDValue RISCVTargetLowering::LowerFormalArguments( 10052 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10053 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10054 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10055 10056 MachineFunction &MF = DAG.getMachineFunction(); 10057 10058 switch (CallConv) { 10059 default: 10060 report_fatal_error("Unsupported calling convention"); 10061 case CallingConv::C: 10062 case CallingConv::Fast: 10063 break; 10064 case CallingConv::GHC: 10065 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10066 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10067 report_fatal_error( 10068 "GHC calling convention requires the F and D instruction set extensions"); 10069 } 10070 10071 const Function &Func = MF.getFunction(); 10072 if (Func.hasFnAttribute("interrupt")) { 10073 if (!Func.arg_empty()) 10074 report_fatal_error( 10075 "Functions with the interrupt attribute cannot have arguments!"); 10076 10077 StringRef Kind = 10078 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10079 10080 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10081 report_fatal_error( 10082 "Function interrupt attribute argument not supported!"); 10083 } 10084 10085 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10086 MVT XLenVT = Subtarget.getXLenVT(); 10087 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10088 // Used with vargs to acumulate store chains. 10089 std::vector<SDValue> OutChains; 10090 10091 // Assign locations to all of the incoming arguments. 10092 SmallVector<CCValAssign, 16> ArgLocs; 10093 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10094 10095 if (CallConv == CallingConv::GHC) 10096 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10097 else 10098 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10099 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10100 : CC_RISCV); 10101 10102 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10103 CCValAssign &VA = ArgLocs[i]; 10104 SDValue ArgValue; 10105 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10106 // case. 10107 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10108 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10109 else if (VA.isRegLoc()) 10110 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10111 else 10112 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10113 10114 if (VA.getLocInfo() == CCValAssign::Indirect) { 10115 // If the original argument was split and passed by reference (e.g. i128 10116 // on RV32), we need to load all parts of it here (using the same 10117 // address). Vectors may be partly split to registers and partly to the 10118 // stack, in which case the base address is partly offset and subsequent 10119 // stores are relative to that. 10120 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10121 MachinePointerInfo())); 10122 unsigned ArgIndex = Ins[i].OrigArgIndex; 10123 unsigned ArgPartOffset = Ins[i].PartOffset; 10124 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10125 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10126 CCValAssign &PartVA = ArgLocs[i + 1]; 10127 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10128 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10129 if (PartVA.getValVT().isScalableVector()) 10130 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10131 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10132 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10133 MachinePointerInfo())); 10134 ++i; 10135 } 10136 continue; 10137 } 10138 InVals.push_back(ArgValue); 10139 } 10140 10141 if (IsVarArg) { 10142 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10143 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10144 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10145 MachineFrameInfo &MFI = MF.getFrameInfo(); 10146 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10147 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10148 10149 // Offset of the first variable argument from stack pointer, and size of 10150 // the vararg save area. For now, the varargs save area is either zero or 10151 // large enough to hold a0-a7. 10152 int VaArgOffset, VarArgsSaveSize; 10153 10154 // If all registers are allocated, then all varargs must be passed on the 10155 // stack and we don't need to save any argregs. 10156 if (ArgRegs.size() == Idx) { 10157 VaArgOffset = CCInfo.getNextStackOffset(); 10158 VarArgsSaveSize = 0; 10159 } else { 10160 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10161 VaArgOffset = -VarArgsSaveSize; 10162 } 10163 10164 // Record the frame index of the first variable argument 10165 // which is a value necessary to VASTART. 10166 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10167 RVFI->setVarArgsFrameIndex(FI); 10168 10169 // If saving an odd number of registers then create an extra stack slot to 10170 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10171 // offsets to even-numbered registered remain 2*XLEN-aligned. 10172 if (Idx % 2) { 10173 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10174 VarArgsSaveSize += XLenInBytes; 10175 } 10176 10177 // Copy the integer registers that may have been used for passing varargs 10178 // to the vararg save area. 10179 for (unsigned I = Idx; I < ArgRegs.size(); 10180 ++I, VaArgOffset += XLenInBytes) { 10181 const Register Reg = RegInfo.createVirtualRegister(RC); 10182 RegInfo.addLiveIn(ArgRegs[I], Reg); 10183 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10184 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10185 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10186 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10187 MachinePointerInfo::getFixedStack(MF, FI)); 10188 cast<StoreSDNode>(Store.getNode()) 10189 ->getMemOperand() 10190 ->setValue((Value *)nullptr); 10191 OutChains.push_back(Store); 10192 } 10193 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10194 } 10195 10196 // All stores are grouped in one node to allow the matching between 10197 // the size of Ins and InVals. This only happens for vararg functions. 10198 if (!OutChains.empty()) { 10199 OutChains.push_back(Chain); 10200 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10201 } 10202 10203 return Chain; 10204 } 10205 10206 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10207 /// for tail call optimization. 10208 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10209 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10210 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10211 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10212 10213 auto &Callee = CLI.Callee; 10214 auto CalleeCC = CLI.CallConv; 10215 auto &Outs = CLI.Outs; 10216 auto &Caller = MF.getFunction(); 10217 auto CallerCC = Caller.getCallingConv(); 10218 10219 // Exception-handling functions need a special set of instructions to 10220 // indicate a return to the hardware. Tail-calling another function would 10221 // probably break this. 10222 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10223 // should be expanded as new function attributes are introduced. 10224 if (Caller.hasFnAttribute("interrupt")) 10225 return false; 10226 10227 // Do not tail call opt if the stack is used to pass parameters. 10228 if (CCInfo.getNextStackOffset() != 0) 10229 return false; 10230 10231 // Do not tail call opt if any parameters need to be passed indirectly. 10232 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10233 // passed indirectly. So the address of the value will be passed in a 10234 // register, or if not available, then the address is put on the stack. In 10235 // order to pass indirectly, space on the stack often needs to be allocated 10236 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10237 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10238 // are passed CCValAssign::Indirect. 10239 for (auto &VA : ArgLocs) 10240 if (VA.getLocInfo() == CCValAssign::Indirect) 10241 return false; 10242 10243 // Do not tail call opt if either caller or callee uses struct return 10244 // semantics. 10245 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10246 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10247 if (IsCallerStructRet || IsCalleeStructRet) 10248 return false; 10249 10250 // Externally-defined functions with weak linkage should not be 10251 // tail-called. The behaviour of branch instructions in this situation (as 10252 // used for tail calls) is implementation-defined, so we cannot rely on the 10253 // linker replacing the tail call with a return. 10254 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10255 const GlobalValue *GV = G->getGlobal(); 10256 if (GV->hasExternalWeakLinkage()) 10257 return false; 10258 } 10259 10260 // The callee has to preserve all registers the caller needs to preserve. 10261 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10262 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10263 if (CalleeCC != CallerCC) { 10264 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10265 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10266 return false; 10267 } 10268 10269 // Byval parameters hand the function a pointer directly into the stack area 10270 // we want to reuse during a tail call. Working around this *is* possible 10271 // but less efficient and uglier in LowerCall. 10272 for (auto &Arg : Outs) 10273 if (Arg.Flags.isByVal()) 10274 return false; 10275 10276 return true; 10277 } 10278 10279 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10280 return DAG.getDataLayout().getPrefTypeAlign( 10281 VT.getTypeForEVT(*DAG.getContext())); 10282 } 10283 10284 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10285 // and output parameter nodes. 10286 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10287 SmallVectorImpl<SDValue> &InVals) const { 10288 SelectionDAG &DAG = CLI.DAG; 10289 SDLoc &DL = CLI.DL; 10290 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10291 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10292 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10293 SDValue Chain = CLI.Chain; 10294 SDValue Callee = CLI.Callee; 10295 bool &IsTailCall = CLI.IsTailCall; 10296 CallingConv::ID CallConv = CLI.CallConv; 10297 bool IsVarArg = CLI.IsVarArg; 10298 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10299 MVT XLenVT = Subtarget.getXLenVT(); 10300 10301 MachineFunction &MF = DAG.getMachineFunction(); 10302 10303 // Analyze the operands of the call, assigning locations to each operand. 10304 SmallVector<CCValAssign, 16> ArgLocs; 10305 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10306 10307 if (CallConv == CallingConv::GHC) 10308 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10309 else 10310 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10311 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10312 : CC_RISCV); 10313 10314 // Check if it's really possible to do a tail call. 10315 if (IsTailCall) 10316 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10317 10318 if (IsTailCall) 10319 ++NumTailCalls; 10320 else if (CLI.CB && CLI.CB->isMustTailCall()) 10321 report_fatal_error("failed to perform tail call elimination on a call " 10322 "site marked musttail"); 10323 10324 // Get a count of how many bytes are to be pushed on the stack. 10325 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10326 10327 // Create local copies for byval args 10328 SmallVector<SDValue, 8> ByValArgs; 10329 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10330 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10331 if (!Flags.isByVal()) 10332 continue; 10333 10334 SDValue Arg = OutVals[i]; 10335 unsigned Size = Flags.getByValSize(); 10336 Align Alignment = Flags.getNonZeroByValAlign(); 10337 10338 int FI = 10339 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10340 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10341 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10342 10343 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10344 /*IsVolatile=*/false, 10345 /*AlwaysInline=*/false, IsTailCall, 10346 MachinePointerInfo(), MachinePointerInfo()); 10347 ByValArgs.push_back(FIPtr); 10348 } 10349 10350 if (!IsTailCall) 10351 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10352 10353 // Copy argument values to their designated locations. 10354 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10355 SmallVector<SDValue, 8> MemOpChains; 10356 SDValue StackPtr; 10357 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10358 CCValAssign &VA = ArgLocs[i]; 10359 SDValue ArgValue = OutVals[i]; 10360 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10361 10362 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10363 bool IsF64OnRV32DSoftABI = 10364 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10365 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10366 SDValue SplitF64 = DAG.getNode( 10367 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10368 SDValue Lo = SplitF64.getValue(0); 10369 SDValue Hi = SplitF64.getValue(1); 10370 10371 Register RegLo = VA.getLocReg(); 10372 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10373 10374 if (RegLo == RISCV::X17) { 10375 // Second half of f64 is passed on the stack. 10376 // Work out the address of the stack slot. 10377 if (!StackPtr.getNode()) 10378 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10379 // Emit the store. 10380 MemOpChains.push_back( 10381 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10382 } else { 10383 // Second half of f64 is passed in another GPR. 10384 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10385 Register RegHigh = RegLo + 1; 10386 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10387 } 10388 continue; 10389 } 10390 10391 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10392 // as any other MemLoc. 10393 10394 // Promote the value if needed. 10395 // For now, only handle fully promoted and indirect arguments. 10396 if (VA.getLocInfo() == CCValAssign::Indirect) { 10397 // Store the argument in a stack slot and pass its address. 10398 Align StackAlign = 10399 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10400 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10401 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10402 // If the original argument was split (e.g. i128), we need 10403 // to store the required parts of it here (and pass just one address). 10404 // Vectors may be partly split to registers and partly to the stack, in 10405 // which case the base address is partly offset and subsequent stores are 10406 // relative to that. 10407 unsigned ArgIndex = Outs[i].OrigArgIndex; 10408 unsigned ArgPartOffset = Outs[i].PartOffset; 10409 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10410 // Calculate the total size to store. We don't have access to what we're 10411 // actually storing other than performing the loop and collecting the 10412 // info. 10413 SmallVector<std::pair<SDValue, SDValue>> Parts; 10414 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10415 SDValue PartValue = OutVals[i + 1]; 10416 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10417 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10418 EVT PartVT = PartValue.getValueType(); 10419 if (PartVT.isScalableVector()) 10420 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10421 StoredSize += PartVT.getStoreSize(); 10422 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10423 Parts.push_back(std::make_pair(PartValue, Offset)); 10424 ++i; 10425 } 10426 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10427 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10428 MemOpChains.push_back( 10429 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10430 MachinePointerInfo::getFixedStack(MF, FI))); 10431 for (const auto &Part : Parts) { 10432 SDValue PartValue = Part.first; 10433 SDValue PartOffset = Part.second; 10434 SDValue Address = 10435 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10436 MemOpChains.push_back( 10437 DAG.getStore(Chain, DL, PartValue, Address, 10438 MachinePointerInfo::getFixedStack(MF, FI))); 10439 } 10440 ArgValue = SpillSlot; 10441 } else { 10442 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10443 } 10444 10445 // Use local copy if it is a byval arg. 10446 if (Flags.isByVal()) 10447 ArgValue = ByValArgs[j++]; 10448 10449 if (VA.isRegLoc()) { 10450 // Queue up the argument copies and emit them at the end. 10451 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10452 } else { 10453 assert(VA.isMemLoc() && "Argument not register or memory"); 10454 assert(!IsTailCall && "Tail call not allowed if stack is used " 10455 "for passing parameters"); 10456 10457 // Work out the address of the stack slot. 10458 if (!StackPtr.getNode()) 10459 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10460 SDValue Address = 10461 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10462 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10463 10464 // Emit the store. 10465 MemOpChains.push_back( 10466 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10467 } 10468 } 10469 10470 // Join the stores, which are independent of one another. 10471 if (!MemOpChains.empty()) 10472 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10473 10474 SDValue Glue; 10475 10476 // Build a sequence of copy-to-reg nodes, chained and glued together. 10477 for (auto &Reg : RegsToPass) { 10478 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10479 Glue = Chain.getValue(1); 10480 } 10481 10482 // Validate that none of the argument registers have been marked as 10483 // reserved, if so report an error. Do the same for the return address if this 10484 // is not a tailcall. 10485 validateCCReservedRegs(RegsToPass, MF); 10486 if (!IsTailCall && 10487 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10488 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10489 MF.getFunction(), 10490 "Return address register required, but has been reserved."}); 10491 10492 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10493 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10494 // split it and then direct call can be matched by PseudoCALL. 10495 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10496 const GlobalValue *GV = S->getGlobal(); 10497 10498 unsigned OpFlags = RISCVII::MO_CALL; 10499 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10500 OpFlags = RISCVII::MO_PLT; 10501 10502 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10503 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10504 unsigned OpFlags = RISCVII::MO_CALL; 10505 10506 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10507 nullptr)) 10508 OpFlags = RISCVII::MO_PLT; 10509 10510 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10511 } 10512 10513 // The first call operand is the chain and the second is the target address. 10514 SmallVector<SDValue, 8> Ops; 10515 Ops.push_back(Chain); 10516 Ops.push_back(Callee); 10517 10518 // Add argument registers to the end of the list so that they are 10519 // known live into the call. 10520 for (auto &Reg : RegsToPass) 10521 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10522 10523 if (!IsTailCall) { 10524 // Add a register mask operand representing the call-preserved registers. 10525 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10526 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10527 assert(Mask && "Missing call preserved mask for calling convention"); 10528 Ops.push_back(DAG.getRegisterMask(Mask)); 10529 } 10530 10531 // Glue the call to the argument copies, if any. 10532 if (Glue.getNode()) 10533 Ops.push_back(Glue); 10534 10535 // Emit the call. 10536 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10537 10538 if (IsTailCall) { 10539 MF.getFrameInfo().setHasTailCall(); 10540 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10541 } 10542 10543 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10544 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10545 Glue = Chain.getValue(1); 10546 10547 // Mark the end of the call, which is glued to the call itself. 10548 Chain = DAG.getCALLSEQ_END(Chain, 10549 DAG.getConstant(NumBytes, DL, PtrVT, true), 10550 DAG.getConstant(0, DL, PtrVT, true), 10551 Glue, DL); 10552 Glue = Chain.getValue(1); 10553 10554 // Assign locations to each value returned by this call. 10555 SmallVector<CCValAssign, 16> RVLocs; 10556 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10557 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10558 10559 // Copy all of the result registers out of their specified physreg. 10560 for (auto &VA : RVLocs) { 10561 // Copy the value out 10562 SDValue RetValue = 10563 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10564 // Glue the RetValue to the end of the call sequence 10565 Chain = RetValue.getValue(1); 10566 Glue = RetValue.getValue(2); 10567 10568 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10569 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10570 SDValue RetValue2 = 10571 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10572 Chain = RetValue2.getValue(1); 10573 Glue = RetValue2.getValue(2); 10574 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10575 RetValue2); 10576 } 10577 10578 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10579 10580 InVals.push_back(RetValue); 10581 } 10582 10583 return Chain; 10584 } 10585 10586 bool RISCVTargetLowering::CanLowerReturn( 10587 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10588 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10589 SmallVector<CCValAssign, 16> RVLocs; 10590 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10591 10592 Optional<unsigned> FirstMaskArgument; 10593 if (Subtarget.hasVInstructions()) 10594 FirstMaskArgument = preAssignMask(Outs); 10595 10596 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10597 MVT VT = Outs[i].VT; 10598 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10599 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10600 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10601 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10602 *this, FirstMaskArgument)) 10603 return false; 10604 } 10605 return true; 10606 } 10607 10608 SDValue 10609 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10610 bool IsVarArg, 10611 const SmallVectorImpl<ISD::OutputArg> &Outs, 10612 const SmallVectorImpl<SDValue> &OutVals, 10613 const SDLoc &DL, SelectionDAG &DAG) const { 10614 const MachineFunction &MF = DAG.getMachineFunction(); 10615 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10616 10617 // Stores the assignment of the return value to a location. 10618 SmallVector<CCValAssign, 16> RVLocs; 10619 10620 // Info about the registers and stack slot. 10621 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10622 *DAG.getContext()); 10623 10624 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10625 nullptr, CC_RISCV); 10626 10627 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10628 report_fatal_error("GHC functions return void only"); 10629 10630 SDValue Glue; 10631 SmallVector<SDValue, 4> RetOps(1, Chain); 10632 10633 // Copy the result values into the output registers. 10634 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10635 SDValue Val = OutVals[i]; 10636 CCValAssign &VA = RVLocs[i]; 10637 assert(VA.isRegLoc() && "Can only return in registers!"); 10638 10639 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10640 // Handle returning f64 on RV32D with a soft float ABI. 10641 assert(VA.isRegLoc() && "Expected return via registers"); 10642 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10643 DAG.getVTList(MVT::i32, MVT::i32), Val); 10644 SDValue Lo = SplitF64.getValue(0); 10645 SDValue Hi = SplitF64.getValue(1); 10646 Register RegLo = VA.getLocReg(); 10647 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10648 Register RegHi = RegLo + 1; 10649 10650 if (STI.isRegisterReservedByUser(RegLo) || 10651 STI.isRegisterReservedByUser(RegHi)) 10652 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10653 MF.getFunction(), 10654 "Return value register required, but has been reserved."}); 10655 10656 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10657 Glue = Chain.getValue(1); 10658 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10659 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10660 Glue = Chain.getValue(1); 10661 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10662 } else { 10663 // Handle a 'normal' return. 10664 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10665 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10666 10667 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10668 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10669 MF.getFunction(), 10670 "Return value register required, but has been reserved."}); 10671 10672 // Guarantee that all emitted copies are stuck together. 10673 Glue = Chain.getValue(1); 10674 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10675 } 10676 } 10677 10678 RetOps[0] = Chain; // Update chain. 10679 10680 // Add the glue node if we have it. 10681 if (Glue.getNode()) { 10682 RetOps.push_back(Glue); 10683 } 10684 10685 unsigned RetOpc = RISCVISD::RET_FLAG; 10686 // Interrupt service routines use different return instructions. 10687 const Function &Func = DAG.getMachineFunction().getFunction(); 10688 if (Func.hasFnAttribute("interrupt")) { 10689 if (!Func.getReturnType()->isVoidTy()) 10690 report_fatal_error( 10691 "Functions with the interrupt attribute must have void return type!"); 10692 10693 MachineFunction &MF = DAG.getMachineFunction(); 10694 StringRef Kind = 10695 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10696 10697 if (Kind == "user") 10698 RetOpc = RISCVISD::URET_FLAG; 10699 else if (Kind == "supervisor") 10700 RetOpc = RISCVISD::SRET_FLAG; 10701 else 10702 RetOpc = RISCVISD::MRET_FLAG; 10703 } 10704 10705 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10706 } 10707 10708 void RISCVTargetLowering::validateCCReservedRegs( 10709 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10710 MachineFunction &MF) const { 10711 const Function &F = MF.getFunction(); 10712 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10713 10714 if (llvm::any_of(Regs, [&STI](auto Reg) { 10715 return STI.isRegisterReservedByUser(Reg.first); 10716 })) 10717 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10718 F, "Argument register required, but has been reserved."}); 10719 } 10720 10721 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10722 return CI->isTailCall(); 10723 } 10724 10725 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10726 #define NODE_NAME_CASE(NODE) \ 10727 case RISCVISD::NODE: \ 10728 return "RISCVISD::" #NODE; 10729 // clang-format off 10730 switch ((RISCVISD::NodeType)Opcode) { 10731 case RISCVISD::FIRST_NUMBER: 10732 break; 10733 NODE_NAME_CASE(RET_FLAG) 10734 NODE_NAME_CASE(URET_FLAG) 10735 NODE_NAME_CASE(SRET_FLAG) 10736 NODE_NAME_CASE(MRET_FLAG) 10737 NODE_NAME_CASE(CALL) 10738 NODE_NAME_CASE(SELECT_CC) 10739 NODE_NAME_CASE(BR_CC) 10740 NODE_NAME_CASE(BuildPairF64) 10741 NODE_NAME_CASE(SplitF64) 10742 NODE_NAME_CASE(TAIL) 10743 NODE_NAME_CASE(MULHSU) 10744 NODE_NAME_CASE(SLLW) 10745 NODE_NAME_CASE(SRAW) 10746 NODE_NAME_CASE(SRLW) 10747 NODE_NAME_CASE(DIVW) 10748 NODE_NAME_CASE(DIVUW) 10749 NODE_NAME_CASE(REMUW) 10750 NODE_NAME_CASE(ROLW) 10751 NODE_NAME_CASE(RORW) 10752 NODE_NAME_CASE(CLZW) 10753 NODE_NAME_CASE(CTZW) 10754 NODE_NAME_CASE(FSLW) 10755 NODE_NAME_CASE(FSRW) 10756 NODE_NAME_CASE(FSL) 10757 NODE_NAME_CASE(FSR) 10758 NODE_NAME_CASE(FMV_H_X) 10759 NODE_NAME_CASE(FMV_X_ANYEXTH) 10760 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10761 NODE_NAME_CASE(FMV_W_X_RV64) 10762 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10763 NODE_NAME_CASE(FCVT_X) 10764 NODE_NAME_CASE(FCVT_XU) 10765 NODE_NAME_CASE(FCVT_W_RV64) 10766 NODE_NAME_CASE(FCVT_WU_RV64) 10767 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10768 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10769 NODE_NAME_CASE(READ_CYCLE_WIDE) 10770 NODE_NAME_CASE(GREV) 10771 NODE_NAME_CASE(GREVW) 10772 NODE_NAME_CASE(GORC) 10773 NODE_NAME_CASE(GORCW) 10774 NODE_NAME_CASE(SHFL) 10775 NODE_NAME_CASE(SHFLW) 10776 NODE_NAME_CASE(UNSHFL) 10777 NODE_NAME_CASE(UNSHFLW) 10778 NODE_NAME_CASE(BFP) 10779 NODE_NAME_CASE(BFPW) 10780 NODE_NAME_CASE(BCOMPRESS) 10781 NODE_NAME_CASE(BCOMPRESSW) 10782 NODE_NAME_CASE(BDECOMPRESS) 10783 NODE_NAME_CASE(BDECOMPRESSW) 10784 NODE_NAME_CASE(VMV_V_X_VL) 10785 NODE_NAME_CASE(VFMV_V_F_VL) 10786 NODE_NAME_CASE(VMV_X_S) 10787 NODE_NAME_CASE(VMV_S_X_VL) 10788 NODE_NAME_CASE(VFMV_S_F_VL) 10789 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10790 NODE_NAME_CASE(READ_VLENB) 10791 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10792 NODE_NAME_CASE(VSLIDEUP_VL) 10793 NODE_NAME_CASE(VSLIDE1UP_VL) 10794 NODE_NAME_CASE(VSLIDEDOWN_VL) 10795 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10796 NODE_NAME_CASE(VID_VL) 10797 NODE_NAME_CASE(VFNCVT_ROD_VL) 10798 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10799 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10800 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10801 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10802 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10803 NODE_NAME_CASE(VECREDUCE_AND_VL) 10804 NODE_NAME_CASE(VECREDUCE_OR_VL) 10805 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10806 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10807 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10808 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10809 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10810 NODE_NAME_CASE(ADD_VL) 10811 NODE_NAME_CASE(AND_VL) 10812 NODE_NAME_CASE(MUL_VL) 10813 NODE_NAME_CASE(OR_VL) 10814 NODE_NAME_CASE(SDIV_VL) 10815 NODE_NAME_CASE(SHL_VL) 10816 NODE_NAME_CASE(SREM_VL) 10817 NODE_NAME_CASE(SRA_VL) 10818 NODE_NAME_CASE(SRL_VL) 10819 NODE_NAME_CASE(SUB_VL) 10820 NODE_NAME_CASE(UDIV_VL) 10821 NODE_NAME_CASE(UREM_VL) 10822 NODE_NAME_CASE(XOR_VL) 10823 NODE_NAME_CASE(SADDSAT_VL) 10824 NODE_NAME_CASE(UADDSAT_VL) 10825 NODE_NAME_CASE(SSUBSAT_VL) 10826 NODE_NAME_CASE(USUBSAT_VL) 10827 NODE_NAME_CASE(FADD_VL) 10828 NODE_NAME_CASE(FSUB_VL) 10829 NODE_NAME_CASE(FMUL_VL) 10830 NODE_NAME_CASE(FDIV_VL) 10831 NODE_NAME_CASE(FNEG_VL) 10832 NODE_NAME_CASE(FABS_VL) 10833 NODE_NAME_CASE(FSQRT_VL) 10834 NODE_NAME_CASE(FMA_VL) 10835 NODE_NAME_CASE(FCOPYSIGN_VL) 10836 NODE_NAME_CASE(SMIN_VL) 10837 NODE_NAME_CASE(SMAX_VL) 10838 NODE_NAME_CASE(UMIN_VL) 10839 NODE_NAME_CASE(UMAX_VL) 10840 NODE_NAME_CASE(FMINNUM_VL) 10841 NODE_NAME_CASE(FMAXNUM_VL) 10842 NODE_NAME_CASE(MULHS_VL) 10843 NODE_NAME_CASE(MULHU_VL) 10844 NODE_NAME_CASE(FP_TO_SINT_VL) 10845 NODE_NAME_CASE(FP_TO_UINT_VL) 10846 NODE_NAME_CASE(SINT_TO_FP_VL) 10847 NODE_NAME_CASE(UINT_TO_FP_VL) 10848 NODE_NAME_CASE(FP_EXTEND_VL) 10849 NODE_NAME_CASE(FP_ROUND_VL) 10850 NODE_NAME_CASE(VWMUL_VL) 10851 NODE_NAME_CASE(VWMULU_VL) 10852 NODE_NAME_CASE(VWMULSU_VL) 10853 NODE_NAME_CASE(VWADD_VL) 10854 NODE_NAME_CASE(VWADDU_VL) 10855 NODE_NAME_CASE(VWSUB_VL) 10856 NODE_NAME_CASE(VWSUBU_VL) 10857 NODE_NAME_CASE(VWADD_W_VL) 10858 NODE_NAME_CASE(VWADDU_W_VL) 10859 NODE_NAME_CASE(VWSUB_W_VL) 10860 NODE_NAME_CASE(VWSUBU_W_VL) 10861 NODE_NAME_CASE(SETCC_VL) 10862 NODE_NAME_CASE(VSELECT_VL) 10863 NODE_NAME_CASE(VP_MERGE_VL) 10864 NODE_NAME_CASE(VMAND_VL) 10865 NODE_NAME_CASE(VMOR_VL) 10866 NODE_NAME_CASE(VMXOR_VL) 10867 NODE_NAME_CASE(VMCLR_VL) 10868 NODE_NAME_CASE(VMSET_VL) 10869 NODE_NAME_CASE(VRGATHER_VX_VL) 10870 NODE_NAME_CASE(VRGATHER_VV_VL) 10871 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10872 NODE_NAME_CASE(VSEXT_VL) 10873 NODE_NAME_CASE(VZEXT_VL) 10874 NODE_NAME_CASE(VCPOP_VL) 10875 NODE_NAME_CASE(READ_CSR) 10876 NODE_NAME_CASE(WRITE_CSR) 10877 NODE_NAME_CASE(SWAP_CSR) 10878 } 10879 // clang-format on 10880 return nullptr; 10881 #undef NODE_NAME_CASE 10882 } 10883 10884 /// getConstraintType - Given a constraint letter, return the type of 10885 /// constraint it is for this target. 10886 RISCVTargetLowering::ConstraintType 10887 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10888 if (Constraint.size() == 1) { 10889 switch (Constraint[0]) { 10890 default: 10891 break; 10892 case 'f': 10893 return C_RegisterClass; 10894 case 'I': 10895 case 'J': 10896 case 'K': 10897 return C_Immediate; 10898 case 'A': 10899 return C_Memory; 10900 case 'S': // A symbolic address 10901 return C_Other; 10902 } 10903 } else { 10904 if (Constraint == "vr" || Constraint == "vm") 10905 return C_RegisterClass; 10906 } 10907 return TargetLowering::getConstraintType(Constraint); 10908 } 10909 10910 std::pair<unsigned, const TargetRegisterClass *> 10911 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10912 StringRef Constraint, 10913 MVT VT) const { 10914 // First, see if this is a constraint that directly corresponds to a 10915 // RISCV register class. 10916 if (Constraint.size() == 1) { 10917 switch (Constraint[0]) { 10918 case 'r': 10919 // TODO: Support fixed vectors up to XLen for P extension? 10920 if (VT.isVector()) 10921 break; 10922 return std::make_pair(0U, &RISCV::GPRRegClass); 10923 case 'f': 10924 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10925 return std::make_pair(0U, &RISCV::FPR16RegClass); 10926 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10927 return std::make_pair(0U, &RISCV::FPR32RegClass); 10928 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10929 return std::make_pair(0U, &RISCV::FPR64RegClass); 10930 break; 10931 default: 10932 break; 10933 } 10934 } else if (Constraint == "vr") { 10935 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10936 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10937 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10938 return std::make_pair(0U, RC); 10939 } 10940 } else if (Constraint == "vm") { 10941 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10942 return std::make_pair(0U, &RISCV::VMV0RegClass); 10943 } 10944 10945 // Clang will correctly decode the usage of register name aliases into their 10946 // official names. However, other frontends like `rustc` do not. This allows 10947 // users of these frontends to use the ABI names for registers in LLVM-style 10948 // register constraints. 10949 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10950 .Case("{zero}", RISCV::X0) 10951 .Case("{ra}", RISCV::X1) 10952 .Case("{sp}", RISCV::X2) 10953 .Case("{gp}", RISCV::X3) 10954 .Case("{tp}", RISCV::X4) 10955 .Case("{t0}", RISCV::X5) 10956 .Case("{t1}", RISCV::X6) 10957 .Case("{t2}", RISCV::X7) 10958 .Cases("{s0}", "{fp}", RISCV::X8) 10959 .Case("{s1}", RISCV::X9) 10960 .Case("{a0}", RISCV::X10) 10961 .Case("{a1}", RISCV::X11) 10962 .Case("{a2}", RISCV::X12) 10963 .Case("{a3}", RISCV::X13) 10964 .Case("{a4}", RISCV::X14) 10965 .Case("{a5}", RISCV::X15) 10966 .Case("{a6}", RISCV::X16) 10967 .Case("{a7}", RISCV::X17) 10968 .Case("{s2}", RISCV::X18) 10969 .Case("{s3}", RISCV::X19) 10970 .Case("{s4}", RISCV::X20) 10971 .Case("{s5}", RISCV::X21) 10972 .Case("{s6}", RISCV::X22) 10973 .Case("{s7}", RISCV::X23) 10974 .Case("{s8}", RISCV::X24) 10975 .Case("{s9}", RISCV::X25) 10976 .Case("{s10}", RISCV::X26) 10977 .Case("{s11}", RISCV::X27) 10978 .Case("{t3}", RISCV::X28) 10979 .Case("{t4}", RISCV::X29) 10980 .Case("{t5}", RISCV::X30) 10981 .Case("{t6}", RISCV::X31) 10982 .Default(RISCV::NoRegister); 10983 if (XRegFromAlias != RISCV::NoRegister) 10984 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10985 10986 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10987 // TableGen record rather than the AsmName to choose registers for InlineAsm 10988 // constraints, plus we want to match those names to the widest floating point 10989 // register type available, manually select floating point registers here. 10990 // 10991 // The second case is the ABI name of the register, so that frontends can also 10992 // use the ABI names in register constraint lists. 10993 if (Subtarget.hasStdExtF()) { 10994 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10995 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10996 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10997 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10998 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10999 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11000 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11001 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11002 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11003 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11004 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11005 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11006 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11007 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11008 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11009 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11010 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11011 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11012 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11013 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11014 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11015 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11016 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11017 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11018 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11019 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11020 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11021 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11022 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11023 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11024 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11025 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11026 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11027 .Default(RISCV::NoRegister); 11028 if (FReg != RISCV::NoRegister) { 11029 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11030 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11031 unsigned RegNo = FReg - RISCV::F0_F; 11032 unsigned DReg = RISCV::F0_D + RegNo; 11033 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11034 } 11035 if (VT == MVT::f32 || VT == MVT::Other) 11036 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11037 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11038 unsigned RegNo = FReg - RISCV::F0_F; 11039 unsigned HReg = RISCV::F0_H + RegNo; 11040 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11041 } 11042 } 11043 } 11044 11045 if (Subtarget.hasVInstructions()) { 11046 Register VReg = StringSwitch<Register>(Constraint.lower()) 11047 .Case("{v0}", RISCV::V0) 11048 .Case("{v1}", RISCV::V1) 11049 .Case("{v2}", RISCV::V2) 11050 .Case("{v3}", RISCV::V3) 11051 .Case("{v4}", RISCV::V4) 11052 .Case("{v5}", RISCV::V5) 11053 .Case("{v6}", RISCV::V6) 11054 .Case("{v7}", RISCV::V7) 11055 .Case("{v8}", RISCV::V8) 11056 .Case("{v9}", RISCV::V9) 11057 .Case("{v10}", RISCV::V10) 11058 .Case("{v11}", RISCV::V11) 11059 .Case("{v12}", RISCV::V12) 11060 .Case("{v13}", RISCV::V13) 11061 .Case("{v14}", RISCV::V14) 11062 .Case("{v15}", RISCV::V15) 11063 .Case("{v16}", RISCV::V16) 11064 .Case("{v17}", RISCV::V17) 11065 .Case("{v18}", RISCV::V18) 11066 .Case("{v19}", RISCV::V19) 11067 .Case("{v20}", RISCV::V20) 11068 .Case("{v21}", RISCV::V21) 11069 .Case("{v22}", RISCV::V22) 11070 .Case("{v23}", RISCV::V23) 11071 .Case("{v24}", RISCV::V24) 11072 .Case("{v25}", RISCV::V25) 11073 .Case("{v26}", RISCV::V26) 11074 .Case("{v27}", RISCV::V27) 11075 .Case("{v28}", RISCV::V28) 11076 .Case("{v29}", RISCV::V29) 11077 .Case("{v30}", RISCV::V30) 11078 .Case("{v31}", RISCV::V31) 11079 .Default(RISCV::NoRegister); 11080 if (VReg != RISCV::NoRegister) { 11081 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11082 return std::make_pair(VReg, &RISCV::VMRegClass); 11083 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11084 return std::make_pair(VReg, &RISCV::VRRegClass); 11085 for (const auto *RC : 11086 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11087 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11088 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11089 return std::make_pair(VReg, RC); 11090 } 11091 } 11092 } 11093 } 11094 11095 std::pair<Register, const TargetRegisterClass *> Res = 11096 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11097 11098 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11099 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11100 // Subtarget into account. 11101 if (Res.second == &RISCV::GPRF16RegClass || 11102 Res.second == &RISCV::GPRF32RegClass || 11103 Res.second == &RISCV::GPRF64RegClass) 11104 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11105 11106 return Res; 11107 } 11108 11109 unsigned 11110 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11111 // Currently only support length 1 constraints. 11112 if (ConstraintCode.size() == 1) { 11113 switch (ConstraintCode[0]) { 11114 case 'A': 11115 return InlineAsm::Constraint_A; 11116 default: 11117 break; 11118 } 11119 } 11120 11121 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11122 } 11123 11124 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11125 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11126 SelectionDAG &DAG) const { 11127 // Currently only support length 1 constraints. 11128 if (Constraint.length() == 1) { 11129 switch (Constraint[0]) { 11130 case 'I': 11131 // Validate & create a 12-bit signed immediate operand. 11132 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11133 uint64_t CVal = C->getSExtValue(); 11134 if (isInt<12>(CVal)) 11135 Ops.push_back( 11136 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11137 } 11138 return; 11139 case 'J': 11140 // Validate & create an integer zero operand. 11141 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11142 if (C->getZExtValue() == 0) 11143 Ops.push_back( 11144 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11145 return; 11146 case 'K': 11147 // Validate & create a 5-bit unsigned immediate operand. 11148 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11149 uint64_t CVal = C->getZExtValue(); 11150 if (isUInt<5>(CVal)) 11151 Ops.push_back( 11152 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11153 } 11154 return; 11155 case 'S': 11156 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11157 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11158 GA->getValueType(0))); 11159 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11160 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11161 BA->getValueType(0))); 11162 } 11163 return; 11164 default: 11165 break; 11166 } 11167 } 11168 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11169 } 11170 11171 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11172 Instruction *Inst, 11173 AtomicOrdering Ord) const { 11174 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11175 return Builder.CreateFence(Ord); 11176 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11177 return Builder.CreateFence(AtomicOrdering::Release); 11178 return nullptr; 11179 } 11180 11181 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11182 Instruction *Inst, 11183 AtomicOrdering Ord) const { 11184 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11185 return Builder.CreateFence(AtomicOrdering::Acquire); 11186 return nullptr; 11187 } 11188 11189 TargetLowering::AtomicExpansionKind 11190 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11191 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11192 // point operations can't be used in an lr/sc sequence without breaking the 11193 // forward-progress guarantee. 11194 if (AI->isFloatingPointOperation()) 11195 return AtomicExpansionKind::CmpXChg; 11196 11197 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11198 if (Size == 8 || Size == 16) 11199 return AtomicExpansionKind::MaskedIntrinsic; 11200 return AtomicExpansionKind::None; 11201 } 11202 11203 static Intrinsic::ID 11204 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11205 if (XLen == 32) { 11206 switch (BinOp) { 11207 default: 11208 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11209 case AtomicRMWInst::Xchg: 11210 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11211 case AtomicRMWInst::Add: 11212 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11213 case AtomicRMWInst::Sub: 11214 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11215 case AtomicRMWInst::Nand: 11216 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11217 case AtomicRMWInst::Max: 11218 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11219 case AtomicRMWInst::Min: 11220 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11221 case AtomicRMWInst::UMax: 11222 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11223 case AtomicRMWInst::UMin: 11224 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11225 } 11226 } 11227 11228 if (XLen == 64) { 11229 switch (BinOp) { 11230 default: 11231 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11232 case AtomicRMWInst::Xchg: 11233 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11234 case AtomicRMWInst::Add: 11235 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11236 case AtomicRMWInst::Sub: 11237 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11238 case AtomicRMWInst::Nand: 11239 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11240 case AtomicRMWInst::Max: 11241 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11242 case AtomicRMWInst::Min: 11243 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11244 case AtomicRMWInst::UMax: 11245 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11246 case AtomicRMWInst::UMin: 11247 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11248 } 11249 } 11250 11251 llvm_unreachable("Unexpected XLen\n"); 11252 } 11253 11254 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11255 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11256 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11257 unsigned XLen = Subtarget.getXLen(); 11258 Value *Ordering = 11259 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11260 Type *Tys[] = {AlignedAddr->getType()}; 11261 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11262 AI->getModule(), 11263 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11264 11265 if (XLen == 64) { 11266 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11267 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11268 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11269 } 11270 11271 Value *Result; 11272 11273 // Must pass the shift amount needed to sign extend the loaded value prior 11274 // to performing a signed comparison for min/max. ShiftAmt is the number of 11275 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11276 // is the number of bits to left+right shift the value in order to 11277 // sign-extend. 11278 if (AI->getOperation() == AtomicRMWInst::Min || 11279 AI->getOperation() == AtomicRMWInst::Max) { 11280 const DataLayout &DL = AI->getModule()->getDataLayout(); 11281 unsigned ValWidth = 11282 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11283 Value *SextShamt = 11284 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11285 Result = Builder.CreateCall(LrwOpScwLoop, 11286 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11287 } else { 11288 Result = 11289 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11290 } 11291 11292 if (XLen == 64) 11293 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11294 return Result; 11295 } 11296 11297 TargetLowering::AtomicExpansionKind 11298 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11299 AtomicCmpXchgInst *CI) const { 11300 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11301 if (Size == 8 || Size == 16) 11302 return AtomicExpansionKind::MaskedIntrinsic; 11303 return AtomicExpansionKind::None; 11304 } 11305 11306 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11307 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11308 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11309 unsigned XLen = Subtarget.getXLen(); 11310 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11311 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11312 if (XLen == 64) { 11313 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11314 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11315 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11316 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11317 } 11318 Type *Tys[] = {AlignedAddr->getType()}; 11319 Function *MaskedCmpXchg = 11320 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11321 Value *Result = Builder.CreateCall( 11322 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11323 if (XLen == 64) 11324 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11325 return Result; 11326 } 11327 11328 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11329 return false; 11330 } 11331 11332 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11333 EVT VT) const { 11334 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11335 return false; 11336 11337 switch (FPVT.getSimpleVT().SimpleTy) { 11338 case MVT::f16: 11339 return Subtarget.hasStdExtZfh(); 11340 case MVT::f32: 11341 return Subtarget.hasStdExtF(); 11342 case MVT::f64: 11343 return Subtarget.hasStdExtD(); 11344 default: 11345 return false; 11346 } 11347 } 11348 11349 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11350 // If we are using the small code model, we can reduce size of jump table 11351 // entry to 4 bytes. 11352 if (Subtarget.is64Bit() && !isPositionIndependent() && 11353 getTargetMachine().getCodeModel() == CodeModel::Small) { 11354 return MachineJumpTableInfo::EK_Custom32; 11355 } 11356 return TargetLowering::getJumpTableEncoding(); 11357 } 11358 11359 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11360 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11361 unsigned uid, MCContext &Ctx) const { 11362 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11363 getTargetMachine().getCodeModel() == CodeModel::Small); 11364 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11365 } 11366 11367 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11368 EVT VT) const { 11369 VT = VT.getScalarType(); 11370 11371 if (!VT.isSimple()) 11372 return false; 11373 11374 switch (VT.getSimpleVT().SimpleTy) { 11375 case MVT::f16: 11376 return Subtarget.hasStdExtZfh(); 11377 case MVT::f32: 11378 return Subtarget.hasStdExtF(); 11379 case MVT::f64: 11380 return Subtarget.hasStdExtD(); 11381 default: 11382 break; 11383 } 11384 11385 return false; 11386 } 11387 11388 Register RISCVTargetLowering::getExceptionPointerRegister( 11389 const Constant *PersonalityFn) const { 11390 return RISCV::X10; 11391 } 11392 11393 Register RISCVTargetLowering::getExceptionSelectorRegister( 11394 const Constant *PersonalityFn) const { 11395 return RISCV::X11; 11396 } 11397 11398 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11399 // Return false to suppress the unnecessary extensions if the LibCall 11400 // arguments or return value is f32 type for LP64 ABI. 11401 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11402 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11403 return false; 11404 11405 return true; 11406 } 11407 11408 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11409 if (Subtarget.is64Bit() && Type == MVT::i32) 11410 return true; 11411 11412 return IsSigned; 11413 } 11414 11415 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11416 SDValue C) const { 11417 // Check integral scalar types. 11418 if (VT.isScalarInteger()) { 11419 // Omit the optimization if the sub target has the M extension and the data 11420 // size exceeds XLen. 11421 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11422 return false; 11423 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11424 // Break the MUL to a SLLI and an ADD/SUB. 11425 const APInt &Imm = ConstNode->getAPIntValue(); 11426 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11427 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11428 return true; 11429 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11430 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11431 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11432 (Imm - 8).isPowerOf2())) 11433 return true; 11434 // Omit the following optimization if the sub target has the M extension 11435 // and the data size >= XLen. 11436 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11437 return false; 11438 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11439 // a pair of LUI/ADDI. 11440 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11441 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11442 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11443 (1 - ImmS).isPowerOf2()) 11444 return true; 11445 } 11446 } 11447 } 11448 11449 return false; 11450 } 11451 11452 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11453 SDValue ConstNode) const { 11454 // Let the DAGCombiner decide for vectors. 11455 EVT VT = AddNode.getValueType(); 11456 if (VT.isVector()) 11457 return true; 11458 11459 // Let the DAGCombiner decide for larger types. 11460 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11461 return true; 11462 11463 // It is worse if c1 is simm12 while c1*c2 is not. 11464 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11465 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11466 const APInt &C1 = C1Node->getAPIntValue(); 11467 const APInt &C2 = C2Node->getAPIntValue(); 11468 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11469 return false; 11470 11471 // Default to true and let the DAGCombiner decide. 11472 return true; 11473 } 11474 11475 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11476 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11477 bool *Fast) const { 11478 if (!VT.isVector()) 11479 return false; 11480 11481 EVT ElemVT = VT.getVectorElementType(); 11482 if (Alignment >= ElemVT.getStoreSize()) { 11483 if (Fast) 11484 *Fast = true; 11485 return true; 11486 } 11487 11488 return false; 11489 } 11490 11491 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11492 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11493 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11494 bool IsABIRegCopy = CC.hasValue(); 11495 EVT ValueVT = Val.getValueType(); 11496 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11497 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11498 // and cast to f32. 11499 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11500 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11501 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11502 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11503 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11504 Parts[0] = Val; 11505 return true; 11506 } 11507 11508 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11509 LLVMContext &Context = *DAG.getContext(); 11510 EVT ValueEltVT = ValueVT.getVectorElementType(); 11511 EVT PartEltVT = PartVT.getVectorElementType(); 11512 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11513 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11514 if (PartVTBitSize % ValueVTBitSize == 0) { 11515 assert(PartVTBitSize >= ValueVTBitSize); 11516 // If the element types are different, bitcast to the same element type of 11517 // PartVT first. 11518 // Give an example here, we want copy a <vscale x 1 x i8> value to 11519 // <vscale x 4 x i16>. 11520 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11521 // subvector, then we can bitcast to <vscale x 4 x i16>. 11522 if (ValueEltVT != PartEltVT) { 11523 if (PartVTBitSize > ValueVTBitSize) { 11524 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11525 assert(Count != 0 && "The number of element should not be zero."); 11526 EVT SameEltTypeVT = 11527 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11528 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11529 DAG.getUNDEF(SameEltTypeVT), Val, 11530 DAG.getVectorIdxConstant(0, DL)); 11531 } 11532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11533 } else { 11534 Val = 11535 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11536 Val, DAG.getVectorIdxConstant(0, DL)); 11537 } 11538 Parts[0] = Val; 11539 return true; 11540 } 11541 } 11542 return false; 11543 } 11544 11545 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11546 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11547 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11548 bool IsABIRegCopy = CC.hasValue(); 11549 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11550 SDValue Val = Parts[0]; 11551 11552 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11553 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11554 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11555 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11556 return Val; 11557 } 11558 11559 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11560 LLVMContext &Context = *DAG.getContext(); 11561 SDValue Val = Parts[0]; 11562 EVT ValueEltVT = ValueVT.getVectorElementType(); 11563 EVT PartEltVT = PartVT.getVectorElementType(); 11564 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11565 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11566 if (PartVTBitSize % ValueVTBitSize == 0) { 11567 assert(PartVTBitSize >= ValueVTBitSize); 11568 EVT SameEltTypeVT = ValueVT; 11569 // If the element types are different, convert it to the same element type 11570 // of PartVT. 11571 // Give an example here, we want copy a <vscale x 1 x i8> value from 11572 // <vscale x 4 x i16>. 11573 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11574 // then we can extract <vscale x 1 x i8>. 11575 if (ValueEltVT != PartEltVT) { 11576 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11577 assert(Count != 0 && "The number of element should not be zero."); 11578 SameEltTypeVT = 11579 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11580 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11581 } 11582 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11583 DAG.getVectorIdxConstant(0, DL)); 11584 return Val; 11585 } 11586 } 11587 return SDValue(); 11588 } 11589 11590 SDValue 11591 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11592 SelectionDAG &DAG, 11593 SmallVectorImpl<SDNode *> &Created) const { 11594 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11595 if (isIntDivCheap(N->getValueType(0), Attr)) 11596 return SDValue(N, 0); // Lower SDIV as SDIV 11597 11598 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11599 "Unexpected divisor!"); 11600 11601 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11602 if (!Subtarget.hasStdExtZbt()) 11603 return SDValue(); 11604 11605 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11606 // Besides, more critical path instructions will be generated when dividing 11607 // by 2. So we keep using the original DAGs for these cases. 11608 unsigned Lg2 = Divisor.countTrailingZeros(); 11609 if (Lg2 == 1 || Lg2 >= 12) 11610 return SDValue(); 11611 11612 // fold (sdiv X, pow2) 11613 EVT VT = N->getValueType(0); 11614 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11615 return SDValue(); 11616 11617 SDLoc DL(N); 11618 SDValue N0 = N->getOperand(0); 11619 SDValue Zero = DAG.getConstant(0, DL, VT); 11620 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11621 11622 // Add (N0 < 0) ? Pow2 - 1 : 0; 11623 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11624 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11625 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11626 11627 Created.push_back(Cmp.getNode()); 11628 Created.push_back(Add.getNode()); 11629 Created.push_back(Sel.getNode()); 11630 11631 // Divide by pow2. 11632 SDValue SRA = 11633 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11634 11635 // If we're dividing by a positive value, we're done. Otherwise, we must 11636 // negate the result. 11637 if (Divisor.isNonNegative()) 11638 return SRA; 11639 11640 Created.push_back(SRA.getNode()); 11641 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11642 } 11643 11644 #define GET_REGISTER_MATCHER 11645 #include "RISCVGenAsmMatcher.inc" 11646 11647 Register 11648 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11649 const MachineFunction &MF) const { 11650 Register Reg = MatchRegisterAltName(RegName); 11651 if (Reg == RISCV::NoRegister) 11652 Reg = MatchRegisterName(RegName); 11653 if (Reg == RISCV::NoRegister) 11654 report_fatal_error( 11655 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11656 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11657 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11658 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11659 StringRef(RegName) + "\".")); 11660 return Reg; 11661 } 11662 11663 namespace llvm { 11664 namespace RISCVVIntrinsicsTable { 11665 11666 #define GET_RISCVVIntrinsicsTable_IMPL 11667 #include "RISCVGenSearchableTables.inc" 11668 11669 } // namespace RISCVVIntrinsicsTable 11670 11671 } // namespace llvm 11672