1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 494 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SEXT, 495 ISD::VP_ZEXT, ISD::VP_TRUNC}; 496 497 static const unsigned FloatingPointVPOps[] = { 498 ISD::VP_FADD, ISD::VP_FSUB, 499 ISD::VP_FMUL, ISD::VP_FDIV, 500 ISD::VP_FNEG, ISD::VP_FMA, 501 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 502 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 503 ISD::VP_MERGE, ISD::VP_SELECT, 504 ISD::VP_SITOFP, ISD::VP_UITOFP, 505 ISD::VP_SETCC, ISD::VP_FP_ROUND}; 506 507 if (!Subtarget.is64Bit()) { 508 // We must custom-lower certain vXi64 operations on RV32 due to the vector 509 // element type being illegal. 510 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 511 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 512 513 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 515 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 516 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 517 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 518 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 519 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 520 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 521 522 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 524 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 525 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 526 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 527 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 528 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 529 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 530 } 531 532 for (MVT VT : BoolVecVTs) { 533 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 534 535 // Mask VTs are custom-expanded into a series of standard nodes 536 setOperationAction(ISD::TRUNCATE, VT, Custom); 537 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 538 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 539 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 540 541 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 542 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 543 544 setOperationAction(ISD::SELECT, VT, Custom); 545 setOperationAction(ISD::SELECT_CC, VT, Expand); 546 setOperationAction(ISD::VSELECT, VT, Expand); 547 setOperationAction(ISD::VP_MERGE, VT, Expand); 548 setOperationAction(ISD::VP_SELECT, VT, Expand); 549 550 setOperationAction(ISD::VP_AND, VT, Custom); 551 setOperationAction(ISD::VP_OR, VT, Custom); 552 setOperationAction(ISD::VP_XOR, VT, Custom); 553 554 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 555 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 556 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 557 558 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 559 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 560 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 561 562 // RVV has native int->float & float->int conversions where the 563 // element type sizes are within one power-of-two of each other. Any 564 // wider distances between type sizes have to be lowered as sequences 565 // which progressively narrow the gap in stages. 566 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 567 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 568 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 569 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 570 571 // Expand all extending loads to types larger than this, and truncating 572 // stores from types larger than this. 573 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 574 setTruncStoreAction(OtherVT, VT, Expand); 575 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 576 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 577 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 578 } 579 580 setOperationAction(ISD::VP_FPTOSI, VT, Custom); 581 setOperationAction(ISD::VP_FPTOUI, VT, Custom); 582 setOperationAction(ISD::VP_TRUNC, VT, Custom); 583 } 584 585 for (MVT VT : IntVecVTs) { 586 if (VT.getVectorElementType() == MVT::i64 && 587 !Subtarget.hasVInstructionsI64()) 588 continue; 589 590 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 591 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 592 593 // Vectors implement MULHS/MULHU. 594 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 595 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 596 597 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 598 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 599 setOperationAction(ISD::MULHU, VT, Expand); 600 setOperationAction(ISD::MULHS, VT, Expand); 601 } 602 603 setOperationAction(ISD::SMIN, VT, Legal); 604 setOperationAction(ISD::SMAX, VT, Legal); 605 setOperationAction(ISD::UMIN, VT, Legal); 606 setOperationAction(ISD::UMAX, VT, Legal); 607 608 setOperationAction(ISD::ROTL, VT, Expand); 609 setOperationAction(ISD::ROTR, VT, Expand); 610 611 setOperationAction(ISD::CTTZ, VT, Expand); 612 setOperationAction(ISD::CTLZ, VT, Expand); 613 setOperationAction(ISD::CTPOP, VT, Expand); 614 615 setOperationAction(ISD::BSWAP, VT, Expand); 616 617 // Custom-lower extensions and truncations from/to mask types. 618 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 619 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 620 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 621 622 // RVV has native int->float & float->int conversions where the 623 // element type sizes are within one power-of-two of each other. Any 624 // wider distances between type sizes have to be lowered as sequences 625 // which progressively narrow the gap in stages. 626 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 627 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 628 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 629 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 630 631 setOperationAction(ISD::SADDSAT, VT, Legal); 632 setOperationAction(ISD::UADDSAT, VT, Legal); 633 setOperationAction(ISD::SSUBSAT, VT, Legal); 634 setOperationAction(ISD::USUBSAT, VT, Legal); 635 636 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 637 // nodes which truncate by one power of two at a time. 638 setOperationAction(ISD::TRUNCATE, VT, Custom); 639 640 // Custom-lower insert/extract operations to simplify patterns. 641 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 642 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 643 644 // Custom-lower reduction operations to set up the corresponding custom 645 // nodes' operands. 646 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 647 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 648 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 649 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 650 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 651 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 652 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 653 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 654 655 for (unsigned VPOpc : IntegerVPOps) 656 setOperationAction(VPOpc, VT, Custom); 657 658 setOperationAction(ISD::LOAD, VT, Custom); 659 setOperationAction(ISD::STORE, VT, Custom); 660 661 setOperationAction(ISD::MLOAD, VT, Custom); 662 setOperationAction(ISD::MSTORE, VT, Custom); 663 setOperationAction(ISD::MGATHER, VT, Custom); 664 setOperationAction(ISD::MSCATTER, VT, Custom); 665 666 setOperationAction(ISD::VP_LOAD, VT, Custom); 667 setOperationAction(ISD::VP_STORE, VT, Custom); 668 setOperationAction(ISD::VP_GATHER, VT, Custom); 669 setOperationAction(ISD::VP_SCATTER, VT, Custom); 670 671 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 672 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 673 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 674 675 setOperationAction(ISD::SELECT, VT, Custom); 676 setOperationAction(ISD::SELECT_CC, VT, Expand); 677 678 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 679 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 680 681 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 682 setTruncStoreAction(VT, OtherVT, Expand); 683 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 684 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 685 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 686 } 687 688 // Splice 689 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 690 691 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 692 // type that can represent the value exactly. 693 if (VT.getVectorElementType() != MVT::i64) { 694 MVT FloatEltVT = 695 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 696 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 697 if (isTypeLegal(FloatVT)) { 698 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 699 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 700 } 701 } 702 } 703 704 // Expand various CCs to best match the RVV ISA, which natively supports UNE 705 // but no other unordered comparisons, and supports all ordered comparisons 706 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 707 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 708 // and we pattern-match those back to the "original", swapping operands once 709 // more. This way we catch both operations and both "vf" and "fv" forms with 710 // fewer patterns. 711 static const ISD::CondCode VFPCCToExpand[] = { 712 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 713 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 714 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 715 }; 716 717 // Sets common operation actions on RVV floating-point vector types. 718 const auto SetCommonVFPActions = [&](MVT VT) { 719 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 720 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 721 // sizes are within one power-of-two of each other. Therefore conversions 722 // between vXf16 and vXf64 must be lowered as sequences which convert via 723 // vXf32. 724 setOperationAction(ISD::FP_ROUND, VT, Custom); 725 setOperationAction(ISD::FP_EXTEND, VT, Custom); 726 // Custom-lower insert/extract operations to simplify patterns. 727 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 728 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 729 // Expand various condition codes (explained above). 730 for (auto CC : VFPCCToExpand) 731 setCondCodeAction(CC, VT, Expand); 732 733 setOperationAction(ISD::FMINNUM, VT, Legal); 734 setOperationAction(ISD::FMAXNUM, VT, Legal); 735 736 setOperationAction(ISD::FTRUNC, VT, Custom); 737 setOperationAction(ISD::FCEIL, VT, Custom); 738 setOperationAction(ISD::FFLOOR, VT, Custom); 739 setOperationAction(ISD::FROUND, VT, Custom); 740 741 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 742 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 743 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 744 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 745 746 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 747 748 setOperationAction(ISD::LOAD, VT, Custom); 749 setOperationAction(ISD::STORE, VT, Custom); 750 751 setOperationAction(ISD::MLOAD, VT, Custom); 752 setOperationAction(ISD::MSTORE, VT, Custom); 753 setOperationAction(ISD::MGATHER, VT, Custom); 754 setOperationAction(ISD::MSCATTER, VT, Custom); 755 756 setOperationAction(ISD::VP_LOAD, VT, Custom); 757 setOperationAction(ISD::VP_STORE, VT, Custom); 758 setOperationAction(ISD::VP_GATHER, VT, Custom); 759 setOperationAction(ISD::VP_SCATTER, VT, Custom); 760 761 setOperationAction(ISD::SELECT, VT, Custom); 762 setOperationAction(ISD::SELECT_CC, VT, Expand); 763 764 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 765 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 766 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 767 768 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 769 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 770 771 for (unsigned VPOpc : FloatingPointVPOps) 772 setOperationAction(VPOpc, VT, Custom); 773 }; 774 775 // Sets common extload/truncstore actions on RVV floating-point vector 776 // types. 777 const auto SetCommonVFPExtLoadTruncStoreActions = 778 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 779 for (auto SmallVT : SmallerVTs) { 780 setTruncStoreAction(VT, SmallVT, Expand); 781 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 782 } 783 }; 784 785 if (Subtarget.hasVInstructionsF16()) 786 for (MVT VT : F16VecVTs) 787 SetCommonVFPActions(VT); 788 789 for (MVT VT : F32VecVTs) { 790 if (Subtarget.hasVInstructionsF32()) 791 SetCommonVFPActions(VT); 792 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 793 } 794 795 for (MVT VT : F64VecVTs) { 796 if (Subtarget.hasVInstructionsF64()) 797 SetCommonVFPActions(VT); 798 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 799 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 800 } 801 802 if (Subtarget.useRVVForFixedLengthVectors()) { 803 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 804 if (!useRVVForFixedLengthVectorVT(VT)) 805 continue; 806 807 // By default everything must be expanded. 808 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 809 setOperationAction(Op, VT, Expand); 810 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 811 setTruncStoreAction(VT, OtherVT, Expand); 812 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 813 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 814 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 815 } 816 817 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 818 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 819 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 820 821 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 822 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 823 824 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 826 827 setOperationAction(ISD::LOAD, VT, Custom); 828 setOperationAction(ISD::STORE, VT, Custom); 829 830 setOperationAction(ISD::SETCC, VT, Custom); 831 832 setOperationAction(ISD::SELECT, VT, Custom); 833 834 setOperationAction(ISD::TRUNCATE, VT, Custom); 835 836 setOperationAction(ISD::BITCAST, VT, Custom); 837 838 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 839 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 840 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 841 842 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 843 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 844 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 845 846 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 847 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 848 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 849 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 850 851 // Operations below are different for between masks and other vectors. 852 if (VT.getVectorElementType() == MVT::i1) { 853 setOperationAction(ISD::VP_AND, VT, Custom); 854 setOperationAction(ISD::VP_OR, VT, Custom); 855 setOperationAction(ISD::VP_XOR, VT, Custom); 856 setOperationAction(ISD::AND, VT, Custom); 857 setOperationAction(ISD::OR, VT, Custom); 858 setOperationAction(ISD::XOR, VT, Custom); 859 860 setOperationAction(ISD::VP_FPTOSI, VT, Custom); 861 setOperationAction(ISD::VP_FPTOUI, VT, Custom); 862 setOperationAction(ISD::VP_SETCC, VT, Custom); 863 setOperationAction(ISD::VP_TRUNC, VT, Custom); 864 continue; 865 } 866 867 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 868 // it before type legalization for i64 vectors on RV32. It will then be 869 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 870 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 871 // improvements first. 872 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 873 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 874 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 875 } 876 877 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 878 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 879 880 setOperationAction(ISD::MLOAD, VT, Custom); 881 setOperationAction(ISD::MSTORE, VT, Custom); 882 setOperationAction(ISD::MGATHER, VT, Custom); 883 setOperationAction(ISD::MSCATTER, VT, Custom); 884 885 setOperationAction(ISD::VP_LOAD, VT, Custom); 886 setOperationAction(ISD::VP_STORE, VT, Custom); 887 setOperationAction(ISD::VP_GATHER, VT, Custom); 888 setOperationAction(ISD::VP_SCATTER, VT, Custom); 889 890 setOperationAction(ISD::ADD, VT, Custom); 891 setOperationAction(ISD::MUL, VT, Custom); 892 setOperationAction(ISD::SUB, VT, Custom); 893 setOperationAction(ISD::AND, VT, Custom); 894 setOperationAction(ISD::OR, VT, Custom); 895 setOperationAction(ISD::XOR, VT, Custom); 896 setOperationAction(ISD::SDIV, VT, Custom); 897 setOperationAction(ISD::SREM, VT, Custom); 898 setOperationAction(ISD::UDIV, VT, Custom); 899 setOperationAction(ISD::UREM, VT, Custom); 900 setOperationAction(ISD::SHL, VT, Custom); 901 setOperationAction(ISD::SRA, VT, Custom); 902 setOperationAction(ISD::SRL, VT, Custom); 903 904 setOperationAction(ISD::SMIN, VT, Custom); 905 setOperationAction(ISD::SMAX, VT, Custom); 906 setOperationAction(ISD::UMIN, VT, Custom); 907 setOperationAction(ISD::UMAX, VT, Custom); 908 setOperationAction(ISD::ABS, VT, Custom); 909 910 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 911 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 912 setOperationAction(ISD::MULHS, VT, Custom); 913 setOperationAction(ISD::MULHU, VT, Custom); 914 } 915 916 setOperationAction(ISD::SADDSAT, VT, Custom); 917 setOperationAction(ISD::UADDSAT, VT, Custom); 918 setOperationAction(ISD::SSUBSAT, VT, Custom); 919 setOperationAction(ISD::USUBSAT, VT, Custom); 920 921 setOperationAction(ISD::VSELECT, VT, Custom); 922 setOperationAction(ISD::SELECT_CC, VT, Expand); 923 924 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 925 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 926 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 927 928 // Custom-lower reduction operations to set up the corresponding custom 929 // nodes' operands. 930 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 931 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 932 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 933 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 934 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 935 936 for (unsigned VPOpc : IntegerVPOps) 937 setOperationAction(VPOpc, VT, Custom); 938 939 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 940 // type that can represent the value exactly. 941 if (VT.getVectorElementType() != MVT::i64) { 942 MVT FloatEltVT = 943 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 944 EVT FloatVT = 945 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 946 if (isTypeLegal(FloatVT)) { 947 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 948 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 949 } 950 } 951 } 952 953 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 954 if (!useRVVForFixedLengthVectorVT(VT)) 955 continue; 956 957 // By default everything must be expanded. 958 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 959 setOperationAction(Op, VT, Expand); 960 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 961 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 962 setTruncStoreAction(VT, OtherVT, Expand); 963 } 964 965 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 966 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 967 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 968 969 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 970 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 971 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 972 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 974 975 setOperationAction(ISD::LOAD, VT, Custom); 976 setOperationAction(ISD::STORE, VT, Custom); 977 setOperationAction(ISD::MLOAD, VT, Custom); 978 setOperationAction(ISD::MSTORE, VT, Custom); 979 setOperationAction(ISD::MGATHER, VT, Custom); 980 setOperationAction(ISD::MSCATTER, VT, Custom); 981 982 setOperationAction(ISD::VP_LOAD, VT, Custom); 983 setOperationAction(ISD::VP_STORE, VT, Custom); 984 setOperationAction(ISD::VP_GATHER, VT, Custom); 985 setOperationAction(ISD::VP_SCATTER, VT, Custom); 986 987 setOperationAction(ISD::FADD, VT, Custom); 988 setOperationAction(ISD::FSUB, VT, Custom); 989 setOperationAction(ISD::FMUL, VT, Custom); 990 setOperationAction(ISD::FDIV, VT, Custom); 991 setOperationAction(ISD::FNEG, VT, Custom); 992 setOperationAction(ISD::FABS, VT, Custom); 993 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 994 setOperationAction(ISD::FSQRT, VT, Custom); 995 setOperationAction(ISD::FMA, VT, Custom); 996 setOperationAction(ISD::FMINNUM, VT, Custom); 997 setOperationAction(ISD::FMAXNUM, VT, Custom); 998 999 setOperationAction(ISD::FP_ROUND, VT, Custom); 1000 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1001 1002 setOperationAction(ISD::FTRUNC, VT, Custom); 1003 setOperationAction(ISD::FCEIL, VT, Custom); 1004 setOperationAction(ISD::FFLOOR, VT, Custom); 1005 setOperationAction(ISD::FROUND, VT, Custom); 1006 1007 for (auto CC : VFPCCToExpand) 1008 setCondCodeAction(CC, VT, Expand); 1009 1010 setOperationAction(ISD::VSELECT, VT, Custom); 1011 setOperationAction(ISD::SELECT, VT, Custom); 1012 setOperationAction(ISD::SELECT_CC, VT, Expand); 1013 1014 setOperationAction(ISD::BITCAST, VT, Custom); 1015 1016 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1017 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1018 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1019 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1020 1021 for (unsigned VPOpc : FloatingPointVPOps) 1022 setOperationAction(VPOpc, VT, Custom); 1023 } 1024 1025 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1026 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1027 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1028 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1029 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1030 if (Subtarget.hasStdExtZfh()) 1031 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1032 if (Subtarget.hasStdExtF()) 1033 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1034 if (Subtarget.hasStdExtD()) 1035 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1036 } 1037 } 1038 1039 // Function alignments. 1040 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1041 setMinFunctionAlignment(FunctionAlignment); 1042 setPrefFunctionAlignment(FunctionAlignment); 1043 1044 setMinimumJumpTableEntries(5); 1045 1046 // Jumps are expensive, compared to logic 1047 setJumpIsExpensive(); 1048 1049 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 1050 ISD::OR, ISD::XOR}); 1051 1052 if (Subtarget.hasStdExtZbp()) 1053 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 1054 if (Subtarget.hasStdExtZbkb()) 1055 setTargetDAGCombine(ISD::BITREVERSE); 1056 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 1057 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1058 if (Subtarget.hasStdExtF()) 1059 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 1060 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 1061 if (Subtarget.hasVInstructions()) 1062 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 1063 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 1064 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 1065 1066 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1067 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1068 } 1069 1070 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1071 LLVMContext &Context, 1072 EVT VT) const { 1073 if (!VT.isVector()) 1074 return getPointerTy(DL); 1075 if (Subtarget.hasVInstructions() && 1076 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1077 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1078 return VT.changeVectorElementTypeToInteger(); 1079 } 1080 1081 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1082 return Subtarget.getXLenVT(); 1083 } 1084 1085 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1086 const CallInst &I, 1087 MachineFunction &MF, 1088 unsigned Intrinsic) const { 1089 auto &DL = I.getModule()->getDataLayout(); 1090 switch (Intrinsic) { 1091 default: 1092 return false; 1093 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1094 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1099 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1100 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1101 case Intrinsic::riscv_masked_cmpxchg_i32: 1102 Info.opc = ISD::INTRINSIC_W_CHAIN; 1103 Info.memVT = MVT::i32; 1104 Info.ptrVal = I.getArgOperand(0); 1105 Info.offset = 0; 1106 Info.align = Align(4); 1107 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1108 MachineMemOperand::MOVolatile; 1109 return true; 1110 case Intrinsic::riscv_masked_strided_load: 1111 Info.opc = ISD::INTRINSIC_W_CHAIN; 1112 Info.ptrVal = I.getArgOperand(1); 1113 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1114 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1115 Info.size = MemoryLocation::UnknownSize; 1116 Info.flags |= MachineMemOperand::MOLoad; 1117 return true; 1118 case Intrinsic::riscv_masked_strided_store: 1119 Info.opc = ISD::INTRINSIC_VOID; 1120 Info.ptrVal = I.getArgOperand(1); 1121 Info.memVT = 1122 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1123 Info.align = Align( 1124 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1125 8); 1126 Info.size = MemoryLocation::UnknownSize; 1127 Info.flags |= MachineMemOperand::MOStore; 1128 return true; 1129 case Intrinsic::riscv_seg2_load: 1130 case Intrinsic::riscv_seg3_load: 1131 case Intrinsic::riscv_seg4_load: 1132 case Intrinsic::riscv_seg5_load: 1133 case Intrinsic::riscv_seg6_load: 1134 case Intrinsic::riscv_seg7_load: 1135 case Intrinsic::riscv_seg8_load: 1136 Info.opc = ISD::INTRINSIC_W_CHAIN; 1137 Info.ptrVal = I.getArgOperand(0); 1138 Info.memVT = 1139 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1140 Info.align = 1141 Align(DL.getTypeSizeInBits( 1142 I.getType()->getStructElementType(0)->getScalarType()) / 1143 8); 1144 Info.size = MemoryLocation::UnknownSize; 1145 Info.flags |= MachineMemOperand::MOLoad; 1146 return true; 1147 } 1148 } 1149 1150 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1151 const AddrMode &AM, Type *Ty, 1152 unsigned AS, 1153 Instruction *I) const { 1154 // No global is ever allowed as a base. 1155 if (AM.BaseGV) 1156 return false; 1157 1158 // Require a 12-bit signed offset. 1159 if (!isInt<12>(AM.BaseOffs)) 1160 return false; 1161 1162 switch (AM.Scale) { 1163 case 0: // "r+i" or just "i", depending on HasBaseReg. 1164 break; 1165 case 1: 1166 if (!AM.HasBaseReg) // allow "r+i". 1167 break; 1168 return false; // disallow "r+r" or "r+r+i". 1169 default: 1170 return false; 1171 } 1172 1173 return true; 1174 } 1175 1176 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1177 return isInt<12>(Imm); 1178 } 1179 1180 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1181 return isInt<12>(Imm); 1182 } 1183 1184 // On RV32, 64-bit integers are split into their high and low parts and held 1185 // in two different registers, so the trunc is free since the low register can 1186 // just be used. 1187 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1188 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1189 return false; 1190 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1191 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1192 return (SrcBits == 64 && DestBits == 32); 1193 } 1194 1195 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1196 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1197 !SrcVT.isInteger() || !DstVT.isInteger()) 1198 return false; 1199 unsigned SrcBits = SrcVT.getSizeInBits(); 1200 unsigned DestBits = DstVT.getSizeInBits(); 1201 return (SrcBits == 64 && DestBits == 32); 1202 } 1203 1204 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1205 // Zexts are free if they can be combined with a load. 1206 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1207 // poorly with type legalization of compares preferring sext. 1208 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1209 EVT MemVT = LD->getMemoryVT(); 1210 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1211 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1212 LD->getExtensionType() == ISD::ZEXTLOAD)) 1213 return true; 1214 } 1215 1216 return TargetLowering::isZExtFree(Val, VT2); 1217 } 1218 1219 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1220 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1221 } 1222 1223 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1224 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1225 } 1226 1227 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1228 return Subtarget.hasStdExtZbb(); 1229 } 1230 1231 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1232 return Subtarget.hasStdExtZbb(); 1233 } 1234 1235 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1236 EVT VT = Y.getValueType(); 1237 1238 // FIXME: Support vectors once we have tests. 1239 if (VT.isVector()) 1240 return false; 1241 1242 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1243 Subtarget.hasStdExtZbkb()) && 1244 !isa<ConstantSDNode>(Y); 1245 } 1246 1247 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1248 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1249 auto *C = dyn_cast<ConstantSDNode>(Y); 1250 return C && C->getAPIntValue().ule(10); 1251 } 1252 1253 /// Check if sinking \p I's operands to I's basic block is profitable, because 1254 /// the operands can be folded into a target instruction, e.g. 1255 /// splats of scalars can fold into vector instructions. 1256 bool RISCVTargetLowering::shouldSinkOperands( 1257 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1258 using namespace llvm::PatternMatch; 1259 1260 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1261 return false; 1262 1263 auto IsSinker = [&](Instruction *I, int Operand) { 1264 switch (I->getOpcode()) { 1265 case Instruction::Add: 1266 case Instruction::Sub: 1267 case Instruction::Mul: 1268 case Instruction::And: 1269 case Instruction::Or: 1270 case Instruction::Xor: 1271 case Instruction::FAdd: 1272 case Instruction::FSub: 1273 case Instruction::FMul: 1274 case Instruction::FDiv: 1275 case Instruction::ICmp: 1276 case Instruction::FCmp: 1277 return true; 1278 case Instruction::Shl: 1279 case Instruction::LShr: 1280 case Instruction::AShr: 1281 case Instruction::UDiv: 1282 case Instruction::SDiv: 1283 case Instruction::URem: 1284 case Instruction::SRem: 1285 return Operand == 1; 1286 case Instruction::Call: 1287 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1288 switch (II->getIntrinsicID()) { 1289 case Intrinsic::fma: 1290 case Intrinsic::vp_fma: 1291 return Operand == 0 || Operand == 1; 1292 // FIXME: Our patterns can only match vx/vf instructions when the splat 1293 // it on the RHS, because TableGen doesn't recognize our VP operations 1294 // as commutative. 1295 case Intrinsic::vp_add: 1296 case Intrinsic::vp_mul: 1297 case Intrinsic::vp_and: 1298 case Intrinsic::vp_or: 1299 case Intrinsic::vp_xor: 1300 case Intrinsic::vp_fadd: 1301 case Intrinsic::vp_fmul: 1302 case Intrinsic::vp_shl: 1303 case Intrinsic::vp_lshr: 1304 case Intrinsic::vp_ashr: 1305 case Intrinsic::vp_udiv: 1306 case Intrinsic::vp_sdiv: 1307 case Intrinsic::vp_urem: 1308 case Intrinsic::vp_srem: 1309 return Operand == 1; 1310 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1311 // explicit patterns for both LHS and RHS (as 'vr' versions). 1312 case Intrinsic::vp_sub: 1313 case Intrinsic::vp_fsub: 1314 case Intrinsic::vp_fdiv: 1315 return Operand == 0 || Operand == 1; 1316 default: 1317 return false; 1318 } 1319 } 1320 return false; 1321 default: 1322 return false; 1323 } 1324 }; 1325 1326 for (auto OpIdx : enumerate(I->operands())) { 1327 if (!IsSinker(I, OpIdx.index())) 1328 continue; 1329 1330 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1331 // Make sure we are not already sinking this operand 1332 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1333 continue; 1334 1335 // We are looking for a splat that can be sunk. 1336 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1337 m_Undef(), m_ZeroMask()))) 1338 continue; 1339 1340 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1341 // and vector registers 1342 for (Use &U : Op->uses()) { 1343 Instruction *Insn = cast<Instruction>(U.getUser()); 1344 if (!IsSinker(Insn, U.getOperandNo())) 1345 return false; 1346 } 1347 1348 Ops.push_back(&Op->getOperandUse(0)); 1349 Ops.push_back(&OpIdx.value()); 1350 } 1351 return true; 1352 } 1353 1354 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1355 bool ForCodeSize) const { 1356 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1357 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1358 return false; 1359 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1360 return false; 1361 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1362 return false; 1363 return Imm.isZero(); 1364 } 1365 1366 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1367 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1368 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1369 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1370 } 1371 1372 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1373 CallingConv::ID CC, 1374 EVT VT) const { 1375 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1376 // We might still end up using a GPR but that will be decided based on ABI. 1377 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1378 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1379 return MVT::f32; 1380 1381 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1382 } 1383 1384 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1385 CallingConv::ID CC, 1386 EVT VT) const { 1387 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1388 // We might still end up using a GPR but that will be decided based on ABI. 1389 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1390 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1391 return 1; 1392 1393 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1394 } 1395 1396 // Changes the condition code and swaps operands if necessary, so the SetCC 1397 // operation matches one of the comparisons supported directly by branches 1398 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1399 // with 1/-1. 1400 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1401 ISD::CondCode &CC, SelectionDAG &DAG) { 1402 // Convert X > -1 to X >= 0. 1403 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1404 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1405 CC = ISD::SETGE; 1406 return; 1407 } 1408 // Convert X < 1 to 0 >= X. 1409 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1410 RHS = LHS; 1411 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1412 CC = ISD::SETGE; 1413 return; 1414 } 1415 1416 switch (CC) { 1417 default: 1418 break; 1419 case ISD::SETGT: 1420 case ISD::SETLE: 1421 case ISD::SETUGT: 1422 case ISD::SETULE: 1423 CC = ISD::getSetCCSwappedOperands(CC); 1424 std::swap(LHS, RHS); 1425 break; 1426 } 1427 } 1428 1429 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1430 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1431 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1432 if (VT.getVectorElementType() == MVT::i1) 1433 KnownSize *= 8; 1434 1435 switch (KnownSize) { 1436 default: 1437 llvm_unreachable("Invalid LMUL."); 1438 case 8: 1439 return RISCVII::VLMUL::LMUL_F8; 1440 case 16: 1441 return RISCVII::VLMUL::LMUL_F4; 1442 case 32: 1443 return RISCVII::VLMUL::LMUL_F2; 1444 case 64: 1445 return RISCVII::VLMUL::LMUL_1; 1446 case 128: 1447 return RISCVII::VLMUL::LMUL_2; 1448 case 256: 1449 return RISCVII::VLMUL::LMUL_4; 1450 case 512: 1451 return RISCVII::VLMUL::LMUL_8; 1452 } 1453 } 1454 1455 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1456 switch (LMul) { 1457 default: 1458 llvm_unreachable("Invalid LMUL."); 1459 case RISCVII::VLMUL::LMUL_F8: 1460 case RISCVII::VLMUL::LMUL_F4: 1461 case RISCVII::VLMUL::LMUL_F2: 1462 case RISCVII::VLMUL::LMUL_1: 1463 return RISCV::VRRegClassID; 1464 case RISCVII::VLMUL::LMUL_2: 1465 return RISCV::VRM2RegClassID; 1466 case RISCVII::VLMUL::LMUL_4: 1467 return RISCV::VRM4RegClassID; 1468 case RISCVII::VLMUL::LMUL_8: 1469 return RISCV::VRM8RegClassID; 1470 } 1471 } 1472 1473 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1474 RISCVII::VLMUL LMUL = getLMUL(VT); 1475 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1476 LMUL == RISCVII::VLMUL::LMUL_F4 || 1477 LMUL == RISCVII::VLMUL::LMUL_F2 || 1478 LMUL == RISCVII::VLMUL::LMUL_1) { 1479 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1480 "Unexpected subreg numbering"); 1481 return RISCV::sub_vrm1_0 + Index; 1482 } 1483 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1484 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1485 "Unexpected subreg numbering"); 1486 return RISCV::sub_vrm2_0 + Index; 1487 } 1488 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1489 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1490 "Unexpected subreg numbering"); 1491 return RISCV::sub_vrm4_0 + Index; 1492 } 1493 llvm_unreachable("Invalid vector type."); 1494 } 1495 1496 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1497 if (VT.getVectorElementType() == MVT::i1) 1498 return RISCV::VRRegClassID; 1499 return getRegClassIDForLMUL(getLMUL(VT)); 1500 } 1501 1502 // Attempt to decompose a subvector insert/extract between VecVT and 1503 // SubVecVT via subregister indices. Returns the subregister index that 1504 // can perform the subvector insert/extract with the given element index, as 1505 // well as the index corresponding to any leftover subvectors that must be 1506 // further inserted/extracted within the register class for SubVecVT. 1507 std::pair<unsigned, unsigned> 1508 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1509 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1510 const RISCVRegisterInfo *TRI) { 1511 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1512 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1513 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1514 "Register classes not ordered"); 1515 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1516 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1517 // Try to compose a subregister index that takes us from the incoming 1518 // LMUL>1 register class down to the outgoing one. At each step we half 1519 // the LMUL: 1520 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1521 // Note that this is not guaranteed to find a subregister index, such as 1522 // when we are extracting from one VR type to another. 1523 unsigned SubRegIdx = RISCV::NoSubRegister; 1524 for (const unsigned RCID : 1525 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1526 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1527 VecVT = VecVT.getHalfNumVectorElementsVT(); 1528 bool IsHi = 1529 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1530 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1531 getSubregIndexByMVT(VecVT, IsHi)); 1532 if (IsHi) 1533 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1534 } 1535 return {SubRegIdx, InsertExtractIdx}; 1536 } 1537 1538 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1539 // stores for those types. 1540 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1541 return !Subtarget.useRVVForFixedLengthVectors() || 1542 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1543 } 1544 1545 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1546 if (ScalarTy->isPointerTy()) 1547 return true; 1548 1549 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1550 ScalarTy->isIntegerTy(32)) 1551 return true; 1552 1553 if (ScalarTy->isIntegerTy(64)) 1554 return Subtarget.hasVInstructionsI64(); 1555 1556 if (ScalarTy->isHalfTy()) 1557 return Subtarget.hasVInstructionsF16(); 1558 if (ScalarTy->isFloatTy()) 1559 return Subtarget.hasVInstructionsF32(); 1560 if (ScalarTy->isDoubleTy()) 1561 return Subtarget.hasVInstructionsF64(); 1562 1563 return false; 1564 } 1565 1566 static SDValue getVLOperand(SDValue Op) { 1567 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1568 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1569 "Unexpected opcode"); 1570 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1571 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1572 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1573 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1574 if (!II) 1575 return SDValue(); 1576 return Op.getOperand(II->VLOperand + 1 + HasChain); 1577 } 1578 1579 static bool useRVVForFixedLengthVectorVT(MVT VT, 1580 const RISCVSubtarget &Subtarget) { 1581 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1582 if (!Subtarget.useRVVForFixedLengthVectors()) 1583 return false; 1584 1585 // We only support a set of vector types with a consistent maximum fixed size 1586 // across all supported vector element types to avoid legalization issues. 1587 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1588 // fixed-length vector type we support is 1024 bytes. 1589 if (VT.getFixedSizeInBits() > 1024 * 8) 1590 return false; 1591 1592 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1593 1594 MVT EltVT = VT.getVectorElementType(); 1595 1596 // Don't use RVV for vectors we cannot scalarize if required. 1597 switch (EltVT.SimpleTy) { 1598 // i1 is supported but has different rules. 1599 default: 1600 return false; 1601 case MVT::i1: 1602 // Masks can only use a single register. 1603 if (VT.getVectorNumElements() > MinVLen) 1604 return false; 1605 MinVLen /= 8; 1606 break; 1607 case MVT::i8: 1608 case MVT::i16: 1609 case MVT::i32: 1610 break; 1611 case MVT::i64: 1612 if (!Subtarget.hasVInstructionsI64()) 1613 return false; 1614 break; 1615 case MVT::f16: 1616 if (!Subtarget.hasVInstructionsF16()) 1617 return false; 1618 break; 1619 case MVT::f32: 1620 if (!Subtarget.hasVInstructionsF32()) 1621 return false; 1622 break; 1623 case MVT::f64: 1624 if (!Subtarget.hasVInstructionsF64()) 1625 return false; 1626 break; 1627 } 1628 1629 // Reject elements larger than ELEN. 1630 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1631 return false; 1632 1633 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1634 // Don't use RVV for types that don't fit. 1635 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1636 return false; 1637 1638 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1639 // the base fixed length RVV support in place. 1640 if (!VT.isPow2VectorType()) 1641 return false; 1642 1643 return true; 1644 } 1645 1646 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1647 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1648 } 1649 1650 // Return the largest legal scalable vector type that matches VT's element type. 1651 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1652 const RISCVSubtarget &Subtarget) { 1653 // This may be called before legal types are setup. 1654 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1655 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1656 "Expected legal fixed length vector!"); 1657 1658 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1659 unsigned MaxELen = Subtarget.getELEN(); 1660 1661 MVT EltVT = VT.getVectorElementType(); 1662 switch (EltVT.SimpleTy) { 1663 default: 1664 llvm_unreachable("unexpected element type for RVV container"); 1665 case MVT::i1: 1666 case MVT::i8: 1667 case MVT::i16: 1668 case MVT::i32: 1669 case MVT::i64: 1670 case MVT::f16: 1671 case MVT::f32: 1672 case MVT::f64: { 1673 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1674 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1675 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1676 unsigned NumElts = 1677 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1678 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1679 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1680 return MVT::getScalableVectorVT(EltVT, NumElts); 1681 } 1682 } 1683 } 1684 1685 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1686 const RISCVSubtarget &Subtarget) { 1687 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1688 Subtarget); 1689 } 1690 1691 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1692 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1693 } 1694 1695 // Grow V to consume an entire RVV register. 1696 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1697 const RISCVSubtarget &Subtarget) { 1698 assert(VT.isScalableVector() && 1699 "Expected to convert into a scalable vector!"); 1700 assert(V.getValueType().isFixedLengthVector() && 1701 "Expected a fixed length vector operand!"); 1702 SDLoc DL(V); 1703 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1704 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1705 } 1706 1707 // Shrink V so it's just big enough to maintain a VT's worth of data. 1708 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1709 const RISCVSubtarget &Subtarget) { 1710 assert(VT.isFixedLengthVector() && 1711 "Expected to convert into a fixed length vector!"); 1712 assert(V.getValueType().isScalableVector() && 1713 "Expected a scalable vector operand!"); 1714 SDLoc DL(V); 1715 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1716 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1717 } 1718 1719 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1720 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1721 // the vector type that it is contained in. 1722 static std::pair<SDValue, SDValue> 1723 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1724 const RISCVSubtarget &Subtarget) { 1725 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1726 MVT XLenVT = Subtarget.getXLenVT(); 1727 SDValue VL = VecVT.isFixedLengthVector() 1728 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1729 : DAG.getRegister(RISCV::X0, XLenVT); 1730 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1731 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1732 return {Mask, VL}; 1733 } 1734 1735 // As above but assuming the given type is a scalable vector type. 1736 static std::pair<SDValue, SDValue> 1737 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1738 const RISCVSubtarget &Subtarget) { 1739 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1740 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1741 } 1742 1743 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1744 // of either is (currently) supported. This can get us into an infinite loop 1745 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1746 // as a ..., etc. 1747 // Until either (or both) of these can reliably lower any node, reporting that 1748 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1749 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1750 // which is not desirable. 1751 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1752 EVT VT, unsigned DefinedValues) const { 1753 return false; 1754 } 1755 1756 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1757 const RISCVSubtarget &Subtarget) { 1758 // RISCV FP-to-int conversions saturate to the destination register size, but 1759 // don't produce 0 for nan. We can use a conversion instruction and fix the 1760 // nan case with a compare and a select. 1761 SDValue Src = Op.getOperand(0); 1762 1763 EVT DstVT = Op.getValueType(); 1764 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1765 1766 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1767 unsigned Opc; 1768 if (SatVT == DstVT) 1769 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1770 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1771 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1772 else 1773 return SDValue(); 1774 // FIXME: Support other SatVTs by clamping before or after the conversion. 1775 1776 SDLoc DL(Op); 1777 SDValue FpToInt = DAG.getNode( 1778 Opc, DL, DstVT, Src, 1779 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1780 1781 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1782 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1783 } 1784 1785 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1786 // and back. Taking care to avoid converting values that are nan or already 1787 // correct. 1788 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1789 // have FRM dependencies modeled yet. 1790 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1791 MVT VT = Op.getSimpleValueType(); 1792 assert(VT.isVector() && "Unexpected type"); 1793 1794 SDLoc DL(Op); 1795 1796 // Freeze the source since we are increasing the number of uses. 1797 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1798 1799 // Truncate to integer and convert back to FP. 1800 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1801 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1802 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1803 1804 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1805 1806 if (Op.getOpcode() == ISD::FCEIL) { 1807 // If the truncated value is the greater than or equal to the original 1808 // value, we've computed the ceil. Otherwise, we went the wrong way and 1809 // need to increase by 1. 1810 // FIXME: This should use a masked operation. Handle here or in isel? 1811 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1812 DAG.getConstantFP(1.0, DL, VT)); 1813 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1814 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1815 } else if (Op.getOpcode() == ISD::FFLOOR) { 1816 // If the truncated value is the less than or equal to the original value, 1817 // we've computed the floor. Otherwise, we went the wrong way and need to 1818 // decrease by 1. 1819 // FIXME: This should use a masked operation. Handle here or in isel? 1820 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1821 DAG.getConstantFP(1.0, DL, VT)); 1822 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1823 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1824 } 1825 1826 // Restore the original sign so that -0.0 is preserved. 1827 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1828 1829 // Determine the largest integer that can be represented exactly. This and 1830 // values larger than it don't have any fractional bits so don't need to 1831 // be converted. 1832 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1833 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1834 APFloat MaxVal = APFloat(FltSem); 1835 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1836 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1837 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1838 1839 // If abs(Src) was larger than MaxVal or nan, keep it. 1840 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1841 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1842 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1843 } 1844 1845 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1846 // This mode isn't supported in vector hardware on RISCV. But as long as we 1847 // aren't compiling with trapping math, we can emulate this with 1848 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1849 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1850 // dependencies modeled yet. 1851 // FIXME: Use masked operations to avoid final merge. 1852 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1853 MVT VT = Op.getSimpleValueType(); 1854 assert(VT.isVector() && "Unexpected type"); 1855 1856 SDLoc DL(Op); 1857 1858 // Freeze the source since we are increasing the number of uses. 1859 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1860 1861 // We do the conversion on the absolute value and fix the sign at the end. 1862 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1863 1864 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1865 bool Ignored; 1866 APFloat Point5Pred = APFloat(0.5f); 1867 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1868 Point5Pred.next(/*nextDown*/ true); 1869 1870 // Add the adjustment. 1871 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1872 DAG.getConstantFP(Point5Pred, DL, VT)); 1873 1874 // Truncate to integer and convert back to fp. 1875 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1876 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1877 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1878 1879 // Restore the original sign. 1880 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1881 1882 // Determine the largest integer that can be represented exactly. This and 1883 // values larger than it don't have any fractional bits so don't need to 1884 // be converted. 1885 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1886 APFloat MaxVal = APFloat(FltSem); 1887 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1888 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1889 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1890 1891 // If abs(Src) was larger than MaxVal or nan, keep it. 1892 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1893 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1894 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1895 } 1896 1897 struct VIDSequence { 1898 int64_t StepNumerator; 1899 unsigned StepDenominator; 1900 int64_t Addend; 1901 }; 1902 1903 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1904 // to the (non-zero) step S and start value X. This can be then lowered as the 1905 // RVV sequence (VID * S) + X, for example. 1906 // The step S is represented as an integer numerator divided by a positive 1907 // denominator. Note that the implementation currently only identifies 1908 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1909 // cannot detect 2/3, for example. 1910 // Note that this method will also match potentially unappealing index 1911 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1912 // determine whether this is worth generating code for. 1913 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1914 unsigned NumElts = Op.getNumOperands(); 1915 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1916 if (!Op.getValueType().isInteger()) 1917 return None; 1918 1919 Optional<unsigned> SeqStepDenom; 1920 Optional<int64_t> SeqStepNum, SeqAddend; 1921 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1922 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1923 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1924 // Assume undef elements match the sequence; we just have to be careful 1925 // when interpolating across them. 1926 if (Op.getOperand(Idx).isUndef()) 1927 continue; 1928 // The BUILD_VECTOR must be all constants. 1929 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1930 return None; 1931 1932 uint64_t Val = Op.getConstantOperandVal(Idx) & 1933 maskTrailingOnes<uint64_t>(EltSizeInBits); 1934 1935 if (PrevElt) { 1936 // Calculate the step since the last non-undef element, and ensure 1937 // it's consistent across the entire sequence. 1938 unsigned IdxDiff = Idx - PrevElt->second; 1939 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1940 1941 // A zero-value value difference means that we're somewhere in the middle 1942 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1943 // step change before evaluating the sequence. 1944 if (ValDiff == 0) 1945 continue; 1946 1947 int64_t Remainder = ValDiff % IdxDiff; 1948 // Normalize the step if it's greater than 1. 1949 if (Remainder != ValDiff) { 1950 // The difference must cleanly divide the element span. 1951 if (Remainder != 0) 1952 return None; 1953 ValDiff /= IdxDiff; 1954 IdxDiff = 1; 1955 } 1956 1957 if (!SeqStepNum) 1958 SeqStepNum = ValDiff; 1959 else if (ValDiff != SeqStepNum) 1960 return None; 1961 1962 if (!SeqStepDenom) 1963 SeqStepDenom = IdxDiff; 1964 else if (IdxDiff != *SeqStepDenom) 1965 return None; 1966 } 1967 1968 // Record this non-undef element for later. 1969 if (!PrevElt || PrevElt->first != Val) 1970 PrevElt = std::make_pair(Val, Idx); 1971 } 1972 1973 // We need to have logged a step for this to count as a legal index sequence. 1974 if (!SeqStepNum || !SeqStepDenom) 1975 return None; 1976 1977 // Loop back through the sequence and validate elements we might have skipped 1978 // while waiting for a valid step. While doing this, log any sequence addend. 1979 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1980 if (Op.getOperand(Idx).isUndef()) 1981 continue; 1982 uint64_t Val = Op.getConstantOperandVal(Idx) & 1983 maskTrailingOnes<uint64_t>(EltSizeInBits); 1984 uint64_t ExpectedVal = 1985 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1986 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1987 if (!SeqAddend) 1988 SeqAddend = Addend; 1989 else if (Addend != SeqAddend) 1990 return None; 1991 } 1992 1993 assert(SeqAddend && "Must have an addend if we have a step"); 1994 1995 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1996 } 1997 1998 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1999 // and lower it as a VRGATHER_VX_VL from the source vector. 2000 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 2001 SelectionDAG &DAG, 2002 const RISCVSubtarget &Subtarget) { 2003 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2004 return SDValue(); 2005 SDValue Vec = SplatVal.getOperand(0); 2006 // Only perform this optimization on vectors of the same size for simplicity. 2007 if (Vec.getValueType() != VT) 2008 return SDValue(); 2009 SDValue Idx = SplatVal.getOperand(1); 2010 // The index must be a legal type. 2011 if (Idx.getValueType() != Subtarget.getXLenVT()) 2012 return SDValue(); 2013 2014 MVT ContainerVT = VT; 2015 if (VT.isFixedLengthVector()) { 2016 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2017 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2018 } 2019 2020 SDValue Mask, VL; 2021 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2022 2023 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2024 Idx, Mask, VL); 2025 2026 if (!VT.isFixedLengthVector()) 2027 return Gather; 2028 2029 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2030 } 2031 2032 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2033 const RISCVSubtarget &Subtarget) { 2034 MVT VT = Op.getSimpleValueType(); 2035 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2036 2037 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2038 2039 SDLoc DL(Op); 2040 SDValue Mask, VL; 2041 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2042 2043 MVT XLenVT = Subtarget.getXLenVT(); 2044 unsigned NumElts = Op.getNumOperands(); 2045 2046 if (VT.getVectorElementType() == MVT::i1) { 2047 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2048 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2049 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2050 } 2051 2052 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2053 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2054 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2055 } 2056 2057 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2058 // scalar integer chunks whose bit-width depends on the number of mask 2059 // bits and XLEN. 2060 // First, determine the most appropriate scalar integer type to use. This 2061 // is at most XLenVT, but may be shrunk to a smaller vector element type 2062 // according to the size of the final vector - use i8 chunks rather than 2063 // XLenVT if we're producing a v8i1. This results in more consistent 2064 // codegen across RV32 and RV64. 2065 unsigned NumViaIntegerBits = 2066 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2067 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2068 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2069 // If we have to use more than one INSERT_VECTOR_ELT then this 2070 // optimization is likely to increase code size; avoid peforming it in 2071 // such a case. We can use a load from a constant pool in this case. 2072 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2073 return SDValue(); 2074 // Now we can create our integer vector type. Note that it may be larger 2075 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2076 MVT IntegerViaVecVT = 2077 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2078 divideCeil(NumElts, NumViaIntegerBits)); 2079 2080 uint64_t Bits = 0; 2081 unsigned BitPos = 0, IntegerEltIdx = 0; 2082 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2083 2084 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2085 // Once we accumulate enough bits to fill our scalar type, insert into 2086 // our vector and clear our accumulated data. 2087 if (I != 0 && I % NumViaIntegerBits == 0) { 2088 if (NumViaIntegerBits <= 32) 2089 Bits = SignExtend64(Bits, 32); 2090 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2091 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2092 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2093 Bits = 0; 2094 BitPos = 0; 2095 IntegerEltIdx++; 2096 } 2097 SDValue V = Op.getOperand(I); 2098 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2099 Bits |= ((uint64_t)BitValue << BitPos); 2100 } 2101 2102 // Insert the (remaining) scalar value into position in our integer 2103 // vector type. 2104 if (NumViaIntegerBits <= 32) 2105 Bits = SignExtend64(Bits, 32); 2106 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2107 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2108 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2109 2110 if (NumElts < NumViaIntegerBits) { 2111 // If we're producing a smaller vector than our minimum legal integer 2112 // type, bitcast to the equivalent (known-legal) mask type, and extract 2113 // our final mask. 2114 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2115 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2116 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2117 DAG.getConstant(0, DL, XLenVT)); 2118 } else { 2119 // Else we must have produced an integer type with the same size as the 2120 // mask type; bitcast for the final result. 2121 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2122 Vec = DAG.getBitcast(VT, Vec); 2123 } 2124 2125 return Vec; 2126 } 2127 2128 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2129 // vector type, we have a legal equivalently-sized i8 type, so we can use 2130 // that. 2131 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2132 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2133 2134 SDValue WideVec; 2135 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2136 // For a splat, perform a scalar truncate before creating the wider 2137 // vector. 2138 assert(Splat.getValueType() == XLenVT && 2139 "Unexpected type for i1 splat value"); 2140 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2141 DAG.getConstant(1, DL, XLenVT)); 2142 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2143 } else { 2144 SmallVector<SDValue, 8> Ops(Op->op_values()); 2145 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2146 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2147 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2148 } 2149 2150 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2151 } 2152 2153 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2154 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2155 return Gather; 2156 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2157 : RISCVISD::VMV_V_X_VL; 2158 Splat = 2159 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2160 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2161 } 2162 2163 // Try and match index sequences, which we can lower to the vid instruction 2164 // with optional modifications. An all-undef vector is matched by 2165 // getSplatValue, above. 2166 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2167 int64_t StepNumerator = SimpleVID->StepNumerator; 2168 unsigned StepDenominator = SimpleVID->StepDenominator; 2169 int64_t Addend = SimpleVID->Addend; 2170 2171 assert(StepNumerator != 0 && "Invalid step"); 2172 bool Negate = false; 2173 int64_t SplatStepVal = StepNumerator; 2174 unsigned StepOpcode = ISD::MUL; 2175 if (StepNumerator != 1) { 2176 if (isPowerOf2_64(std::abs(StepNumerator))) { 2177 Negate = StepNumerator < 0; 2178 StepOpcode = ISD::SHL; 2179 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2180 } 2181 } 2182 2183 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2184 // threshold since it's the immediate value many RVV instructions accept. 2185 // There is no vmul.vi instruction so ensure multiply constant can fit in 2186 // a single addi instruction. 2187 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2188 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2189 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2190 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2191 // Convert right out of the scalable type so we can use standard ISD 2192 // nodes for the rest of the computation. If we used scalable types with 2193 // these, we'd lose the fixed-length vector info and generate worse 2194 // vsetvli code. 2195 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2196 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2197 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2198 SDValue SplatStep = DAG.getSplatBuildVector( 2199 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2200 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2201 } 2202 if (StepDenominator != 1) { 2203 SDValue SplatStep = DAG.getSplatBuildVector( 2204 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2205 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2206 } 2207 if (Addend != 0 || Negate) { 2208 SDValue SplatAddend = DAG.getSplatBuildVector( 2209 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2210 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2211 } 2212 return VID; 2213 } 2214 } 2215 2216 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2217 // when re-interpreted as a vector with a larger element type. For example, 2218 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2219 // could be instead splat as 2220 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2221 // TODO: This optimization could also work on non-constant splats, but it 2222 // would require bit-manipulation instructions to construct the splat value. 2223 SmallVector<SDValue> Sequence; 2224 unsigned EltBitSize = VT.getScalarSizeInBits(); 2225 const auto *BV = cast<BuildVectorSDNode>(Op); 2226 if (VT.isInteger() && EltBitSize < 64 && 2227 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2228 BV->getRepeatedSequence(Sequence) && 2229 (Sequence.size() * EltBitSize) <= 64) { 2230 unsigned SeqLen = Sequence.size(); 2231 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2232 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2233 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2234 ViaIntVT == MVT::i64) && 2235 "Unexpected sequence type"); 2236 2237 unsigned EltIdx = 0; 2238 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2239 uint64_t SplatValue = 0; 2240 // Construct the amalgamated value which can be splatted as this larger 2241 // vector type. 2242 for (const auto &SeqV : Sequence) { 2243 if (!SeqV.isUndef()) 2244 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2245 << (EltIdx * EltBitSize)); 2246 EltIdx++; 2247 } 2248 2249 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2250 // achieve better constant materializion. 2251 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2252 SplatValue = SignExtend64(SplatValue, 32); 2253 2254 // Since we can't introduce illegal i64 types at this stage, we can only 2255 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2256 // way we can use RVV instructions to splat. 2257 assert((ViaIntVT.bitsLE(XLenVT) || 2258 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2259 "Unexpected bitcast sequence"); 2260 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2261 SDValue ViaVL = 2262 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2263 MVT ViaContainerVT = 2264 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2265 SDValue Splat = 2266 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2267 DAG.getUNDEF(ViaContainerVT), 2268 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2269 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2270 return DAG.getBitcast(VT, Splat); 2271 } 2272 } 2273 2274 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2275 // which constitute a large proportion of the elements. In such cases we can 2276 // splat a vector with the dominant element and make up the shortfall with 2277 // INSERT_VECTOR_ELTs. 2278 // Note that this includes vectors of 2 elements by association. The 2279 // upper-most element is the "dominant" one, allowing us to use a splat to 2280 // "insert" the upper element, and an insert of the lower element at position 2281 // 0, which improves codegen. 2282 SDValue DominantValue; 2283 unsigned MostCommonCount = 0; 2284 DenseMap<SDValue, unsigned> ValueCounts; 2285 unsigned NumUndefElts = 2286 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2287 2288 // Track the number of scalar loads we know we'd be inserting, estimated as 2289 // any non-zero floating-point constant. Other kinds of element are either 2290 // already in registers or are materialized on demand. The threshold at which 2291 // a vector load is more desirable than several scalar materializion and 2292 // vector-insertion instructions is not known. 2293 unsigned NumScalarLoads = 0; 2294 2295 for (SDValue V : Op->op_values()) { 2296 if (V.isUndef()) 2297 continue; 2298 2299 ValueCounts.insert(std::make_pair(V, 0)); 2300 unsigned &Count = ValueCounts[V]; 2301 2302 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2303 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2304 2305 // Is this value dominant? In case of a tie, prefer the highest element as 2306 // it's cheaper to insert near the beginning of a vector than it is at the 2307 // end. 2308 if (++Count >= MostCommonCount) { 2309 DominantValue = V; 2310 MostCommonCount = Count; 2311 } 2312 } 2313 2314 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2315 unsigned NumDefElts = NumElts - NumUndefElts; 2316 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2317 2318 // Don't perform this optimization when optimizing for size, since 2319 // materializing elements and inserting them tends to cause code bloat. 2320 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2321 ((MostCommonCount > DominantValueCountThreshold) || 2322 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2323 // Start by splatting the most common element. 2324 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2325 2326 DenseSet<SDValue> Processed{DominantValue}; 2327 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2328 for (const auto &OpIdx : enumerate(Op->ops())) { 2329 const SDValue &V = OpIdx.value(); 2330 if (V.isUndef() || !Processed.insert(V).second) 2331 continue; 2332 if (ValueCounts[V] == 1) { 2333 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2334 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2335 } else { 2336 // Blend in all instances of this value using a VSELECT, using a 2337 // mask where each bit signals whether that element is the one 2338 // we're after. 2339 SmallVector<SDValue> Ops; 2340 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2341 return DAG.getConstant(V == V1, DL, XLenVT); 2342 }); 2343 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2344 DAG.getBuildVector(SelMaskTy, DL, Ops), 2345 DAG.getSplatBuildVector(VT, DL, V), Vec); 2346 } 2347 } 2348 2349 return Vec; 2350 } 2351 2352 return SDValue(); 2353 } 2354 2355 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2356 SDValue Lo, SDValue Hi, SDValue VL, 2357 SelectionDAG &DAG) { 2358 if (!Passthru) 2359 Passthru = DAG.getUNDEF(VT); 2360 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2361 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2362 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2363 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2364 // node in order to try and match RVV vector/scalar instructions. 2365 if ((LoC >> 31) == HiC) 2366 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2367 2368 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2369 // vmv.v.x whose EEW = 32 to lower it. 2370 auto *Const = dyn_cast<ConstantSDNode>(VL); 2371 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2372 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2373 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2374 // access the subtarget here now. 2375 auto InterVec = DAG.getNode( 2376 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2377 DAG.getRegister(RISCV::X0, MVT::i32)); 2378 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2379 } 2380 } 2381 2382 // Fall back to a stack store and stride x0 vector load. 2383 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2384 Hi, VL); 2385 } 2386 2387 // Called by type legalization to handle splat of i64 on RV32. 2388 // FIXME: We can optimize this when the type has sign or zero bits in one 2389 // of the halves. 2390 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2391 SDValue Scalar, SDValue VL, 2392 SelectionDAG &DAG) { 2393 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2394 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2395 DAG.getConstant(0, DL, MVT::i32)); 2396 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2397 DAG.getConstant(1, DL, MVT::i32)); 2398 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2399 } 2400 2401 // This function lowers a splat of a scalar operand Splat with the vector 2402 // length VL. It ensures the final sequence is type legal, which is useful when 2403 // lowering a splat after type legalization. 2404 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2405 MVT VT, SDLoc DL, SelectionDAG &DAG, 2406 const RISCVSubtarget &Subtarget) { 2407 bool HasPassthru = Passthru && !Passthru.isUndef(); 2408 if (!HasPassthru && !Passthru) 2409 Passthru = DAG.getUNDEF(VT); 2410 if (VT.isFloatingPoint()) { 2411 // If VL is 1, we could use vfmv.s.f. 2412 if (isOneConstant(VL)) 2413 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2414 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2415 } 2416 2417 MVT XLenVT = Subtarget.getXLenVT(); 2418 2419 // Simplest case is that the operand needs to be promoted to XLenVT. 2420 if (Scalar.getValueType().bitsLE(XLenVT)) { 2421 // If the operand is a constant, sign extend to increase our chances 2422 // of being able to use a .vi instruction. ANY_EXTEND would become a 2423 // a zero extend and the simm5 check in isel would fail. 2424 // FIXME: Should we ignore the upper bits in isel instead? 2425 unsigned ExtOpc = 2426 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2427 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2428 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2429 // If VL is 1 and the scalar value won't benefit from immediate, we could 2430 // use vmv.s.x. 2431 if (isOneConstant(VL) && 2432 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2433 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2434 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2435 } 2436 2437 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2438 "Unexpected scalar for splat lowering!"); 2439 2440 if (isOneConstant(VL) && isNullConstant(Scalar)) 2441 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2442 DAG.getConstant(0, DL, XLenVT), VL); 2443 2444 // Otherwise use the more complicated splatting algorithm. 2445 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2446 } 2447 2448 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2449 const RISCVSubtarget &Subtarget) { 2450 // We need to be able to widen elements to the next larger integer type. 2451 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2452 return false; 2453 2454 int Size = Mask.size(); 2455 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2456 2457 int Srcs[] = {-1, -1}; 2458 for (int i = 0; i != Size; ++i) { 2459 // Ignore undef elements. 2460 if (Mask[i] < 0) 2461 continue; 2462 2463 // Is this an even or odd element. 2464 int Pol = i % 2; 2465 2466 // Ensure we consistently use the same source for this element polarity. 2467 int Src = Mask[i] / Size; 2468 if (Srcs[Pol] < 0) 2469 Srcs[Pol] = Src; 2470 if (Srcs[Pol] != Src) 2471 return false; 2472 2473 // Make sure the element within the source is appropriate for this element 2474 // in the destination. 2475 int Elt = Mask[i] % Size; 2476 if (Elt != i / 2) 2477 return false; 2478 } 2479 2480 // We need to find a source for each polarity and they can't be the same. 2481 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2482 return false; 2483 2484 // Swap the sources if the second source was in the even polarity. 2485 SwapSources = Srcs[0] > Srcs[1]; 2486 2487 return true; 2488 } 2489 2490 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2491 /// and then extract the original number of elements from the rotated result. 2492 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2493 /// returned rotation amount is for a rotate right, where elements move from 2494 /// higher elements to lower elements. \p LoSrc indicates the first source 2495 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2496 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2497 /// 0 or 1 if a rotation is found. 2498 /// 2499 /// NOTE: We talk about rotate to the right which matches how bit shift and 2500 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2501 /// and the table below write vectors with the lowest elements on the left. 2502 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2503 int Size = Mask.size(); 2504 2505 // We need to detect various ways of spelling a rotation: 2506 // [11, 12, 13, 14, 15, 0, 1, 2] 2507 // [-1, 12, 13, 14, -1, -1, 1, -1] 2508 // [-1, -1, -1, -1, -1, -1, 1, 2] 2509 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2510 // [-1, 4, 5, 6, -1, -1, 9, -1] 2511 // [-1, 4, 5, 6, -1, -1, -1, -1] 2512 int Rotation = 0; 2513 LoSrc = -1; 2514 HiSrc = -1; 2515 for (int i = 0; i != Size; ++i) { 2516 int M = Mask[i]; 2517 if (M < 0) 2518 continue; 2519 2520 // Determine where a rotate vector would have started. 2521 int StartIdx = i - (M % Size); 2522 // The identity rotation isn't interesting, stop. 2523 if (StartIdx == 0) 2524 return -1; 2525 2526 // If we found the tail of a vector the rotation must be the missing 2527 // front. If we found the head of a vector, it must be how much of the 2528 // head. 2529 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2530 2531 if (Rotation == 0) 2532 Rotation = CandidateRotation; 2533 else if (Rotation != CandidateRotation) 2534 // The rotations don't match, so we can't match this mask. 2535 return -1; 2536 2537 // Compute which value this mask is pointing at. 2538 int MaskSrc = M < Size ? 0 : 1; 2539 2540 // Compute which of the two target values this index should be assigned to. 2541 // This reflects whether the high elements are remaining or the low elemnts 2542 // are remaining. 2543 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2544 2545 // Either set up this value if we've not encountered it before, or check 2546 // that it remains consistent. 2547 if (TargetSrc < 0) 2548 TargetSrc = MaskSrc; 2549 else if (TargetSrc != MaskSrc) 2550 // This may be a rotation, but it pulls from the inputs in some 2551 // unsupported interleaving. 2552 return -1; 2553 } 2554 2555 // Check that we successfully analyzed the mask, and normalize the results. 2556 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2557 assert((LoSrc >= 0 || HiSrc >= 0) && 2558 "Failed to find a rotated input vector!"); 2559 2560 return Rotation; 2561 } 2562 2563 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2564 const RISCVSubtarget &Subtarget) { 2565 SDValue V1 = Op.getOperand(0); 2566 SDValue V2 = Op.getOperand(1); 2567 SDLoc DL(Op); 2568 MVT XLenVT = Subtarget.getXLenVT(); 2569 MVT VT = Op.getSimpleValueType(); 2570 unsigned NumElts = VT.getVectorNumElements(); 2571 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2572 2573 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2574 2575 SDValue TrueMask, VL; 2576 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2577 2578 if (SVN->isSplat()) { 2579 const int Lane = SVN->getSplatIndex(); 2580 if (Lane >= 0) { 2581 MVT SVT = VT.getVectorElementType(); 2582 2583 // Turn splatted vector load into a strided load with an X0 stride. 2584 SDValue V = V1; 2585 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2586 // with undef. 2587 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2588 int Offset = Lane; 2589 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2590 int OpElements = 2591 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2592 V = V.getOperand(Offset / OpElements); 2593 Offset %= OpElements; 2594 } 2595 2596 // We need to ensure the load isn't atomic or volatile. 2597 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2598 auto *Ld = cast<LoadSDNode>(V); 2599 Offset *= SVT.getStoreSize(); 2600 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2601 TypeSize::Fixed(Offset), DL); 2602 2603 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2604 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2605 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2606 SDValue IntID = 2607 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2608 SDValue Ops[] = {Ld->getChain(), 2609 IntID, 2610 DAG.getUNDEF(ContainerVT), 2611 NewAddr, 2612 DAG.getRegister(RISCV::X0, XLenVT), 2613 VL}; 2614 SDValue NewLoad = DAG.getMemIntrinsicNode( 2615 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2616 DAG.getMachineFunction().getMachineMemOperand( 2617 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2618 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2619 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2620 } 2621 2622 // Otherwise use a scalar load and splat. This will give the best 2623 // opportunity to fold a splat into the operation. ISel can turn it into 2624 // the x0 strided load if we aren't able to fold away the select. 2625 if (SVT.isFloatingPoint()) 2626 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2627 Ld->getPointerInfo().getWithOffset(Offset), 2628 Ld->getOriginalAlign(), 2629 Ld->getMemOperand()->getFlags()); 2630 else 2631 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2632 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2633 Ld->getOriginalAlign(), 2634 Ld->getMemOperand()->getFlags()); 2635 DAG.makeEquivalentMemoryOrdering(Ld, V); 2636 2637 unsigned Opc = 2638 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2639 SDValue Splat = 2640 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2641 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2642 } 2643 2644 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2645 assert(Lane < (int)NumElts && "Unexpected lane!"); 2646 SDValue Gather = 2647 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2648 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2649 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2650 } 2651 } 2652 2653 ArrayRef<int> Mask = SVN->getMask(); 2654 2655 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2656 // be undef which can be handled with a single SLIDEDOWN/UP. 2657 int LoSrc, HiSrc; 2658 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2659 if (Rotation > 0) { 2660 SDValue LoV, HiV; 2661 if (LoSrc >= 0) { 2662 LoV = LoSrc == 0 ? V1 : V2; 2663 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2664 } 2665 if (HiSrc >= 0) { 2666 HiV = HiSrc == 0 ? V1 : V2; 2667 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2668 } 2669 2670 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2671 // to slide LoV up by (NumElts - Rotation). 2672 unsigned InvRotate = NumElts - Rotation; 2673 2674 SDValue Res = DAG.getUNDEF(ContainerVT); 2675 if (HiV) { 2676 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2677 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2678 // causes multiple vsetvlis in some test cases such as lowering 2679 // reduce.mul 2680 SDValue DownVL = VL; 2681 if (LoV) 2682 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2683 Res = 2684 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2685 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2686 } 2687 if (LoV) 2688 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2689 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2690 2691 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2692 } 2693 2694 // Detect an interleave shuffle and lower to 2695 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2696 bool SwapSources; 2697 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2698 // Swap sources if needed. 2699 if (SwapSources) 2700 std::swap(V1, V2); 2701 2702 // Extract the lower half of the vectors. 2703 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2704 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2705 DAG.getConstant(0, DL, XLenVT)); 2706 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2707 DAG.getConstant(0, DL, XLenVT)); 2708 2709 // Double the element width and halve the number of elements in an int type. 2710 unsigned EltBits = VT.getScalarSizeInBits(); 2711 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2712 MVT WideIntVT = 2713 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2714 // Convert this to a scalable vector. We need to base this on the 2715 // destination size to ensure there's always a type with a smaller LMUL. 2716 MVT WideIntContainerVT = 2717 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2718 2719 // Convert sources to scalable vectors with the same element count as the 2720 // larger type. 2721 MVT HalfContainerVT = MVT::getVectorVT( 2722 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2723 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2724 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2725 2726 // Cast sources to integer. 2727 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2728 MVT IntHalfVT = 2729 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2730 V1 = DAG.getBitcast(IntHalfVT, V1); 2731 V2 = DAG.getBitcast(IntHalfVT, V2); 2732 2733 // Freeze V2 since we use it twice and we need to be sure that the add and 2734 // multiply see the same value. 2735 V2 = DAG.getFreeze(V2); 2736 2737 // Recreate TrueMask using the widened type's element count. 2738 MVT MaskVT = 2739 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2740 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2741 2742 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2743 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2744 V2, TrueMask, VL); 2745 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2746 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2747 DAG.getUNDEF(IntHalfVT), 2748 DAG.getAllOnesConstant(DL, XLenVT)); 2749 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2750 V2, Multiplier, TrueMask, VL); 2751 // Add the new copies to our previous addition giving us 2^eltbits copies of 2752 // V2. This is equivalent to shifting V2 left by eltbits. This should 2753 // combine with the vwmulu.vv above to form vwmaccu.vv. 2754 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2755 TrueMask, VL); 2756 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2757 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2758 // vector VT. 2759 ContainerVT = 2760 MVT::getVectorVT(VT.getVectorElementType(), 2761 WideIntContainerVT.getVectorElementCount() * 2); 2762 Add = DAG.getBitcast(ContainerVT, Add); 2763 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2764 } 2765 2766 // Detect shuffles which can be re-expressed as vector selects; these are 2767 // shuffles in which each element in the destination is taken from an element 2768 // at the corresponding index in either source vectors. 2769 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2770 int MaskIndex = MaskIdx.value(); 2771 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2772 }); 2773 2774 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2775 2776 SmallVector<SDValue> MaskVals; 2777 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2778 // merged with a second vrgather. 2779 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2780 2781 // By default we preserve the original operand order, and use a mask to 2782 // select LHS as true and RHS as false. However, since RVV vector selects may 2783 // feature splats but only on the LHS, we may choose to invert our mask and 2784 // instead select between RHS and LHS. 2785 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2786 bool InvertMask = IsSelect == SwapOps; 2787 2788 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2789 // half. 2790 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2791 2792 // Now construct the mask that will be used by the vselect or blended 2793 // vrgather operation. For vrgathers, construct the appropriate indices into 2794 // each vector. 2795 for (int MaskIndex : Mask) { 2796 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2797 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2798 if (!IsSelect) { 2799 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2800 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2801 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2802 : DAG.getUNDEF(XLenVT)); 2803 GatherIndicesRHS.push_back( 2804 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2805 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2806 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2807 ++LHSIndexCounts[MaskIndex]; 2808 if (!IsLHSOrUndefIndex) 2809 ++RHSIndexCounts[MaskIndex - NumElts]; 2810 } 2811 } 2812 2813 if (SwapOps) { 2814 std::swap(V1, V2); 2815 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2816 } 2817 2818 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2819 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2820 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2821 2822 if (IsSelect) 2823 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2824 2825 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2826 // On such a large vector we're unable to use i8 as the index type. 2827 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2828 // may involve vector splitting if we're already at LMUL=8, or our 2829 // user-supplied maximum fixed-length LMUL. 2830 return SDValue(); 2831 } 2832 2833 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2834 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2835 MVT IndexVT = VT.changeTypeToInteger(); 2836 // Since we can't introduce illegal index types at this stage, use i16 and 2837 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2838 // than XLenVT. 2839 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2840 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2841 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2842 } 2843 2844 MVT IndexContainerVT = 2845 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2846 2847 SDValue Gather; 2848 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2849 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2850 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2851 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2852 Subtarget); 2853 } else { 2854 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2855 // If only one index is used, we can use a "splat" vrgather. 2856 // TODO: We can splat the most-common index and fix-up any stragglers, if 2857 // that's beneficial. 2858 if (LHSIndexCounts.size() == 1) { 2859 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2860 Gather = 2861 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2862 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2863 } else { 2864 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2865 LHSIndices = 2866 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2867 2868 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2869 TrueMask, VL); 2870 } 2871 } 2872 2873 // If a second vector operand is used by this shuffle, blend it in with an 2874 // additional vrgather. 2875 if (!V2.isUndef()) { 2876 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2877 // If only one index is used, we can use a "splat" vrgather. 2878 // TODO: We can splat the most-common index and fix-up any stragglers, if 2879 // that's beneficial. 2880 if (RHSIndexCounts.size() == 1) { 2881 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2882 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2883 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2884 } else { 2885 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2886 RHSIndices = 2887 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2888 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2889 VL); 2890 } 2891 2892 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2893 SelectMask = 2894 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2895 2896 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2897 Gather, VL); 2898 } 2899 2900 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2901 } 2902 2903 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2904 // Support splats for any type. These should type legalize well. 2905 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2906 return true; 2907 2908 // Only support legal VTs for other shuffles for now. 2909 if (!isTypeLegal(VT)) 2910 return false; 2911 2912 MVT SVT = VT.getSimpleVT(); 2913 2914 bool SwapSources; 2915 int LoSrc, HiSrc; 2916 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2917 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2918 } 2919 2920 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2921 SDLoc DL, SelectionDAG &DAG, 2922 const RISCVSubtarget &Subtarget) { 2923 if (VT.isScalableVector()) 2924 return DAG.getFPExtendOrRound(Op, DL, VT); 2925 assert(VT.isFixedLengthVector() && 2926 "Unexpected value type for RVV FP extend/round lowering"); 2927 SDValue Mask, VL; 2928 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2929 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2930 ? RISCVISD::FP_EXTEND_VL 2931 : RISCVISD::FP_ROUND_VL; 2932 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2933 } 2934 2935 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2936 // the exponent. 2937 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2938 MVT VT = Op.getSimpleValueType(); 2939 unsigned EltSize = VT.getScalarSizeInBits(); 2940 SDValue Src = Op.getOperand(0); 2941 SDLoc DL(Op); 2942 2943 // We need a FP type that can represent the value. 2944 // TODO: Use f16 for i8 when possible? 2945 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2946 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2947 2948 // Legal types should have been checked in the RISCVTargetLowering 2949 // constructor. 2950 // TODO: Splitting may make sense in some cases. 2951 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2952 "Expected legal float type!"); 2953 2954 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2955 // The trailing zero count is equal to log2 of this single bit value. 2956 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2957 SDValue Neg = 2958 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2959 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2960 } 2961 2962 // We have a legal FP type, convert to it. 2963 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2964 // Bitcast to integer and shift the exponent to the LSB. 2965 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2966 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2967 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2968 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2969 DAG.getConstant(ShiftAmt, DL, IntVT)); 2970 // Truncate back to original type to allow vnsrl. 2971 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2972 // The exponent contains log2 of the value in biased form. 2973 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2974 2975 // For trailing zeros, we just need to subtract the bias. 2976 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2977 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2978 DAG.getConstant(ExponentBias, DL, VT)); 2979 2980 // For leading zeros, we need to remove the bias and convert from log2 to 2981 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2982 unsigned Adjust = ExponentBias + (EltSize - 1); 2983 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2984 } 2985 2986 // While RVV has alignment restrictions, we should always be able to load as a 2987 // legal equivalently-sized byte-typed vector instead. This method is 2988 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2989 // the load is already correctly-aligned, it returns SDValue(). 2990 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2991 SelectionDAG &DAG) const { 2992 auto *Load = cast<LoadSDNode>(Op); 2993 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2994 2995 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2996 Load->getMemoryVT(), 2997 *Load->getMemOperand())) 2998 return SDValue(); 2999 3000 SDLoc DL(Op); 3001 MVT VT = Op.getSimpleValueType(); 3002 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3003 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3004 "Unexpected unaligned RVV load type"); 3005 MVT NewVT = 3006 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3007 assert(NewVT.isValid() && 3008 "Expecting equally-sized RVV vector types to be legal"); 3009 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 3010 Load->getPointerInfo(), Load->getOriginalAlign(), 3011 Load->getMemOperand()->getFlags()); 3012 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3013 } 3014 3015 // While RVV has alignment restrictions, we should always be able to store as a 3016 // legal equivalently-sized byte-typed vector instead. This method is 3017 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3018 // returns SDValue() if the store is already correctly aligned. 3019 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3020 SelectionDAG &DAG) const { 3021 auto *Store = cast<StoreSDNode>(Op); 3022 assert(Store && Store->getValue().getValueType().isVector() && 3023 "Expected vector store"); 3024 3025 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3026 Store->getMemoryVT(), 3027 *Store->getMemOperand())) 3028 return SDValue(); 3029 3030 SDLoc DL(Op); 3031 SDValue StoredVal = Store->getValue(); 3032 MVT VT = StoredVal.getSimpleValueType(); 3033 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3034 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3035 "Unexpected unaligned RVV store type"); 3036 MVT NewVT = 3037 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3038 assert(NewVT.isValid() && 3039 "Expecting equally-sized RVV vector types to be legal"); 3040 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3041 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3042 Store->getPointerInfo(), Store->getOriginalAlign(), 3043 Store->getMemOperand()->getFlags()); 3044 } 3045 3046 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3047 SelectionDAG &DAG) const { 3048 switch (Op.getOpcode()) { 3049 default: 3050 report_fatal_error("unimplemented operand"); 3051 case ISD::GlobalAddress: 3052 return lowerGlobalAddress(Op, DAG); 3053 case ISD::BlockAddress: 3054 return lowerBlockAddress(Op, DAG); 3055 case ISD::ConstantPool: 3056 return lowerConstantPool(Op, DAG); 3057 case ISD::JumpTable: 3058 return lowerJumpTable(Op, DAG); 3059 case ISD::GlobalTLSAddress: 3060 return lowerGlobalTLSAddress(Op, DAG); 3061 case ISD::SELECT: 3062 return lowerSELECT(Op, DAG); 3063 case ISD::BRCOND: 3064 return lowerBRCOND(Op, DAG); 3065 case ISD::VASTART: 3066 return lowerVASTART(Op, DAG); 3067 case ISD::FRAMEADDR: 3068 return lowerFRAMEADDR(Op, DAG); 3069 case ISD::RETURNADDR: 3070 return lowerRETURNADDR(Op, DAG); 3071 case ISD::SHL_PARTS: 3072 return lowerShiftLeftParts(Op, DAG); 3073 case ISD::SRA_PARTS: 3074 return lowerShiftRightParts(Op, DAG, true); 3075 case ISD::SRL_PARTS: 3076 return lowerShiftRightParts(Op, DAG, false); 3077 case ISD::BITCAST: { 3078 SDLoc DL(Op); 3079 EVT VT = Op.getValueType(); 3080 SDValue Op0 = Op.getOperand(0); 3081 EVT Op0VT = Op0.getValueType(); 3082 MVT XLenVT = Subtarget.getXLenVT(); 3083 if (VT.isFixedLengthVector()) { 3084 // We can handle fixed length vector bitcasts with a simple replacement 3085 // in isel. 3086 if (Op0VT.isFixedLengthVector()) 3087 return Op; 3088 // When bitcasting from scalar to fixed-length vector, insert the scalar 3089 // into a one-element vector of the result type, and perform a vector 3090 // bitcast. 3091 if (!Op0VT.isVector()) { 3092 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3093 if (!isTypeLegal(BVT)) 3094 return SDValue(); 3095 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3096 DAG.getUNDEF(BVT), Op0, 3097 DAG.getConstant(0, DL, XLenVT))); 3098 } 3099 return SDValue(); 3100 } 3101 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3102 // thus: bitcast the vector to a one-element vector type whose element type 3103 // is the same as the result type, and extract the first element. 3104 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3105 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3106 if (!isTypeLegal(BVT)) 3107 return SDValue(); 3108 SDValue BVec = DAG.getBitcast(BVT, Op0); 3109 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3110 DAG.getConstant(0, DL, XLenVT)); 3111 } 3112 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3113 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3114 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3115 return FPConv; 3116 } 3117 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3118 Subtarget.hasStdExtF()) { 3119 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3120 SDValue FPConv = 3121 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3122 return FPConv; 3123 } 3124 return SDValue(); 3125 } 3126 case ISD::INTRINSIC_WO_CHAIN: 3127 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3128 case ISD::INTRINSIC_W_CHAIN: 3129 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3130 case ISD::INTRINSIC_VOID: 3131 return LowerINTRINSIC_VOID(Op, DAG); 3132 case ISD::BSWAP: 3133 case ISD::BITREVERSE: { 3134 MVT VT = Op.getSimpleValueType(); 3135 SDLoc DL(Op); 3136 if (Subtarget.hasStdExtZbp()) { 3137 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3138 // Start with the maximum immediate value which is the bitwidth - 1. 3139 unsigned Imm = VT.getSizeInBits() - 1; 3140 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3141 if (Op.getOpcode() == ISD::BSWAP) 3142 Imm &= ~0x7U; 3143 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3144 DAG.getConstant(Imm, DL, VT)); 3145 } 3146 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3147 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3148 // Expand bitreverse to a bswap(rev8) followed by brev8. 3149 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3150 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3151 // as brev8 by an isel pattern. 3152 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3153 DAG.getConstant(7, DL, VT)); 3154 } 3155 case ISD::FSHL: 3156 case ISD::FSHR: { 3157 MVT VT = Op.getSimpleValueType(); 3158 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3159 SDLoc DL(Op); 3160 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3161 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3162 // accidentally setting the extra bit. 3163 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3164 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3165 DAG.getConstant(ShAmtWidth, DL, VT)); 3166 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3167 // instruction use different orders. fshl will return its first operand for 3168 // shift of zero, fshr will return its second operand. fsl and fsr both 3169 // return rs1 so the ISD nodes need to have different operand orders. 3170 // Shift amount is in rs2. 3171 SDValue Op0 = Op.getOperand(0); 3172 SDValue Op1 = Op.getOperand(1); 3173 unsigned Opc = RISCVISD::FSL; 3174 if (Op.getOpcode() == ISD::FSHR) { 3175 std::swap(Op0, Op1); 3176 Opc = RISCVISD::FSR; 3177 } 3178 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3179 } 3180 case ISD::TRUNCATE: 3181 // Only custom-lower vector truncates 3182 if (!Op.getSimpleValueType().isVector()) 3183 return Op; 3184 return lowerVectorTruncLike(Op, DAG); 3185 case ISD::ANY_EXTEND: 3186 case ISD::ZERO_EXTEND: 3187 if (Op.getOperand(0).getValueType().isVector() && 3188 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3189 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3190 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3191 case ISD::SIGN_EXTEND: 3192 if (Op.getOperand(0).getValueType().isVector() && 3193 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3194 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3195 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3196 case ISD::SPLAT_VECTOR_PARTS: 3197 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3198 case ISD::INSERT_VECTOR_ELT: 3199 return lowerINSERT_VECTOR_ELT(Op, DAG); 3200 case ISD::EXTRACT_VECTOR_ELT: 3201 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3202 case ISD::VSCALE: { 3203 MVT VT = Op.getSimpleValueType(); 3204 SDLoc DL(Op); 3205 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3206 // We define our scalable vector types for lmul=1 to use a 64 bit known 3207 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3208 // vscale as VLENB / 8. 3209 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3210 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3211 report_fatal_error("Support for VLEN==32 is incomplete."); 3212 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3213 // We assume VLENB is a multiple of 8. We manually choose the best shift 3214 // here because SimplifyDemandedBits isn't always able to simplify it. 3215 uint64_t Val = Op.getConstantOperandVal(0); 3216 if (isPowerOf2_64(Val)) { 3217 uint64_t Log2 = Log2_64(Val); 3218 if (Log2 < 3) 3219 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3220 DAG.getConstant(3 - Log2, DL, VT)); 3221 if (Log2 > 3) 3222 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3223 DAG.getConstant(Log2 - 3, DL, VT)); 3224 return VLENB; 3225 } 3226 // If the multiplier is a multiple of 8, scale it down to avoid needing 3227 // to shift the VLENB value. 3228 if ((Val % 8) == 0) 3229 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3230 DAG.getConstant(Val / 8, DL, VT)); 3231 } 3232 3233 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3234 DAG.getConstant(3, DL, VT)); 3235 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3236 } 3237 case ISD::FPOWI: { 3238 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3239 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3240 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3241 Op.getOperand(1).getValueType() == MVT::i32) { 3242 SDLoc DL(Op); 3243 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3244 SDValue Powi = 3245 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3246 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3247 DAG.getIntPtrConstant(0, DL)); 3248 } 3249 return SDValue(); 3250 } 3251 case ISD::FP_EXTEND: { 3252 // RVV can only do fp_extend to types double the size as the source. We 3253 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3254 // via f32. 3255 SDLoc DL(Op); 3256 MVT VT = Op.getSimpleValueType(); 3257 SDValue Src = Op.getOperand(0); 3258 MVT SrcVT = Src.getSimpleValueType(); 3259 3260 // Prepare any fixed-length vector operands. 3261 MVT ContainerVT = VT; 3262 if (SrcVT.isFixedLengthVector()) { 3263 ContainerVT = getContainerForFixedLengthVector(VT); 3264 MVT SrcContainerVT = 3265 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3266 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3267 } 3268 3269 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3270 SrcVT.getVectorElementType() != MVT::f16) { 3271 // For scalable vectors, we only need to close the gap between 3272 // vXf16->vXf64. 3273 if (!VT.isFixedLengthVector()) 3274 return Op; 3275 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3276 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3277 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3278 } 3279 3280 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3281 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3282 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3283 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3284 3285 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3286 DL, DAG, Subtarget); 3287 if (VT.isFixedLengthVector()) 3288 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3289 return Extend; 3290 } 3291 case ISD::FP_ROUND: 3292 if (!Op.getValueType().isVector()) 3293 return Op; 3294 return lowerVectorFPRoundLike(Op, DAG); 3295 case ISD::FP_TO_SINT: 3296 case ISD::FP_TO_UINT: 3297 case ISD::SINT_TO_FP: 3298 case ISD::UINT_TO_FP: { 3299 // RVV can only do fp<->int conversions to types half/double the size as 3300 // the source. We custom-lower any conversions that do two hops into 3301 // sequences. 3302 MVT VT = Op.getSimpleValueType(); 3303 if (!VT.isVector()) 3304 return Op; 3305 SDLoc DL(Op); 3306 SDValue Src = Op.getOperand(0); 3307 MVT EltVT = VT.getVectorElementType(); 3308 MVT SrcVT = Src.getSimpleValueType(); 3309 MVT SrcEltVT = SrcVT.getVectorElementType(); 3310 unsigned EltSize = EltVT.getSizeInBits(); 3311 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3312 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3313 "Unexpected vector element types"); 3314 3315 bool IsInt2FP = SrcEltVT.isInteger(); 3316 // Widening conversions 3317 if (EltSize > (2 * SrcEltSize)) { 3318 if (IsInt2FP) { 3319 // Do a regular integer sign/zero extension then convert to float. 3320 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3321 VT.getVectorElementCount()); 3322 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3323 ? ISD::ZERO_EXTEND 3324 : ISD::SIGN_EXTEND; 3325 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3326 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3327 } 3328 // FP2Int 3329 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3330 // Do one doubling fp_extend then complete the operation by converting 3331 // to int. 3332 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3333 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3334 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3335 } 3336 3337 // Narrowing conversions 3338 if (SrcEltSize > (2 * EltSize)) { 3339 if (IsInt2FP) { 3340 // One narrowing int_to_fp, then an fp_round. 3341 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3342 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3343 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3344 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3345 } 3346 // FP2Int 3347 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3348 // representable by the integer, the result is poison. 3349 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3350 VT.getVectorElementCount()); 3351 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3352 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3353 } 3354 3355 // Scalable vectors can exit here. Patterns will handle equally-sized 3356 // conversions halving/doubling ones. 3357 if (!VT.isFixedLengthVector()) 3358 return Op; 3359 3360 // For fixed-length vectors we lower to a custom "VL" node. 3361 unsigned RVVOpc = 0; 3362 switch (Op.getOpcode()) { 3363 default: 3364 llvm_unreachable("Impossible opcode"); 3365 case ISD::FP_TO_SINT: 3366 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3367 break; 3368 case ISD::FP_TO_UINT: 3369 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3370 break; 3371 case ISD::SINT_TO_FP: 3372 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3373 break; 3374 case ISD::UINT_TO_FP: 3375 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3376 break; 3377 } 3378 3379 MVT ContainerVT, SrcContainerVT; 3380 // Derive the reference container type from the larger vector type. 3381 if (SrcEltSize > EltSize) { 3382 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3383 ContainerVT = 3384 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3385 } else { 3386 ContainerVT = getContainerForFixedLengthVector(VT); 3387 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3388 } 3389 3390 SDValue Mask, VL; 3391 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3392 3393 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3394 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3395 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3396 } 3397 case ISD::FP_TO_SINT_SAT: 3398 case ISD::FP_TO_UINT_SAT: 3399 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3400 case ISD::FTRUNC: 3401 case ISD::FCEIL: 3402 case ISD::FFLOOR: 3403 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3404 case ISD::FROUND: 3405 return lowerFROUND(Op, DAG); 3406 case ISD::VECREDUCE_ADD: 3407 case ISD::VECREDUCE_UMAX: 3408 case ISD::VECREDUCE_SMAX: 3409 case ISD::VECREDUCE_UMIN: 3410 case ISD::VECREDUCE_SMIN: 3411 return lowerVECREDUCE(Op, DAG); 3412 case ISD::VECREDUCE_AND: 3413 case ISD::VECREDUCE_OR: 3414 case ISD::VECREDUCE_XOR: 3415 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3416 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3417 return lowerVECREDUCE(Op, DAG); 3418 case ISD::VECREDUCE_FADD: 3419 case ISD::VECREDUCE_SEQ_FADD: 3420 case ISD::VECREDUCE_FMIN: 3421 case ISD::VECREDUCE_FMAX: 3422 return lowerFPVECREDUCE(Op, DAG); 3423 case ISD::VP_REDUCE_ADD: 3424 case ISD::VP_REDUCE_UMAX: 3425 case ISD::VP_REDUCE_SMAX: 3426 case ISD::VP_REDUCE_UMIN: 3427 case ISD::VP_REDUCE_SMIN: 3428 case ISD::VP_REDUCE_FADD: 3429 case ISD::VP_REDUCE_SEQ_FADD: 3430 case ISD::VP_REDUCE_FMIN: 3431 case ISD::VP_REDUCE_FMAX: 3432 return lowerVPREDUCE(Op, DAG); 3433 case ISD::VP_REDUCE_AND: 3434 case ISD::VP_REDUCE_OR: 3435 case ISD::VP_REDUCE_XOR: 3436 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3437 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3438 return lowerVPREDUCE(Op, DAG); 3439 case ISD::INSERT_SUBVECTOR: 3440 return lowerINSERT_SUBVECTOR(Op, DAG); 3441 case ISD::EXTRACT_SUBVECTOR: 3442 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3443 case ISD::STEP_VECTOR: 3444 return lowerSTEP_VECTOR(Op, DAG); 3445 case ISD::VECTOR_REVERSE: 3446 return lowerVECTOR_REVERSE(Op, DAG); 3447 case ISD::VECTOR_SPLICE: 3448 return lowerVECTOR_SPLICE(Op, DAG); 3449 case ISD::BUILD_VECTOR: 3450 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3451 case ISD::SPLAT_VECTOR: 3452 if (Op.getValueType().getVectorElementType() == MVT::i1) 3453 return lowerVectorMaskSplat(Op, DAG); 3454 return SDValue(); 3455 case ISD::VECTOR_SHUFFLE: 3456 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3457 case ISD::CONCAT_VECTORS: { 3458 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3459 // better than going through the stack, as the default expansion does. 3460 SDLoc DL(Op); 3461 MVT VT = Op.getSimpleValueType(); 3462 unsigned NumOpElts = 3463 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3464 SDValue Vec = DAG.getUNDEF(VT); 3465 for (const auto &OpIdx : enumerate(Op->ops())) { 3466 SDValue SubVec = OpIdx.value(); 3467 // Don't insert undef subvectors. 3468 if (SubVec.isUndef()) 3469 continue; 3470 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3471 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3472 } 3473 return Vec; 3474 } 3475 case ISD::LOAD: 3476 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3477 return V; 3478 if (Op.getValueType().isFixedLengthVector()) 3479 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3480 return Op; 3481 case ISD::STORE: 3482 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3483 return V; 3484 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3485 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3486 return Op; 3487 case ISD::MLOAD: 3488 case ISD::VP_LOAD: 3489 return lowerMaskedLoad(Op, DAG); 3490 case ISD::MSTORE: 3491 case ISD::VP_STORE: 3492 return lowerMaskedStore(Op, DAG); 3493 case ISD::SETCC: 3494 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3495 case ISD::ADD: 3496 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3497 case ISD::SUB: 3498 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3499 case ISD::MUL: 3500 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3501 case ISD::MULHS: 3502 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3503 case ISD::MULHU: 3504 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3505 case ISD::AND: 3506 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3507 RISCVISD::AND_VL); 3508 case ISD::OR: 3509 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3510 RISCVISD::OR_VL); 3511 case ISD::XOR: 3512 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3513 RISCVISD::XOR_VL); 3514 case ISD::SDIV: 3515 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3516 case ISD::SREM: 3517 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3518 case ISD::UDIV: 3519 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3520 case ISD::UREM: 3521 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3522 case ISD::SHL: 3523 case ISD::SRA: 3524 case ISD::SRL: 3525 if (Op.getSimpleValueType().isFixedLengthVector()) 3526 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3527 // This can be called for an i32 shift amount that needs to be promoted. 3528 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3529 "Unexpected custom legalisation"); 3530 return SDValue(); 3531 case ISD::SADDSAT: 3532 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3533 case ISD::UADDSAT: 3534 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3535 case ISD::SSUBSAT: 3536 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3537 case ISD::USUBSAT: 3538 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3539 case ISD::FADD: 3540 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3541 case ISD::FSUB: 3542 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3543 case ISD::FMUL: 3544 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3545 case ISD::FDIV: 3546 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3547 case ISD::FNEG: 3548 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3549 case ISD::FABS: 3550 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3551 case ISD::FSQRT: 3552 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3553 case ISD::FMA: 3554 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3555 case ISD::SMIN: 3556 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3557 case ISD::SMAX: 3558 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3559 case ISD::UMIN: 3560 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3561 case ISD::UMAX: 3562 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3563 case ISD::FMINNUM: 3564 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3565 case ISD::FMAXNUM: 3566 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3567 case ISD::ABS: 3568 return lowerABS(Op, DAG); 3569 case ISD::CTLZ_ZERO_UNDEF: 3570 case ISD::CTTZ_ZERO_UNDEF: 3571 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3572 case ISD::VSELECT: 3573 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3574 case ISD::FCOPYSIGN: 3575 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3576 case ISD::MGATHER: 3577 case ISD::VP_GATHER: 3578 return lowerMaskedGather(Op, DAG); 3579 case ISD::MSCATTER: 3580 case ISD::VP_SCATTER: 3581 return lowerMaskedScatter(Op, DAG); 3582 case ISD::FLT_ROUNDS_: 3583 return lowerGET_ROUNDING(Op, DAG); 3584 case ISD::SET_ROUNDING: 3585 return lowerSET_ROUNDING(Op, DAG); 3586 case ISD::VP_SELECT: 3587 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3588 case ISD::VP_MERGE: 3589 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3590 case ISD::VP_ADD: 3591 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3592 case ISD::VP_SUB: 3593 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3594 case ISD::VP_MUL: 3595 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3596 case ISD::VP_SDIV: 3597 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3598 case ISD::VP_UDIV: 3599 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3600 case ISD::VP_SREM: 3601 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3602 case ISD::VP_UREM: 3603 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3604 case ISD::VP_AND: 3605 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3606 case ISD::VP_OR: 3607 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3608 case ISD::VP_XOR: 3609 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3610 case ISD::VP_ASHR: 3611 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3612 case ISD::VP_LSHR: 3613 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3614 case ISD::VP_SHL: 3615 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3616 case ISD::VP_FADD: 3617 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3618 case ISD::VP_FSUB: 3619 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3620 case ISD::VP_FMUL: 3621 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3622 case ISD::VP_FDIV: 3623 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3624 case ISD::VP_FNEG: 3625 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3626 case ISD::VP_FMA: 3627 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3628 case ISD::VP_SEXT: 3629 case ISD::VP_ZEXT: 3630 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3631 return lowerVPExtMaskOp(Op, DAG); 3632 return lowerVPOp(Op, DAG, 3633 Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL 3634 : RISCVISD::VZEXT_VL); 3635 case ISD::VP_TRUNC: 3636 return lowerVectorTruncLike(Op, DAG); 3637 case ISD::VP_FP_ROUND: 3638 return lowerVectorFPRoundLike(Op, DAG); 3639 case ISD::VP_FPTOSI: 3640 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3641 case ISD::VP_FPTOUI: 3642 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3643 case ISD::VP_SITOFP: 3644 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3645 case ISD::VP_UITOFP: 3646 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3647 case ISD::VP_SETCC: 3648 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3649 } 3650 } 3651 3652 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3653 SelectionDAG &DAG, unsigned Flags) { 3654 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3655 } 3656 3657 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3658 SelectionDAG &DAG, unsigned Flags) { 3659 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3660 Flags); 3661 } 3662 3663 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3664 SelectionDAG &DAG, unsigned Flags) { 3665 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3666 N->getOffset(), Flags); 3667 } 3668 3669 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3670 SelectionDAG &DAG, unsigned Flags) { 3671 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3672 } 3673 3674 template <class NodeTy> 3675 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3676 bool IsLocal) const { 3677 SDLoc DL(N); 3678 EVT Ty = getPointerTy(DAG.getDataLayout()); 3679 3680 if (isPositionIndependent()) { 3681 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3682 if (IsLocal) 3683 // Use PC-relative addressing to access the symbol. This generates the 3684 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3685 // %pcrel_lo(auipc)). 3686 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3687 3688 // Use PC-relative addressing to access the GOT for this symbol, then load 3689 // the address from the GOT. This generates the pattern (PseudoLA sym), 3690 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3691 SDValue Load = 3692 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3693 MachineFunction &MF = DAG.getMachineFunction(); 3694 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3695 MachinePointerInfo::getGOT(MF), 3696 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3697 MachineMemOperand::MOInvariant, 3698 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3699 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3700 return Load; 3701 } 3702 3703 switch (getTargetMachine().getCodeModel()) { 3704 default: 3705 report_fatal_error("Unsupported code model for lowering"); 3706 case CodeModel::Small: { 3707 // Generate a sequence for accessing addresses within the first 2 GiB of 3708 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3709 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3710 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3711 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3712 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3713 } 3714 case CodeModel::Medium: { 3715 // Generate a sequence for accessing addresses within any 2GiB range within 3716 // the address space. This generates the pattern (PseudoLLA sym), which 3717 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3718 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3719 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3720 } 3721 } 3722 } 3723 3724 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3725 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3726 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3727 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3728 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3729 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3730 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3731 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3732 3733 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3734 SelectionDAG &DAG) const { 3735 SDLoc DL(Op); 3736 EVT Ty = Op.getValueType(); 3737 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3738 int64_t Offset = N->getOffset(); 3739 MVT XLenVT = Subtarget.getXLenVT(); 3740 3741 const GlobalValue *GV = N->getGlobal(); 3742 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3743 SDValue Addr = getAddr(N, DAG, IsLocal); 3744 3745 // In order to maximise the opportunity for common subexpression elimination, 3746 // emit a separate ADD node for the global address offset instead of folding 3747 // it in the global address node. Later peephole optimisations may choose to 3748 // fold it back in when profitable. 3749 if (Offset != 0) 3750 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3751 DAG.getConstant(Offset, DL, XLenVT)); 3752 return Addr; 3753 } 3754 3755 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3756 SelectionDAG &DAG) const { 3757 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3758 3759 return getAddr(N, DAG); 3760 } 3761 3762 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3763 SelectionDAG &DAG) const { 3764 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3765 3766 return getAddr(N, DAG); 3767 } 3768 3769 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3770 SelectionDAG &DAG) const { 3771 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3772 3773 return getAddr(N, DAG); 3774 } 3775 3776 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3777 SelectionDAG &DAG, 3778 bool UseGOT) const { 3779 SDLoc DL(N); 3780 EVT Ty = getPointerTy(DAG.getDataLayout()); 3781 const GlobalValue *GV = N->getGlobal(); 3782 MVT XLenVT = Subtarget.getXLenVT(); 3783 3784 if (UseGOT) { 3785 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3786 // load the address from the GOT and add the thread pointer. This generates 3787 // the pattern (PseudoLA_TLS_IE sym), which expands to 3788 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3789 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3790 SDValue Load = 3791 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3792 MachineFunction &MF = DAG.getMachineFunction(); 3793 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3794 MachinePointerInfo::getGOT(MF), 3795 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3796 MachineMemOperand::MOInvariant, 3797 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3798 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3799 3800 // Add the thread pointer. 3801 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3802 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3803 } 3804 3805 // Generate a sequence for accessing the address relative to the thread 3806 // pointer, with the appropriate adjustment for the thread pointer offset. 3807 // This generates the pattern 3808 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3809 SDValue AddrHi = 3810 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3811 SDValue AddrAdd = 3812 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3813 SDValue AddrLo = 3814 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3815 3816 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3817 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3818 SDValue MNAdd = SDValue( 3819 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3820 0); 3821 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3822 } 3823 3824 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3825 SelectionDAG &DAG) const { 3826 SDLoc DL(N); 3827 EVT Ty = getPointerTy(DAG.getDataLayout()); 3828 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3829 const GlobalValue *GV = N->getGlobal(); 3830 3831 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3832 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3833 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3834 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3835 SDValue Load = 3836 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3837 3838 // Prepare argument list to generate call. 3839 ArgListTy Args; 3840 ArgListEntry Entry; 3841 Entry.Node = Load; 3842 Entry.Ty = CallTy; 3843 Args.push_back(Entry); 3844 3845 // Setup call to __tls_get_addr. 3846 TargetLowering::CallLoweringInfo CLI(DAG); 3847 CLI.setDebugLoc(DL) 3848 .setChain(DAG.getEntryNode()) 3849 .setLibCallee(CallingConv::C, CallTy, 3850 DAG.getExternalSymbol("__tls_get_addr", Ty), 3851 std::move(Args)); 3852 3853 return LowerCallTo(CLI).first; 3854 } 3855 3856 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3857 SelectionDAG &DAG) const { 3858 SDLoc DL(Op); 3859 EVT Ty = Op.getValueType(); 3860 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3861 int64_t Offset = N->getOffset(); 3862 MVT XLenVT = Subtarget.getXLenVT(); 3863 3864 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3865 3866 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3867 CallingConv::GHC) 3868 report_fatal_error("In GHC calling convention TLS is not supported"); 3869 3870 SDValue Addr; 3871 switch (Model) { 3872 case TLSModel::LocalExec: 3873 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3874 break; 3875 case TLSModel::InitialExec: 3876 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3877 break; 3878 case TLSModel::LocalDynamic: 3879 case TLSModel::GeneralDynamic: 3880 Addr = getDynamicTLSAddr(N, DAG); 3881 break; 3882 } 3883 3884 // In order to maximise the opportunity for common subexpression elimination, 3885 // emit a separate ADD node for the global address offset instead of folding 3886 // it in the global address node. Later peephole optimisations may choose to 3887 // fold it back in when profitable. 3888 if (Offset != 0) 3889 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3890 DAG.getConstant(Offset, DL, XLenVT)); 3891 return Addr; 3892 } 3893 3894 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3895 SDValue CondV = Op.getOperand(0); 3896 SDValue TrueV = Op.getOperand(1); 3897 SDValue FalseV = Op.getOperand(2); 3898 SDLoc DL(Op); 3899 MVT VT = Op.getSimpleValueType(); 3900 MVT XLenVT = Subtarget.getXLenVT(); 3901 3902 // Lower vector SELECTs to VSELECTs by splatting the condition. 3903 if (VT.isVector()) { 3904 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3905 SDValue CondSplat = VT.isScalableVector() 3906 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3907 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3908 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3909 } 3910 3911 // If the result type is XLenVT and CondV is the output of a SETCC node 3912 // which also operated on XLenVT inputs, then merge the SETCC node into the 3913 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3914 // compare+branch instructions. i.e.: 3915 // (select (setcc lhs, rhs, cc), truev, falsev) 3916 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3917 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3918 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3919 SDValue LHS = CondV.getOperand(0); 3920 SDValue RHS = CondV.getOperand(1); 3921 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3922 ISD::CondCode CCVal = CC->get(); 3923 3924 // Special case for a select of 2 constants that have a diffence of 1. 3925 // Normally this is done by DAGCombine, but if the select is introduced by 3926 // type legalization or op legalization, we miss it. Restricting to SETLT 3927 // case for now because that is what signed saturating add/sub need. 3928 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3929 // but we would probably want to swap the true/false values if the condition 3930 // is SETGE/SETLE to avoid an XORI. 3931 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3932 CCVal == ISD::SETLT) { 3933 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3934 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3935 if (TrueVal - 1 == FalseVal) 3936 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3937 if (TrueVal + 1 == FalseVal) 3938 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3939 } 3940 3941 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3942 3943 SDValue TargetCC = DAG.getCondCode(CCVal); 3944 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3945 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3946 } 3947 3948 // Otherwise: 3949 // (select condv, truev, falsev) 3950 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3951 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3952 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3953 3954 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3955 3956 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3957 } 3958 3959 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3960 SDValue CondV = Op.getOperand(1); 3961 SDLoc DL(Op); 3962 MVT XLenVT = Subtarget.getXLenVT(); 3963 3964 if (CondV.getOpcode() == ISD::SETCC && 3965 CondV.getOperand(0).getValueType() == XLenVT) { 3966 SDValue LHS = CondV.getOperand(0); 3967 SDValue RHS = CondV.getOperand(1); 3968 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3969 3970 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3971 3972 SDValue TargetCC = DAG.getCondCode(CCVal); 3973 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3974 LHS, RHS, TargetCC, Op.getOperand(2)); 3975 } 3976 3977 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3978 CondV, DAG.getConstant(0, DL, XLenVT), 3979 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3980 } 3981 3982 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3983 MachineFunction &MF = DAG.getMachineFunction(); 3984 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3985 3986 SDLoc DL(Op); 3987 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3988 getPointerTy(MF.getDataLayout())); 3989 3990 // vastart just stores the address of the VarArgsFrameIndex slot into the 3991 // memory location argument. 3992 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3993 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3994 MachinePointerInfo(SV)); 3995 } 3996 3997 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3998 SelectionDAG &DAG) const { 3999 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4000 MachineFunction &MF = DAG.getMachineFunction(); 4001 MachineFrameInfo &MFI = MF.getFrameInfo(); 4002 MFI.setFrameAddressIsTaken(true); 4003 Register FrameReg = RI.getFrameRegister(MF); 4004 int XLenInBytes = Subtarget.getXLen() / 8; 4005 4006 EVT VT = Op.getValueType(); 4007 SDLoc DL(Op); 4008 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4009 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4010 while (Depth--) { 4011 int Offset = -(XLenInBytes * 2); 4012 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4013 DAG.getIntPtrConstant(Offset, DL)); 4014 FrameAddr = 4015 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4016 } 4017 return FrameAddr; 4018 } 4019 4020 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4021 SelectionDAG &DAG) const { 4022 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4023 MachineFunction &MF = DAG.getMachineFunction(); 4024 MachineFrameInfo &MFI = MF.getFrameInfo(); 4025 MFI.setReturnAddressIsTaken(true); 4026 MVT XLenVT = Subtarget.getXLenVT(); 4027 int XLenInBytes = Subtarget.getXLen() / 8; 4028 4029 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4030 return SDValue(); 4031 4032 EVT VT = Op.getValueType(); 4033 SDLoc DL(Op); 4034 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4035 if (Depth) { 4036 int Off = -XLenInBytes; 4037 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4038 SDValue Offset = DAG.getConstant(Off, DL, VT); 4039 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4040 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4041 MachinePointerInfo()); 4042 } 4043 4044 // Return the value of the return address register, marking it an implicit 4045 // live-in. 4046 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4047 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4048 } 4049 4050 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4051 SelectionDAG &DAG) const { 4052 SDLoc DL(Op); 4053 SDValue Lo = Op.getOperand(0); 4054 SDValue Hi = Op.getOperand(1); 4055 SDValue Shamt = Op.getOperand(2); 4056 EVT VT = Lo.getValueType(); 4057 4058 // if Shamt-XLEN < 0: // Shamt < XLEN 4059 // Lo = Lo << Shamt 4060 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4061 // else: 4062 // Lo = 0 4063 // Hi = Lo << (Shamt-XLEN) 4064 4065 SDValue Zero = DAG.getConstant(0, DL, VT); 4066 SDValue One = DAG.getConstant(1, DL, VT); 4067 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4068 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4069 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4070 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4071 4072 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4073 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4074 SDValue ShiftRightLo = 4075 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4076 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4077 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4078 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4079 4080 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4081 4082 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4083 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4084 4085 SDValue Parts[2] = {Lo, Hi}; 4086 return DAG.getMergeValues(Parts, DL); 4087 } 4088 4089 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4090 bool IsSRA) const { 4091 SDLoc DL(Op); 4092 SDValue Lo = Op.getOperand(0); 4093 SDValue Hi = Op.getOperand(1); 4094 SDValue Shamt = Op.getOperand(2); 4095 EVT VT = Lo.getValueType(); 4096 4097 // SRA expansion: 4098 // if Shamt-XLEN < 0: // Shamt < XLEN 4099 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4100 // Hi = Hi >>s Shamt 4101 // else: 4102 // Lo = Hi >>s (Shamt-XLEN); 4103 // Hi = Hi >>s (XLEN-1) 4104 // 4105 // SRL expansion: 4106 // if Shamt-XLEN < 0: // Shamt < XLEN 4107 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4108 // Hi = Hi >>u Shamt 4109 // else: 4110 // Lo = Hi >>u (Shamt-XLEN); 4111 // Hi = 0; 4112 4113 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4114 4115 SDValue Zero = DAG.getConstant(0, DL, VT); 4116 SDValue One = DAG.getConstant(1, DL, VT); 4117 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4118 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4119 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4120 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4121 4122 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4123 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4124 SDValue ShiftLeftHi = 4125 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4126 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4127 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4128 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4129 SDValue HiFalse = 4130 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4131 4132 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4133 4134 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4135 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4136 4137 SDValue Parts[2] = {Lo, Hi}; 4138 return DAG.getMergeValues(Parts, DL); 4139 } 4140 4141 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4142 // legal equivalently-sized i8 type, so we can use that as a go-between. 4143 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4144 SelectionDAG &DAG) const { 4145 SDLoc DL(Op); 4146 MVT VT = Op.getSimpleValueType(); 4147 SDValue SplatVal = Op.getOperand(0); 4148 // All-zeros or all-ones splats are handled specially. 4149 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4150 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4151 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4152 } 4153 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4154 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4155 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4156 } 4157 MVT XLenVT = Subtarget.getXLenVT(); 4158 assert(SplatVal.getValueType() == XLenVT && 4159 "Unexpected type for i1 splat value"); 4160 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4161 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4162 DAG.getConstant(1, DL, XLenVT)); 4163 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4164 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4165 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4166 } 4167 4168 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4169 // illegal (currently only vXi64 RV32). 4170 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4171 // them to VMV_V_X_VL. 4172 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4173 SelectionDAG &DAG) const { 4174 SDLoc DL(Op); 4175 MVT VecVT = Op.getSimpleValueType(); 4176 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4177 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4178 4179 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4180 SDValue Lo = Op.getOperand(0); 4181 SDValue Hi = Op.getOperand(1); 4182 4183 if (VecVT.isFixedLengthVector()) { 4184 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4185 SDLoc DL(Op); 4186 SDValue Mask, VL; 4187 std::tie(Mask, VL) = 4188 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4189 4190 SDValue Res = 4191 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4192 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4193 } 4194 4195 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4196 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4197 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4198 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4199 // node in order to try and match RVV vector/scalar instructions. 4200 if ((LoC >> 31) == HiC) 4201 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4202 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4203 } 4204 4205 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4206 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4207 isa<ConstantSDNode>(Hi.getOperand(1)) && 4208 Hi.getConstantOperandVal(1) == 31) 4209 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4210 DAG.getRegister(RISCV::X0, MVT::i32)); 4211 4212 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4213 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4214 DAG.getUNDEF(VecVT), Lo, Hi, 4215 DAG.getRegister(RISCV::X0, MVT::i32)); 4216 } 4217 4218 // Custom-lower extensions from mask vectors by using a vselect either with 1 4219 // for zero/any-extension or -1 for sign-extension: 4220 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4221 // Note that any-extension is lowered identically to zero-extension. 4222 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4223 int64_t ExtTrueVal) const { 4224 SDLoc DL(Op); 4225 MVT VecVT = Op.getSimpleValueType(); 4226 SDValue Src = Op.getOperand(0); 4227 // Only custom-lower extensions from mask types 4228 assert(Src.getValueType().isVector() && 4229 Src.getValueType().getVectorElementType() == MVT::i1); 4230 4231 if (VecVT.isScalableVector()) { 4232 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4233 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4234 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4235 } 4236 4237 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4238 MVT I1ContainerVT = 4239 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4240 4241 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4242 4243 SDValue Mask, VL; 4244 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4245 4246 MVT XLenVT = Subtarget.getXLenVT(); 4247 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4248 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4249 4250 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4251 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4252 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4253 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4254 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4255 SplatTrueVal, SplatZero, VL); 4256 4257 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4258 } 4259 4260 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4261 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4262 MVT ExtVT = Op.getSimpleValueType(); 4263 // Only custom-lower extensions from fixed-length vector types. 4264 if (!ExtVT.isFixedLengthVector()) 4265 return Op; 4266 MVT VT = Op.getOperand(0).getSimpleValueType(); 4267 // Grab the canonical container type for the extended type. Infer the smaller 4268 // type from that to ensure the same number of vector elements, as we know 4269 // the LMUL will be sufficient to hold the smaller type. 4270 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4271 // Get the extended container type manually to ensure the same number of 4272 // vector elements between source and dest. 4273 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4274 ContainerExtVT.getVectorElementCount()); 4275 4276 SDValue Op1 = 4277 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4278 4279 SDLoc DL(Op); 4280 SDValue Mask, VL; 4281 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4282 4283 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4284 4285 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4286 } 4287 4288 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4289 // setcc operation: 4290 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4291 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4292 SelectionDAG &DAG) const { 4293 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4294 SDLoc DL(Op); 4295 EVT MaskVT = Op.getValueType(); 4296 // Only expect to custom-lower truncations to mask types 4297 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4298 "Unexpected type for vector mask lowering"); 4299 SDValue Src = Op.getOperand(0); 4300 MVT VecVT = Src.getSimpleValueType(); 4301 SDValue Mask, VL; 4302 if (IsVPTrunc) { 4303 Mask = Op.getOperand(1); 4304 VL = Op.getOperand(2); 4305 } 4306 // If this is a fixed vector, we need to convert it to a scalable vector. 4307 MVT ContainerVT = VecVT; 4308 4309 if (VecVT.isFixedLengthVector()) { 4310 ContainerVT = getContainerForFixedLengthVector(VecVT); 4311 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4312 if (IsVPTrunc) { 4313 MVT MaskContainerVT = 4314 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4315 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4316 } 4317 } 4318 4319 if (!IsVPTrunc) { 4320 std::tie(Mask, VL) = 4321 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4322 } 4323 4324 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4325 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4326 4327 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4328 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4329 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4330 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4331 4332 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4333 SDValue Trunc = 4334 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4335 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4336 DAG.getCondCode(ISD::SETNE), Mask, VL); 4337 if (MaskVT.isFixedLengthVector()) 4338 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4339 return Trunc; 4340 } 4341 4342 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4343 SelectionDAG &DAG) const { 4344 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4345 SDLoc DL(Op); 4346 4347 MVT VT = Op.getSimpleValueType(); 4348 // Only custom-lower vector truncates 4349 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4350 4351 // Truncates to mask types are handled differently 4352 if (VT.getVectorElementType() == MVT::i1) 4353 return lowerVectorMaskTruncLike(Op, DAG); 4354 4355 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4356 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4357 // truncate by one power of two at a time. 4358 MVT DstEltVT = VT.getVectorElementType(); 4359 4360 SDValue Src = Op.getOperand(0); 4361 MVT SrcVT = Src.getSimpleValueType(); 4362 MVT SrcEltVT = SrcVT.getVectorElementType(); 4363 4364 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4365 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4366 "Unexpected vector truncate lowering"); 4367 4368 MVT ContainerVT = SrcVT; 4369 SDValue Mask, VL; 4370 if (IsVPTrunc) { 4371 Mask = Op.getOperand(1); 4372 VL = Op.getOperand(2); 4373 } 4374 if (SrcVT.isFixedLengthVector()) { 4375 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4376 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4377 if (IsVPTrunc) { 4378 MVT MaskVT = 4379 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4380 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4381 } 4382 } 4383 4384 SDValue Result = Src; 4385 if (!IsVPTrunc) { 4386 std::tie(Mask, VL) = 4387 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4388 } 4389 4390 LLVMContext &Context = *DAG.getContext(); 4391 const ElementCount Count = ContainerVT.getVectorElementCount(); 4392 do { 4393 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4394 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4395 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4396 Mask, VL); 4397 } while (SrcEltVT != DstEltVT); 4398 4399 if (SrcVT.isFixedLengthVector()) 4400 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4401 4402 return Result; 4403 } 4404 4405 SDValue RISCVTargetLowering::lowerVectorFPRoundLike(SDValue Op, 4406 SelectionDAG &DAG) const { 4407 bool IsVPFPTrunc = Op.getOpcode() == ISD::VP_FP_ROUND; 4408 // RVV can only do truncate fp to types half the size as the source. We 4409 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4410 // conversion instruction. 4411 SDLoc DL(Op); 4412 MVT VT = Op.getSimpleValueType(); 4413 4414 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4415 4416 SDValue Src = Op.getOperand(0); 4417 MVT SrcVT = Src.getSimpleValueType(); 4418 4419 bool IsDirectConv = VT.getVectorElementType() != MVT::f16 || 4420 SrcVT.getVectorElementType() != MVT::f64; 4421 4422 // For FP_ROUND of scalable vectors, leave it to the pattern. 4423 if (!VT.isFixedLengthVector() && !IsVPFPTrunc && IsDirectConv) 4424 return Op; 4425 4426 // Prepare any fixed-length vector operands. 4427 MVT ContainerVT = VT; 4428 SDValue Mask, VL; 4429 if (IsVPFPTrunc) { 4430 Mask = Op.getOperand(1); 4431 VL = Op.getOperand(2); 4432 } 4433 if (VT.isFixedLengthVector()) { 4434 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4435 ContainerVT = 4436 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4437 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4438 if (IsVPFPTrunc) { 4439 MVT MaskVT = 4440 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4441 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4442 } 4443 } 4444 4445 if (!IsVPFPTrunc) 4446 std::tie(Mask, VL) = 4447 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4448 4449 if (IsDirectConv) { 4450 Src = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, Src, Mask, VL); 4451 if (VT.isFixedLengthVector()) 4452 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4453 return Src; 4454 } 4455 4456 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4457 SDValue IntermediateRound = 4458 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 4459 SDValue Round = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, 4460 IntermediateRound, Mask, VL); 4461 if (VT.isFixedLengthVector()) 4462 return convertFromScalableVector(VT, Round, DAG, Subtarget); 4463 return Round; 4464 } 4465 4466 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4467 // first position of a vector, and that vector is slid up to the insert index. 4468 // By limiting the active vector length to index+1 and merging with the 4469 // original vector (with an undisturbed tail policy for elements >= VL), we 4470 // achieve the desired result of leaving all elements untouched except the one 4471 // at VL-1, which is replaced with the desired value. 4472 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4473 SelectionDAG &DAG) const { 4474 SDLoc DL(Op); 4475 MVT VecVT = Op.getSimpleValueType(); 4476 SDValue Vec = Op.getOperand(0); 4477 SDValue Val = Op.getOperand(1); 4478 SDValue Idx = Op.getOperand(2); 4479 4480 if (VecVT.getVectorElementType() == MVT::i1) { 4481 // FIXME: For now we just promote to an i8 vector and insert into that, 4482 // but this is probably not optimal. 4483 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4484 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4485 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4486 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4487 } 4488 4489 MVT ContainerVT = VecVT; 4490 // If the operand is a fixed-length vector, convert to a scalable one. 4491 if (VecVT.isFixedLengthVector()) { 4492 ContainerVT = getContainerForFixedLengthVector(VecVT); 4493 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4494 } 4495 4496 MVT XLenVT = Subtarget.getXLenVT(); 4497 4498 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4499 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4500 // Even i64-element vectors on RV32 can be lowered without scalar 4501 // legalization if the most-significant 32 bits of the value are not affected 4502 // by the sign-extension of the lower 32 bits. 4503 // TODO: We could also catch sign extensions of a 32-bit value. 4504 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4505 const auto *CVal = cast<ConstantSDNode>(Val); 4506 if (isInt<32>(CVal->getSExtValue())) { 4507 IsLegalInsert = true; 4508 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4509 } 4510 } 4511 4512 SDValue Mask, VL; 4513 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4514 4515 SDValue ValInVec; 4516 4517 if (IsLegalInsert) { 4518 unsigned Opc = 4519 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4520 if (isNullConstant(Idx)) { 4521 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4522 if (!VecVT.isFixedLengthVector()) 4523 return Vec; 4524 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4525 } 4526 ValInVec = 4527 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4528 } else { 4529 // On RV32, i64-element vectors must be specially handled to place the 4530 // value at element 0, by using two vslide1up instructions in sequence on 4531 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4532 // this. 4533 SDValue One = DAG.getConstant(1, DL, XLenVT); 4534 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4535 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4536 MVT I32ContainerVT = 4537 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4538 SDValue I32Mask = 4539 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4540 // Limit the active VL to two. 4541 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4542 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4543 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4544 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4545 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4546 // First slide in the hi value, then the lo in underneath it. 4547 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4548 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4549 I32Mask, InsertI64VL); 4550 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4551 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4552 I32Mask, InsertI64VL); 4553 // Bitcast back to the right container type. 4554 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4555 } 4556 4557 // Now that the value is in a vector, slide it into position. 4558 SDValue InsertVL = 4559 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4560 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4561 ValInVec, Idx, Mask, InsertVL); 4562 if (!VecVT.isFixedLengthVector()) 4563 return Slideup; 4564 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4565 } 4566 4567 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4568 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4569 // types this is done using VMV_X_S to allow us to glean information about the 4570 // sign bits of the result. 4571 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4572 SelectionDAG &DAG) const { 4573 SDLoc DL(Op); 4574 SDValue Idx = Op.getOperand(1); 4575 SDValue Vec = Op.getOperand(0); 4576 EVT EltVT = Op.getValueType(); 4577 MVT VecVT = Vec.getSimpleValueType(); 4578 MVT XLenVT = Subtarget.getXLenVT(); 4579 4580 if (VecVT.getVectorElementType() == MVT::i1) { 4581 if (VecVT.isFixedLengthVector()) { 4582 unsigned NumElts = VecVT.getVectorNumElements(); 4583 if (NumElts >= 8) { 4584 MVT WideEltVT; 4585 unsigned WidenVecLen; 4586 SDValue ExtractElementIdx; 4587 SDValue ExtractBitIdx; 4588 unsigned MaxEEW = Subtarget.getELEN(); 4589 MVT LargestEltVT = MVT::getIntegerVT( 4590 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4591 if (NumElts <= LargestEltVT.getSizeInBits()) { 4592 assert(isPowerOf2_32(NumElts) && 4593 "the number of elements should be power of 2"); 4594 WideEltVT = MVT::getIntegerVT(NumElts); 4595 WidenVecLen = 1; 4596 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4597 ExtractBitIdx = Idx; 4598 } else { 4599 WideEltVT = LargestEltVT; 4600 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4601 // extract element index = index / element width 4602 ExtractElementIdx = DAG.getNode( 4603 ISD::SRL, DL, XLenVT, Idx, 4604 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4605 // mask bit index = index % element width 4606 ExtractBitIdx = DAG.getNode( 4607 ISD::AND, DL, XLenVT, Idx, 4608 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4609 } 4610 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4611 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4612 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4613 Vec, ExtractElementIdx); 4614 // Extract the bit from GPR. 4615 SDValue ShiftRight = 4616 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4617 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4618 DAG.getConstant(1, DL, XLenVT)); 4619 } 4620 } 4621 // Otherwise, promote to an i8 vector and extract from that. 4622 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4623 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4624 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4625 } 4626 4627 // If this is a fixed vector, we need to convert it to a scalable vector. 4628 MVT ContainerVT = VecVT; 4629 if (VecVT.isFixedLengthVector()) { 4630 ContainerVT = getContainerForFixedLengthVector(VecVT); 4631 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4632 } 4633 4634 // If the index is 0, the vector is already in the right position. 4635 if (!isNullConstant(Idx)) { 4636 // Use a VL of 1 to avoid processing more elements than we need. 4637 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4638 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4639 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4640 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4641 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4642 } 4643 4644 if (!EltVT.isInteger()) { 4645 // Floating-point extracts are handled in TableGen. 4646 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4647 DAG.getConstant(0, DL, XLenVT)); 4648 } 4649 4650 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4651 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4652 } 4653 4654 // Some RVV intrinsics may claim that they want an integer operand to be 4655 // promoted or expanded. 4656 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4657 const RISCVSubtarget &Subtarget) { 4658 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4659 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4660 "Unexpected opcode"); 4661 4662 if (!Subtarget.hasVInstructions()) 4663 return SDValue(); 4664 4665 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4666 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4667 SDLoc DL(Op); 4668 4669 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4670 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4671 if (!II || !II->hasScalarOperand()) 4672 return SDValue(); 4673 4674 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4675 assert(SplatOp < Op.getNumOperands()); 4676 4677 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4678 SDValue &ScalarOp = Operands[SplatOp]; 4679 MVT OpVT = ScalarOp.getSimpleValueType(); 4680 MVT XLenVT = Subtarget.getXLenVT(); 4681 4682 // If this isn't a scalar, or its type is XLenVT we're done. 4683 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4684 return SDValue(); 4685 4686 // Simplest case is that the operand needs to be promoted to XLenVT. 4687 if (OpVT.bitsLT(XLenVT)) { 4688 // If the operand is a constant, sign extend to increase our chances 4689 // of being able to use a .vi instruction. ANY_EXTEND would become a 4690 // a zero extend and the simm5 check in isel would fail. 4691 // FIXME: Should we ignore the upper bits in isel instead? 4692 unsigned ExtOpc = 4693 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4694 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4695 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4696 } 4697 4698 // Use the previous operand to get the vXi64 VT. The result might be a mask 4699 // VT for compares. Using the previous operand assumes that the previous 4700 // operand will never have a smaller element size than a scalar operand and 4701 // that a widening operation never uses SEW=64. 4702 // NOTE: If this fails the below assert, we can probably just find the 4703 // element count from any operand or result and use it to construct the VT. 4704 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4705 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4706 4707 // The more complex case is when the scalar is larger than XLenVT. 4708 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4709 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4710 4711 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4712 // instruction to sign-extend since SEW>XLEN. 4713 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4714 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4715 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4716 } 4717 4718 switch (IntNo) { 4719 case Intrinsic::riscv_vslide1up: 4720 case Intrinsic::riscv_vslide1down: 4721 case Intrinsic::riscv_vslide1up_mask: 4722 case Intrinsic::riscv_vslide1down_mask: { 4723 // We need to special case these when the scalar is larger than XLen. 4724 unsigned NumOps = Op.getNumOperands(); 4725 bool IsMasked = NumOps == 7; 4726 4727 // Convert the vector source to the equivalent nxvXi32 vector. 4728 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4729 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4730 4731 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4732 DAG.getConstant(0, DL, XLenVT)); 4733 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4734 DAG.getConstant(1, DL, XLenVT)); 4735 4736 // Double the VL since we halved SEW. 4737 SDValue AVL = getVLOperand(Op); 4738 SDValue I32VL; 4739 4740 // Optimize for constant AVL 4741 if (isa<ConstantSDNode>(AVL)) { 4742 unsigned EltSize = VT.getScalarSizeInBits(); 4743 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4744 4745 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4746 unsigned MaxVLMAX = 4747 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4748 4749 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4750 unsigned MinVLMAX = 4751 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4752 4753 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4754 if (AVLInt <= MinVLMAX) { 4755 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4756 } else if (AVLInt >= 2 * MaxVLMAX) { 4757 // Just set vl to VLMAX in this situation 4758 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4759 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4760 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4761 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4762 SDValue SETVLMAX = DAG.getTargetConstant( 4763 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4764 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4765 LMUL); 4766 } else { 4767 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4768 // is related to the hardware implementation. 4769 // So let the following code handle 4770 } 4771 } 4772 if (!I32VL) { 4773 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4774 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4775 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4776 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4777 SDValue SETVL = 4778 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4779 // Using vsetvli instruction to get actually used length which related to 4780 // the hardware implementation 4781 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4782 SEW, LMUL); 4783 I32VL = 4784 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4785 } 4786 4787 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4788 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL); 4789 4790 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4791 // instructions. 4792 SDValue Passthru; 4793 if (IsMasked) 4794 Passthru = DAG.getUNDEF(I32VT); 4795 else 4796 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4797 4798 if (IntNo == Intrinsic::riscv_vslide1up || 4799 IntNo == Intrinsic::riscv_vslide1up_mask) { 4800 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4801 ScalarHi, I32Mask, I32VL); 4802 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4803 ScalarLo, I32Mask, I32VL); 4804 } else { 4805 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4806 ScalarLo, I32Mask, I32VL); 4807 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4808 ScalarHi, I32Mask, I32VL); 4809 } 4810 4811 // Convert back to nxvXi64. 4812 Vec = DAG.getBitcast(VT, Vec); 4813 4814 if (!IsMasked) 4815 return Vec; 4816 // Apply mask after the operation. 4817 SDValue Mask = Operands[NumOps - 3]; 4818 SDValue MaskedOff = Operands[1]; 4819 // Assume Policy operand is the last operand. 4820 uint64_t Policy = 4821 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4822 // We don't need to select maskedoff if it's undef. 4823 if (MaskedOff.isUndef()) 4824 return Vec; 4825 // TAMU 4826 if (Policy == RISCVII::TAIL_AGNOSTIC) 4827 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4828 AVL); 4829 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4830 // It's fine because vmerge does not care mask policy. 4831 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4832 AVL); 4833 } 4834 } 4835 4836 // We need to convert the scalar to a splat vector. 4837 SDValue VL = getVLOperand(Op); 4838 assert(VL.getValueType() == XLenVT); 4839 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4840 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4841 } 4842 4843 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4844 SelectionDAG &DAG) const { 4845 unsigned IntNo = Op.getConstantOperandVal(0); 4846 SDLoc DL(Op); 4847 MVT XLenVT = Subtarget.getXLenVT(); 4848 4849 switch (IntNo) { 4850 default: 4851 break; // Don't custom lower most intrinsics. 4852 case Intrinsic::thread_pointer: { 4853 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4854 return DAG.getRegister(RISCV::X4, PtrVT); 4855 } 4856 case Intrinsic::riscv_orc_b: 4857 case Intrinsic::riscv_brev8: { 4858 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4859 unsigned Opc = 4860 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4861 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4862 DAG.getConstant(7, DL, XLenVT)); 4863 } 4864 case Intrinsic::riscv_grev: 4865 case Intrinsic::riscv_gorc: { 4866 unsigned Opc = 4867 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4868 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4869 } 4870 case Intrinsic::riscv_zip: 4871 case Intrinsic::riscv_unzip: { 4872 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4873 // For i32 the immediate is 15. For i64 the immediate is 31. 4874 unsigned Opc = 4875 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4876 unsigned BitWidth = Op.getValueSizeInBits(); 4877 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4878 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4879 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4880 } 4881 case Intrinsic::riscv_shfl: 4882 case Intrinsic::riscv_unshfl: { 4883 unsigned Opc = 4884 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4885 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4886 } 4887 case Intrinsic::riscv_bcompress: 4888 case Intrinsic::riscv_bdecompress: { 4889 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4890 : RISCVISD::BDECOMPRESS; 4891 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4892 } 4893 case Intrinsic::riscv_bfp: 4894 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4895 Op.getOperand(2)); 4896 case Intrinsic::riscv_fsl: 4897 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4898 Op.getOperand(2), Op.getOperand(3)); 4899 case Intrinsic::riscv_fsr: 4900 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4901 Op.getOperand(2), Op.getOperand(3)); 4902 case Intrinsic::riscv_vmv_x_s: 4903 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4904 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4905 Op.getOperand(1)); 4906 case Intrinsic::riscv_vmv_v_x: 4907 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4908 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4909 Subtarget); 4910 case Intrinsic::riscv_vfmv_v_f: 4911 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4912 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4913 case Intrinsic::riscv_vmv_s_x: { 4914 SDValue Scalar = Op.getOperand(2); 4915 4916 if (Scalar.getValueType().bitsLE(XLenVT)) { 4917 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4918 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4919 Op.getOperand(1), Scalar, Op.getOperand(3)); 4920 } 4921 4922 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4923 4924 // This is an i64 value that lives in two scalar registers. We have to 4925 // insert this in a convoluted way. First we build vXi64 splat containing 4926 // the two values that we assemble using some bit math. Next we'll use 4927 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4928 // to merge element 0 from our splat into the source vector. 4929 // FIXME: This is probably not the best way to do this, but it is 4930 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4931 // point. 4932 // sw lo, (a0) 4933 // sw hi, 4(a0) 4934 // vlse vX, (a0) 4935 // 4936 // vid.v vVid 4937 // vmseq.vx mMask, vVid, 0 4938 // vmerge.vvm vDest, vSrc, vVal, mMask 4939 MVT VT = Op.getSimpleValueType(); 4940 SDValue Vec = Op.getOperand(1); 4941 SDValue VL = getVLOperand(Op); 4942 4943 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4944 if (Op.getOperand(1).isUndef()) 4945 return SplattedVal; 4946 SDValue SplattedIdx = 4947 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4948 DAG.getConstant(0, DL, MVT::i32), VL); 4949 4950 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4951 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4952 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4953 SDValue SelectCond = 4954 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4955 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4956 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4957 Vec, VL); 4958 } 4959 } 4960 4961 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4962 } 4963 4964 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4965 SelectionDAG &DAG) const { 4966 unsigned IntNo = Op.getConstantOperandVal(1); 4967 switch (IntNo) { 4968 default: 4969 break; 4970 case Intrinsic::riscv_masked_strided_load: { 4971 SDLoc DL(Op); 4972 MVT XLenVT = Subtarget.getXLenVT(); 4973 4974 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4975 // the selection of the masked intrinsics doesn't do this for us. 4976 SDValue Mask = Op.getOperand(5); 4977 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4978 4979 MVT VT = Op->getSimpleValueType(0); 4980 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4981 4982 SDValue PassThru = Op.getOperand(2); 4983 if (!IsUnmasked) { 4984 MVT MaskVT = 4985 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4986 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4987 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4988 } 4989 4990 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4991 4992 SDValue IntID = DAG.getTargetConstant( 4993 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4994 XLenVT); 4995 4996 auto *Load = cast<MemIntrinsicSDNode>(Op); 4997 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4998 if (IsUnmasked) 4999 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5000 else 5001 Ops.push_back(PassThru); 5002 Ops.push_back(Op.getOperand(3)); // Ptr 5003 Ops.push_back(Op.getOperand(4)); // Stride 5004 if (!IsUnmasked) 5005 Ops.push_back(Mask); 5006 Ops.push_back(VL); 5007 if (!IsUnmasked) { 5008 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 5009 Ops.push_back(Policy); 5010 } 5011 5012 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5013 SDValue Result = 5014 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5015 Load->getMemoryVT(), Load->getMemOperand()); 5016 SDValue Chain = Result.getValue(1); 5017 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5018 return DAG.getMergeValues({Result, Chain}, DL); 5019 } 5020 case Intrinsic::riscv_seg2_load: 5021 case Intrinsic::riscv_seg3_load: 5022 case Intrinsic::riscv_seg4_load: 5023 case Intrinsic::riscv_seg5_load: 5024 case Intrinsic::riscv_seg6_load: 5025 case Intrinsic::riscv_seg7_load: 5026 case Intrinsic::riscv_seg8_load: { 5027 SDLoc DL(Op); 5028 static const Intrinsic::ID VlsegInts[7] = { 5029 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 5030 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 5031 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 5032 Intrinsic::riscv_vlseg8}; 5033 unsigned NF = Op->getNumValues() - 1; 5034 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 5035 MVT XLenVT = Subtarget.getXLenVT(); 5036 MVT VT = Op->getSimpleValueType(0); 5037 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5038 5039 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5040 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 5041 auto *Load = cast<MemIntrinsicSDNode>(Op); 5042 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 5043 ContainerVTs.push_back(MVT::Other); 5044 SDVTList VTs = DAG.getVTList(ContainerVTs); 5045 SDValue Result = 5046 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 5047 {Load->getChain(), IntID, Op.getOperand(2), VL}, 5048 Load->getMemoryVT(), Load->getMemOperand()); 5049 SmallVector<SDValue, 9> Results; 5050 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5051 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5052 DAG, Subtarget)); 5053 Results.push_back(Result.getValue(NF)); 5054 return DAG.getMergeValues(Results, DL); 5055 } 5056 } 5057 5058 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5059 } 5060 5061 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5062 SelectionDAG &DAG) const { 5063 unsigned IntNo = Op.getConstantOperandVal(1); 5064 switch (IntNo) { 5065 default: 5066 break; 5067 case Intrinsic::riscv_masked_strided_store: { 5068 SDLoc DL(Op); 5069 MVT XLenVT = Subtarget.getXLenVT(); 5070 5071 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5072 // the selection of the masked intrinsics doesn't do this for us. 5073 SDValue Mask = Op.getOperand(5); 5074 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5075 5076 SDValue Val = Op.getOperand(2); 5077 MVT VT = Val.getSimpleValueType(); 5078 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5079 5080 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5081 if (!IsUnmasked) { 5082 MVT MaskVT = 5083 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5084 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5085 } 5086 5087 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5088 5089 SDValue IntID = DAG.getTargetConstant( 5090 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5091 XLenVT); 5092 5093 auto *Store = cast<MemIntrinsicSDNode>(Op); 5094 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5095 Ops.push_back(Val); 5096 Ops.push_back(Op.getOperand(3)); // Ptr 5097 Ops.push_back(Op.getOperand(4)); // Stride 5098 if (!IsUnmasked) 5099 Ops.push_back(Mask); 5100 Ops.push_back(VL); 5101 5102 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5103 Ops, Store->getMemoryVT(), 5104 Store->getMemOperand()); 5105 } 5106 } 5107 5108 return SDValue(); 5109 } 5110 5111 static MVT getLMUL1VT(MVT VT) { 5112 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5113 "Unexpected vector MVT"); 5114 return MVT::getScalableVectorVT( 5115 VT.getVectorElementType(), 5116 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5117 } 5118 5119 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5120 switch (ISDOpcode) { 5121 default: 5122 llvm_unreachable("Unhandled reduction"); 5123 case ISD::VECREDUCE_ADD: 5124 return RISCVISD::VECREDUCE_ADD_VL; 5125 case ISD::VECREDUCE_UMAX: 5126 return RISCVISD::VECREDUCE_UMAX_VL; 5127 case ISD::VECREDUCE_SMAX: 5128 return RISCVISD::VECREDUCE_SMAX_VL; 5129 case ISD::VECREDUCE_UMIN: 5130 return RISCVISD::VECREDUCE_UMIN_VL; 5131 case ISD::VECREDUCE_SMIN: 5132 return RISCVISD::VECREDUCE_SMIN_VL; 5133 case ISD::VECREDUCE_AND: 5134 return RISCVISD::VECREDUCE_AND_VL; 5135 case ISD::VECREDUCE_OR: 5136 return RISCVISD::VECREDUCE_OR_VL; 5137 case ISD::VECREDUCE_XOR: 5138 return RISCVISD::VECREDUCE_XOR_VL; 5139 } 5140 } 5141 5142 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5143 SelectionDAG &DAG, 5144 bool IsVP) const { 5145 SDLoc DL(Op); 5146 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5147 MVT VecVT = Vec.getSimpleValueType(); 5148 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5149 Op.getOpcode() == ISD::VECREDUCE_OR || 5150 Op.getOpcode() == ISD::VECREDUCE_XOR || 5151 Op.getOpcode() == ISD::VP_REDUCE_AND || 5152 Op.getOpcode() == ISD::VP_REDUCE_OR || 5153 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5154 "Unexpected reduction lowering"); 5155 5156 MVT XLenVT = Subtarget.getXLenVT(); 5157 assert(Op.getValueType() == XLenVT && 5158 "Expected reduction output to be legalized to XLenVT"); 5159 5160 MVT ContainerVT = VecVT; 5161 if (VecVT.isFixedLengthVector()) { 5162 ContainerVT = getContainerForFixedLengthVector(VecVT); 5163 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5164 } 5165 5166 SDValue Mask, VL; 5167 if (IsVP) { 5168 Mask = Op.getOperand(2); 5169 VL = Op.getOperand(3); 5170 } else { 5171 std::tie(Mask, VL) = 5172 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5173 } 5174 5175 unsigned BaseOpc; 5176 ISD::CondCode CC; 5177 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5178 5179 switch (Op.getOpcode()) { 5180 default: 5181 llvm_unreachable("Unhandled reduction"); 5182 case ISD::VECREDUCE_AND: 5183 case ISD::VP_REDUCE_AND: { 5184 // vcpop ~x == 0 5185 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5186 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5187 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5188 CC = ISD::SETEQ; 5189 BaseOpc = ISD::AND; 5190 break; 5191 } 5192 case ISD::VECREDUCE_OR: 5193 case ISD::VP_REDUCE_OR: 5194 // vcpop x != 0 5195 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5196 CC = ISD::SETNE; 5197 BaseOpc = ISD::OR; 5198 break; 5199 case ISD::VECREDUCE_XOR: 5200 case ISD::VP_REDUCE_XOR: { 5201 // ((vcpop x) & 1) != 0 5202 SDValue One = DAG.getConstant(1, DL, XLenVT); 5203 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5204 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5205 CC = ISD::SETNE; 5206 BaseOpc = ISD::XOR; 5207 break; 5208 } 5209 } 5210 5211 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5212 5213 if (!IsVP) 5214 return SetCC; 5215 5216 // Now include the start value in the operation. 5217 // Note that we must return the start value when no elements are operated 5218 // upon. The vcpop instructions we've emitted in each case above will return 5219 // 0 for an inactive vector, and so we've already received the neutral value: 5220 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5221 // can simply include the start value. 5222 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5223 } 5224 5225 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5226 SelectionDAG &DAG) const { 5227 SDLoc DL(Op); 5228 SDValue Vec = Op.getOperand(0); 5229 EVT VecEVT = Vec.getValueType(); 5230 5231 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5232 5233 // Due to ordering in legalize types we may have a vector type that needs to 5234 // be split. Do that manually so we can get down to a legal type. 5235 while (getTypeAction(*DAG.getContext(), VecEVT) == 5236 TargetLowering::TypeSplitVector) { 5237 SDValue Lo, Hi; 5238 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5239 VecEVT = Lo.getValueType(); 5240 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5241 } 5242 5243 // TODO: The type may need to be widened rather than split. Or widened before 5244 // it can be split. 5245 if (!isTypeLegal(VecEVT)) 5246 return SDValue(); 5247 5248 MVT VecVT = VecEVT.getSimpleVT(); 5249 MVT VecEltVT = VecVT.getVectorElementType(); 5250 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5251 5252 MVT ContainerVT = VecVT; 5253 if (VecVT.isFixedLengthVector()) { 5254 ContainerVT = getContainerForFixedLengthVector(VecVT); 5255 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5256 } 5257 5258 MVT M1VT = getLMUL1VT(ContainerVT); 5259 MVT XLenVT = Subtarget.getXLenVT(); 5260 5261 SDValue Mask, VL; 5262 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5263 5264 SDValue NeutralElem = 5265 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5266 SDValue IdentitySplat = 5267 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5268 M1VT, DL, DAG, Subtarget); 5269 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5270 IdentitySplat, Mask, VL); 5271 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5272 DAG.getConstant(0, DL, XLenVT)); 5273 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5274 } 5275 5276 // Given a reduction op, this function returns the matching reduction opcode, 5277 // the vector SDValue and the scalar SDValue required to lower this to a 5278 // RISCVISD node. 5279 static std::tuple<unsigned, SDValue, SDValue> 5280 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5281 SDLoc DL(Op); 5282 auto Flags = Op->getFlags(); 5283 unsigned Opcode = Op.getOpcode(); 5284 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5285 switch (Opcode) { 5286 default: 5287 llvm_unreachable("Unhandled reduction"); 5288 case ISD::VECREDUCE_FADD: { 5289 // Use positive zero if we can. It is cheaper to materialize. 5290 SDValue Zero = 5291 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5292 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5293 } 5294 case ISD::VECREDUCE_SEQ_FADD: 5295 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5296 Op.getOperand(0)); 5297 case ISD::VECREDUCE_FMIN: 5298 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5299 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5300 case ISD::VECREDUCE_FMAX: 5301 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5302 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5303 } 5304 } 5305 5306 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5307 SelectionDAG &DAG) const { 5308 SDLoc DL(Op); 5309 MVT VecEltVT = Op.getSimpleValueType(); 5310 5311 unsigned RVVOpcode; 5312 SDValue VectorVal, ScalarVal; 5313 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5314 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5315 MVT VecVT = VectorVal.getSimpleValueType(); 5316 5317 MVT ContainerVT = VecVT; 5318 if (VecVT.isFixedLengthVector()) { 5319 ContainerVT = getContainerForFixedLengthVector(VecVT); 5320 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5321 } 5322 5323 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5324 MVT XLenVT = Subtarget.getXLenVT(); 5325 5326 SDValue Mask, VL; 5327 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5328 5329 SDValue ScalarSplat = 5330 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5331 M1VT, DL, DAG, Subtarget); 5332 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5333 VectorVal, ScalarSplat, Mask, VL); 5334 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5335 DAG.getConstant(0, DL, XLenVT)); 5336 } 5337 5338 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5339 switch (ISDOpcode) { 5340 default: 5341 llvm_unreachable("Unhandled reduction"); 5342 case ISD::VP_REDUCE_ADD: 5343 return RISCVISD::VECREDUCE_ADD_VL; 5344 case ISD::VP_REDUCE_UMAX: 5345 return RISCVISD::VECREDUCE_UMAX_VL; 5346 case ISD::VP_REDUCE_SMAX: 5347 return RISCVISD::VECREDUCE_SMAX_VL; 5348 case ISD::VP_REDUCE_UMIN: 5349 return RISCVISD::VECREDUCE_UMIN_VL; 5350 case ISD::VP_REDUCE_SMIN: 5351 return RISCVISD::VECREDUCE_SMIN_VL; 5352 case ISD::VP_REDUCE_AND: 5353 return RISCVISD::VECREDUCE_AND_VL; 5354 case ISD::VP_REDUCE_OR: 5355 return RISCVISD::VECREDUCE_OR_VL; 5356 case ISD::VP_REDUCE_XOR: 5357 return RISCVISD::VECREDUCE_XOR_VL; 5358 case ISD::VP_REDUCE_FADD: 5359 return RISCVISD::VECREDUCE_FADD_VL; 5360 case ISD::VP_REDUCE_SEQ_FADD: 5361 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5362 case ISD::VP_REDUCE_FMAX: 5363 return RISCVISD::VECREDUCE_FMAX_VL; 5364 case ISD::VP_REDUCE_FMIN: 5365 return RISCVISD::VECREDUCE_FMIN_VL; 5366 } 5367 } 5368 5369 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5370 SelectionDAG &DAG) const { 5371 SDLoc DL(Op); 5372 SDValue Vec = Op.getOperand(1); 5373 EVT VecEVT = Vec.getValueType(); 5374 5375 // TODO: The type may need to be widened rather than split. Or widened before 5376 // it can be split. 5377 if (!isTypeLegal(VecEVT)) 5378 return SDValue(); 5379 5380 MVT VecVT = VecEVT.getSimpleVT(); 5381 MVT VecEltVT = VecVT.getVectorElementType(); 5382 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5383 5384 MVT ContainerVT = VecVT; 5385 if (VecVT.isFixedLengthVector()) { 5386 ContainerVT = getContainerForFixedLengthVector(VecVT); 5387 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5388 } 5389 5390 SDValue VL = Op.getOperand(3); 5391 SDValue Mask = Op.getOperand(2); 5392 5393 MVT M1VT = getLMUL1VT(ContainerVT); 5394 MVT XLenVT = Subtarget.getXLenVT(); 5395 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5396 5397 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5398 DAG.getConstant(1, DL, XLenVT), M1VT, 5399 DL, DAG, Subtarget); 5400 SDValue Reduction = 5401 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5402 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5403 DAG.getConstant(0, DL, XLenVT)); 5404 if (!VecVT.isInteger()) 5405 return Elt0; 5406 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5407 } 5408 5409 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5410 SelectionDAG &DAG) const { 5411 SDValue Vec = Op.getOperand(0); 5412 SDValue SubVec = Op.getOperand(1); 5413 MVT VecVT = Vec.getSimpleValueType(); 5414 MVT SubVecVT = SubVec.getSimpleValueType(); 5415 5416 SDLoc DL(Op); 5417 MVT XLenVT = Subtarget.getXLenVT(); 5418 unsigned OrigIdx = Op.getConstantOperandVal(2); 5419 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5420 5421 // We don't have the ability to slide mask vectors up indexed by their i1 5422 // elements; the smallest we can do is i8. Often we are able to bitcast to 5423 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5424 // into a scalable one, we might not necessarily have enough scalable 5425 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5426 if (SubVecVT.getVectorElementType() == MVT::i1 && 5427 (OrigIdx != 0 || !Vec.isUndef())) { 5428 if (VecVT.getVectorMinNumElements() >= 8 && 5429 SubVecVT.getVectorMinNumElements() >= 8) { 5430 assert(OrigIdx % 8 == 0 && "Invalid index"); 5431 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5432 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5433 "Unexpected mask vector lowering"); 5434 OrigIdx /= 8; 5435 SubVecVT = 5436 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5437 SubVecVT.isScalableVector()); 5438 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5439 VecVT.isScalableVector()); 5440 Vec = DAG.getBitcast(VecVT, Vec); 5441 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5442 } else { 5443 // We can't slide this mask vector up indexed by its i1 elements. 5444 // This poses a problem when we wish to insert a scalable vector which 5445 // can't be re-expressed as a larger type. Just choose the slow path and 5446 // extend to a larger type, then truncate back down. 5447 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5448 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5449 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5450 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5451 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5452 Op.getOperand(2)); 5453 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5454 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5455 } 5456 } 5457 5458 // If the subvector vector is a fixed-length type, we cannot use subregister 5459 // manipulation to simplify the codegen; we don't know which register of a 5460 // LMUL group contains the specific subvector as we only know the minimum 5461 // register size. Therefore we must slide the vector group up the full 5462 // amount. 5463 if (SubVecVT.isFixedLengthVector()) { 5464 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5465 return Op; 5466 MVT ContainerVT = VecVT; 5467 if (VecVT.isFixedLengthVector()) { 5468 ContainerVT = getContainerForFixedLengthVector(VecVT); 5469 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5470 } 5471 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5472 DAG.getUNDEF(ContainerVT), SubVec, 5473 DAG.getConstant(0, DL, XLenVT)); 5474 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5475 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5476 return DAG.getBitcast(Op.getValueType(), SubVec); 5477 } 5478 SDValue Mask = 5479 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5480 // Set the vector length to only the number of elements we care about. Note 5481 // that for slideup this includes the offset. 5482 SDValue VL = 5483 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5484 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5485 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5486 SubVec, SlideupAmt, Mask, VL); 5487 if (VecVT.isFixedLengthVector()) 5488 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5489 return DAG.getBitcast(Op.getValueType(), Slideup); 5490 } 5491 5492 unsigned SubRegIdx, RemIdx; 5493 std::tie(SubRegIdx, RemIdx) = 5494 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5495 VecVT, SubVecVT, OrigIdx, TRI); 5496 5497 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5498 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5499 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5500 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5501 5502 // 1. If the Idx has been completely eliminated and this subvector's size is 5503 // a vector register or a multiple thereof, or the surrounding elements are 5504 // undef, then this is a subvector insert which naturally aligns to a vector 5505 // register. These can easily be handled using subregister manipulation. 5506 // 2. If the subvector is smaller than a vector register, then the insertion 5507 // must preserve the undisturbed elements of the register. We do this by 5508 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5509 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5510 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5511 // LMUL=1 type back into the larger vector (resolving to another subregister 5512 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5513 // to avoid allocating a large register group to hold our subvector. 5514 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5515 return Op; 5516 5517 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5518 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5519 // (in our case undisturbed). This means we can set up a subvector insertion 5520 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5521 // size of the subvector. 5522 MVT InterSubVT = VecVT; 5523 SDValue AlignedExtract = Vec; 5524 unsigned AlignedIdx = OrigIdx - RemIdx; 5525 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5526 InterSubVT = getLMUL1VT(VecVT); 5527 // Extract a subvector equal to the nearest full vector register type. This 5528 // should resolve to a EXTRACT_SUBREG instruction. 5529 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5530 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5531 } 5532 5533 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5534 // For scalable vectors this must be further multiplied by vscale. 5535 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5536 5537 SDValue Mask, VL; 5538 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5539 5540 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5541 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5542 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5543 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5544 5545 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5546 DAG.getUNDEF(InterSubVT), SubVec, 5547 DAG.getConstant(0, DL, XLenVT)); 5548 5549 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5550 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5551 5552 // If required, insert this subvector back into the correct vector register. 5553 // This should resolve to an INSERT_SUBREG instruction. 5554 if (VecVT.bitsGT(InterSubVT)) 5555 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5556 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5557 5558 // We might have bitcast from a mask type: cast back to the original type if 5559 // required. 5560 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5561 } 5562 5563 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5564 SelectionDAG &DAG) const { 5565 SDValue Vec = Op.getOperand(0); 5566 MVT SubVecVT = Op.getSimpleValueType(); 5567 MVT VecVT = Vec.getSimpleValueType(); 5568 5569 SDLoc DL(Op); 5570 MVT XLenVT = Subtarget.getXLenVT(); 5571 unsigned OrigIdx = Op.getConstantOperandVal(1); 5572 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5573 5574 // We don't have the ability to slide mask vectors down indexed by their i1 5575 // elements; the smallest we can do is i8. Often we are able to bitcast to 5576 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5577 // from a scalable one, we might not necessarily have enough scalable 5578 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5579 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5580 if (VecVT.getVectorMinNumElements() >= 8 && 5581 SubVecVT.getVectorMinNumElements() >= 8) { 5582 assert(OrigIdx % 8 == 0 && "Invalid index"); 5583 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5584 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5585 "Unexpected mask vector lowering"); 5586 OrigIdx /= 8; 5587 SubVecVT = 5588 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5589 SubVecVT.isScalableVector()); 5590 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5591 VecVT.isScalableVector()); 5592 Vec = DAG.getBitcast(VecVT, Vec); 5593 } else { 5594 // We can't slide this mask vector down, indexed by its i1 elements. 5595 // This poses a problem when we wish to extract a scalable vector which 5596 // can't be re-expressed as a larger type. Just choose the slow path and 5597 // extend to a larger type, then truncate back down. 5598 // TODO: We could probably improve this when extracting certain fixed 5599 // from fixed, where we can extract as i8 and shift the correct element 5600 // right to reach the desired subvector? 5601 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5602 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5603 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5604 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5605 Op.getOperand(1)); 5606 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5607 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5608 } 5609 } 5610 5611 // If the subvector vector is a fixed-length type, we cannot use subregister 5612 // manipulation to simplify the codegen; we don't know which register of a 5613 // LMUL group contains the specific subvector as we only know the minimum 5614 // register size. Therefore we must slide the vector group down the full 5615 // amount. 5616 if (SubVecVT.isFixedLengthVector()) { 5617 // With an index of 0 this is a cast-like subvector, which can be performed 5618 // with subregister operations. 5619 if (OrigIdx == 0) 5620 return Op; 5621 MVT ContainerVT = VecVT; 5622 if (VecVT.isFixedLengthVector()) { 5623 ContainerVT = getContainerForFixedLengthVector(VecVT); 5624 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5625 } 5626 SDValue Mask = 5627 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5628 // Set the vector length to only the number of elements we care about. This 5629 // avoids sliding down elements we're going to discard straight away. 5630 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5631 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5632 SDValue Slidedown = 5633 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5634 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5635 // Now we can use a cast-like subvector extract to get the result. 5636 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5637 DAG.getConstant(0, DL, XLenVT)); 5638 return DAG.getBitcast(Op.getValueType(), Slidedown); 5639 } 5640 5641 unsigned SubRegIdx, RemIdx; 5642 std::tie(SubRegIdx, RemIdx) = 5643 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5644 VecVT, SubVecVT, OrigIdx, TRI); 5645 5646 // If the Idx has been completely eliminated then this is a subvector extract 5647 // which naturally aligns to a vector register. These can easily be handled 5648 // using subregister manipulation. 5649 if (RemIdx == 0) 5650 return Op; 5651 5652 // Else we must shift our vector register directly to extract the subvector. 5653 // Do this using VSLIDEDOWN. 5654 5655 // If the vector type is an LMUL-group type, extract a subvector equal to the 5656 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5657 // instruction. 5658 MVT InterSubVT = VecVT; 5659 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5660 InterSubVT = getLMUL1VT(VecVT); 5661 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5662 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5663 } 5664 5665 // Slide this vector register down by the desired number of elements in order 5666 // to place the desired subvector starting at element 0. 5667 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5668 // For scalable vectors this must be further multiplied by vscale. 5669 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5670 5671 SDValue Mask, VL; 5672 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5673 SDValue Slidedown = 5674 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5675 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5676 5677 // Now the vector is in the right position, extract our final subvector. This 5678 // should resolve to a COPY. 5679 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5680 DAG.getConstant(0, DL, XLenVT)); 5681 5682 // We might have bitcast from a mask type: cast back to the original type if 5683 // required. 5684 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5685 } 5686 5687 // Lower step_vector to the vid instruction. Any non-identity step value must 5688 // be accounted for my manual expansion. 5689 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5690 SelectionDAG &DAG) const { 5691 SDLoc DL(Op); 5692 MVT VT = Op.getSimpleValueType(); 5693 MVT XLenVT = Subtarget.getXLenVT(); 5694 SDValue Mask, VL; 5695 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5696 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5697 uint64_t StepValImm = Op.getConstantOperandVal(0); 5698 if (StepValImm != 1) { 5699 if (isPowerOf2_64(StepValImm)) { 5700 SDValue StepVal = 5701 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5702 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5703 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5704 } else { 5705 SDValue StepVal = lowerScalarSplat( 5706 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5707 VL, VT, DL, DAG, Subtarget); 5708 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5709 } 5710 } 5711 return StepVec; 5712 } 5713 5714 // Implement vector_reverse using vrgather.vv with indices determined by 5715 // subtracting the id of each element from (VLMAX-1). This will convert 5716 // the indices like so: 5717 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5718 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5719 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5720 SelectionDAG &DAG) const { 5721 SDLoc DL(Op); 5722 MVT VecVT = Op.getSimpleValueType(); 5723 unsigned EltSize = VecVT.getScalarSizeInBits(); 5724 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5725 5726 unsigned MaxVLMAX = 0; 5727 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5728 if (VectorBitsMax != 0) 5729 MaxVLMAX = 5730 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5731 5732 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5733 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5734 5735 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5736 // to use vrgatherei16.vv. 5737 // TODO: It's also possible to use vrgatherei16.vv for other types to 5738 // decrease register width for the index calculation. 5739 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5740 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5741 // Reverse each half, then reassemble them in reverse order. 5742 // NOTE: It's also possible that after splitting that VLMAX no longer 5743 // requires vrgatherei16.vv. 5744 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5745 SDValue Lo, Hi; 5746 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5747 EVT LoVT, HiVT; 5748 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5749 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5750 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5751 // Reassemble the low and high pieces reversed. 5752 // FIXME: This is a CONCAT_VECTORS. 5753 SDValue Res = 5754 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5755 DAG.getIntPtrConstant(0, DL)); 5756 return DAG.getNode( 5757 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5758 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5759 } 5760 5761 // Just promote the int type to i16 which will double the LMUL. 5762 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5763 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5764 } 5765 5766 MVT XLenVT = Subtarget.getXLenVT(); 5767 SDValue Mask, VL; 5768 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5769 5770 // Calculate VLMAX-1 for the desired SEW. 5771 unsigned MinElts = VecVT.getVectorMinNumElements(); 5772 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5773 DAG.getConstant(MinElts, DL, XLenVT)); 5774 SDValue VLMinus1 = 5775 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5776 5777 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5778 bool IsRV32E64 = 5779 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5780 SDValue SplatVL; 5781 if (!IsRV32E64) 5782 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5783 else 5784 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5785 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5786 5787 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5788 SDValue Indices = 5789 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5790 5791 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5792 } 5793 5794 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5795 SelectionDAG &DAG) const { 5796 SDLoc DL(Op); 5797 SDValue V1 = Op.getOperand(0); 5798 SDValue V2 = Op.getOperand(1); 5799 MVT XLenVT = Subtarget.getXLenVT(); 5800 MVT VecVT = Op.getSimpleValueType(); 5801 5802 unsigned MinElts = VecVT.getVectorMinNumElements(); 5803 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5804 DAG.getConstant(MinElts, DL, XLenVT)); 5805 5806 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5807 SDValue DownOffset, UpOffset; 5808 if (ImmValue >= 0) { 5809 // The operand is a TargetConstant, we need to rebuild it as a regular 5810 // constant. 5811 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5812 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5813 } else { 5814 // The operand is a TargetConstant, we need to rebuild it as a regular 5815 // constant rather than negating the original operand. 5816 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5817 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5818 } 5819 5820 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5821 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5822 5823 SDValue SlideDown = 5824 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5825 DownOffset, TrueMask, UpOffset); 5826 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5827 TrueMask, 5828 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5829 } 5830 5831 SDValue 5832 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5833 SelectionDAG &DAG) const { 5834 SDLoc DL(Op); 5835 auto *Load = cast<LoadSDNode>(Op); 5836 5837 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5838 Load->getMemoryVT(), 5839 *Load->getMemOperand()) && 5840 "Expecting a correctly-aligned load"); 5841 5842 MVT VT = Op.getSimpleValueType(); 5843 MVT XLenVT = Subtarget.getXLenVT(); 5844 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5845 5846 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5847 5848 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5849 SDValue IntID = DAG.getTargetConstant( 5850 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5851 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5852 if (!IsMaskOp) 5853 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5854 Ops.push_back(Load->getBasePtr()); 5855 Ops.push_back(VL); 5856 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5857 SDValue NewLoad = 5858 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5859 Load->getMemoryVT(), Load->getMemOperand()); 5860 5861 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5862 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5863 } 5864 5865 SDValue 5866 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5867 SelectionDAG &DAG) const { 5868 SDLoc DL(Op); 5869 auto *Store = cast<StoreSDNode>(Op); 5870 5871 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5872 Store->getMemoryVT(), 5873 *Store->getMemOperand()) && 5874 "Expecting a correctly-aligned store"); 5875 5876 SDValue StoreVal = Store->getValue(); 5877 MVT VT = StoreVal.getSimpleValueType(); 5878 MVT XLenVT = Subtarget.getXLenVT(); 5879 5880 // If the size less than a byte, we need to pad with zeros to make a byte. 5881 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5882 VT = MVT::v8i1; 5883 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5884 DAG.getConstant(0, DL, VT), StoreVal, 5885 DAG.getIntPtrConstant(0, DL)); 5886 } 5887 5888 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5889 5890 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5891 5892 SDValue NewValue = 5893 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5894 5895 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5896 SDValue IntID = DAG.getTargetConstant( 5897 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5898 return DAG.getMemIntrinsicNode( 5899 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5900 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5901 Store->getMemoryVT(), Store->getMemOperand()); 5902 } 5903 5904 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5905 SelectionDAG &DAG) const { 5906 SDLoc DL(Op); 5907 MVT VT = Op.getSimpleValueType(); 5908 5909 const auto *MemSD = cast<MemSDNode>(Op); 5910 EVT MemVT = MemSD->getMemoryVT(); 5911 MachineMemOperand *MMO = MemSD->getMemOperand(); 5912 SDValue Chain = MemSD->getChain(); 5913 SDValue BasePtr = MemSD->getBasePtr(); 5914 5915 SDValue Mask, PassThru, VL; 5916 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5917 Mask = VPLoad->getMask(); 5918 PassThru = DAG.getUNDEF(VT); 5919 VL = VPLoad->getVectorLength(); 5920 } else { 5921 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5922 Mask = MLoad->getMask(); 5923 PassThru = MLoad->getPassThru(); 5924 } 5925 5926 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5927 5928 MVT XLenVT = Subtarget.getXLenVT(); 5929 5930 MVT ContainerVT = VT; 5931 if (VT.isFixedLengthVector()) { 5932 ContainerVT = getContainerForFixedLengthVector(VT); 5933 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5934 if (!IsUnmasked) { 5935 MVT MaskVT = 5936 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5937 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5938 } 5939 } 5940 5941 if (!VL) 5942 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5943 5944 unsigned IntID = 5945 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5946 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5947 if (IsUnmasked) 5948 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5949 else 5950 Ops.push_back(PassThru); 5951 Ops.push_back(BasePtr); 5952 if (!IsUnmasked) 5953 Ops.push_back(Mask); 5954 Ops.push_back(VL); 5955 if (!IsUnmasked) 5956 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5957 5958 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5959 5960 SDValue Result = 5961 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5962 Chain = Result.getValue(1); 5963 5964 if (VT.isFixedLengthVector()) 5965 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5966 5967 return DAG.getMergeValues({Result, Chain}, DL); 5968 } 5969 5970 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5971 SelectionDAG &DAG) const { 5972 SDLoc DL(Op); 5973 5974 const auto *MemSD = cast<MemSDNode>(Op); 5975 EVT MemVT = MemSD->getMemoryVT(); 5976 MachineMemOperand *MMO = MemSD->getMemOperand(); 5977 SDValue Chain = MemSD->getChain(); 5978 SDValue BasePtr = MemSD->getBasePtr(); 5979 SDValue Val, Mask, VL; 5980 5981 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5982 Val = VPStore->getValue(); 5983 Mask = VPStore->getMask(); 5984 VL = VPStore->getVectorLength(); 5985 } else { 5986 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5987 Val = MStore->getValue(); 5988 Mask = MStore->getMask(); 5989 } 5990 5991 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5992 5993 MVT VT = Val.getSimpleValueType(); 5994 MVT XLenVT = Subtarget.getXLenVT(); 5995 5996 MVT ContainerVT = VT; 5997 if (VT.isFixedLengthVector()) { 5998 ContainerVT = getContainerForFixedLengthVector(VT); 5999 6000 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6001 if (!IsUnmasked) { 6002 MVT MaskVT = 6003 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6004 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6005 } 6006 } 6007 6008 if (!VL) 6009 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6010 6011 unsigned IntID = 6012 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 6013 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6014 Ops.push_back(Val); 6015 Ops.push_back(BasePtr); 6016 if (!IsUnmasked) 6017 Ops.push_back(Mask); 6018 Ops.push_back(VL); 6019 6020 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6021 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6022 } 6023 6024 SDValue 6025 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 6026 SelectionDAG &DAG) const { 6027 MVT InVT = Op.getOperand(0).getSimpleValueType(); 6028 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 6029 6030 MVT VT = Op.getSimpleValueType(); 6031 6032 SDValue Op1 = 6033 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 6034 SDValue Op2 = 6035 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6036 6037 SDLoc DL(Op); 6038 SDValue VL = 6039 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 6040 6041 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6042 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6043 6044 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 6045 Op.getOperand(2), Mask, VL); 6046 6047 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 6048 } 6049 6050 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6051 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6052 MVT VT = Op.getSimpleValueType(); 6053 6054 if (VT.getVectorElementType() == MVT::i1) 6055 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 6056 6057 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 6058 } 6059 6060 SDValue 6061 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6062 SelectionDAG &DAG) const { 6063 unsigned Opc; 6064 switch (Op.getOpcode()) { 6065 default: llvm_unreachable("Unexpected opcode!"); 6066 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6067 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6068 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6069 } 6070 6071 return lowerToScalableOp(Op, DAG, Opc); 6072 } 6073 6074 // Lower vector ABS to smax(X, sub(0, X)). 6075 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6076 SDLoc DL(Op); 6077 MVT VT = Op.getSimpleValueType(); 6078 SDValue X = Op.getOperand(0); 6079 6080 assert(VT.isFixedLengthVector() && "Unexpected type"); 6081 6082 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6083 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6084 6085 SDValue Mask, VL; 6086 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6087 6088 SDValue SplatZero = DAG.getNode( 6089 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6090 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6091 SDValue NegX = 6092 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6093 SDValue Max = 6094 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6095 6096 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6097 } 6098 6099 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6100 SDValue Op, SelectionDAG &DAG) const { 6101 SDLoc DL(Op); 6102 MVT VT = Op.getSimpleValueType(); 6103 SDValue Mag = Op.getOperand(0); 6104 SDValue Sign = Op.getOperand(1); 6105 assert(Mag.getValueType() == Sign.getValueType() && 6106 "Can only handle COPYSIGN with matching types."); 6107 6108 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6109 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6110 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6111 6112 SDValue Mask, VL; 6113 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6114 6115 SDValue CopySign = 6116 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6117 6118 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6119 } 6120 6121 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6122 SDValue Op, SelectionDAG &DAG) const { 6123 MVT VT = Op.getSimpleValueType(); 6124 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6125 6126 MVT I1ContainerVT = 6127 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6128 6129 SDValue CC = 6130 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6131 SDValue Op1 = 6132 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6133 SDValue Op2 = 6134 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6135 6136 SDLoc DL(Op); 6137 SDValue Mask, VL; 6138 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6139 6140 SDValue Select = 6141 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6142 6143 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6144 } 6145 6146 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6147 unsigned NewOpc, 6148 bool HasMask) const { 6149 MVT VT = Op.getSimpleValueType(); 6150 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6151 6152 // Create list of operands by converting existing ones to scalable types. 6153 SmallVector<SDValue, 6> Ops; 6154 for (const SDValue &V : Op->op_values()) { 6155 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6156 6157 // Pass through non-vector operands. 6158 if (!V.getValueType().isVector()) { 6159 Ops.push_back(V); 6160 continue; 6161 } 6162 6163 // "cast" fixed length vector to a scalable vector. 6164 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6165 "Only fixed length vectors are supported!"); 6166 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6167 } 6168 6169 SDLoc DL(Op); 6170 SDValue Mask, VL; 6171 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6172 if (HasMask) 6173 Ops.push_back(Mask); 6174 Ops.push_back(VL); 6175 6176 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6177 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6178 } 6179 6180 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6181 // * Operands of each node are assumed to be in the same order. 6182 // * The EVL operand is promoted from i32 to i64 on RV64. 6183 // * Fixed-length vectors are converted to their scalable-vector container 6184 // types. 6185 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6186 unsigned RISCVISDOpc) const { 6187 SDLoc DL(Op); 6188 MVT VT = Op.getSimpleValueType(); 6189 SmallVector<SDValue, 4> Ops; 6190 6191 for (const auto &OpIdx : enumerate(Op->ops())) { 6192 SDValue V = OpIdx.value(); 6193 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6194 // Pass through operands which aren't fixed-length vectors. 6195 if (!V.getValueType().isFixedLengthVector()) { 6196 Ops.push_back(V); 6197 continue; 6198 } 6199 // "cast" fixed length vector to a scalable vector. 6200 MVT OpVT = V.getSimpleValueType(); 6201 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6202 assert(useRVVForFixedLengthVectorVT(OpVT) && 6203 "Only fixed length vectors are supported!"); 6204 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6205 } 6206 6207 if (!VT.isFixedLengthVector()) 6208 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6209 6210 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6211 6212 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6213 6214 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6215 } 6216 6217 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6218 SelectionDAG &DAG) const { 6219 SDLoc DL(Op); 6220 MVT VT = Op.getSimpleValueType(); 6221 6222 SDValue Src = Op.getOperand(0); 6223 // NOTE: Mask is dropped. 6224 SDValue VL = Op.getOperand(2); 6225 6226 MVT ContainerVT = VT; 6227 if (VT.isFixedLengthVector()) { 6228 ContainerVT = getContainerForFixedLengthVector(VT); 6229 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6230 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6231 } 6232 6233 MVT XLenVT = Subtarget.getXLenVT(); 6234 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6235 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6236 DAG.getUNDEF(ContainerVT), Zero, VL); 6237 6238 SDValue SplatValue = 6239 DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT); 6240 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6241 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6242 6243 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6244 Splat, ZeroSplat, VL); 6245 if (!VT.isFixedLengthVector()) 6246 return Result; 6247 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6248 } 6249 6250 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6251 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6252 unsigned RISCVISDOpc) const { 6253 SDLoc DL(Op); 6254 6255 SDValue Src = Op.getOperand(0); 6256 SDValue Mask = Op.getOperand(1); 6257 SDValue VL = Op.getOperand(2); 6258 6259 MVT DstVT = Op.getSimpleValueType(); 6260 MVT SrcVT = Src.getSimpleValueType(); 6261 if (DstVT.isFixedLengthVector()) { 6262 DstVT = getContainerForFixedLengthVector(DstVT); 6263 SrcVT = getContainerForFixedLengthVector(SrcVT); 6264 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6265 MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount()); 6266 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6267 } 6268 6269 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6270 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6271 ? RISCVISD::VSEXT_VL 6272 : RISCVISD::VZEXT_VL; 6273 6274 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6275 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6276 6277 SDValue Result; 6278 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6279 if (SrcVT.isInteger()) { 6280 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6281 6282 // Do we need to do any pre-widening before converting? 6283 if (SrcEltSize == 1) { 6284 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6285 MVT XLenVT = Subtarget.getXLenVT(); 6286 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6287 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6288 DAG.getUNDEF(IntVT), Zero, VL); 6289 SDValue One = DAG.getConstant( 6290 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6291 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6292 DAG.getUNDEF(IntVT), One, VL); 6293 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6294 ZeroSplat, VL); 6295 } else if (DstEltSize > (2 * SrcEltSize)) { 6296 // Widen before converting. 6297 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6298 DstVT.getVectorElementCount()); 6299 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6300 } 6301 6302 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6303 } else { 6304 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6305 "Wrong input/output vector types"); 6306 6307 // Convert f16 to f32 then convert f32 to i64. 6308 if (DstEltSize > (2 * SrcEltSize)) { 6309 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6310 MVT InterimFVT = 6311 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6312 Src = 6313 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6314 } 6315 6316 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6317 } 6318 } else { // Narrowing + Conversion 6319 if (SrcVT.isInteger()) { 6320 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6321 // First do a narrowing convert to an FP type half the size, then round 6322 // the FP type to a small FP type if needed. 6323 6324 MVT InterimFVT = DstVT; 6325 if (SrcEltSize > (2 * DstEltSize)) { 6326 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6327 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6328 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6329 } 6330 6331 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6332 6333 if (InterimFVT != DstVT) { 6334 Src = Result; 6335 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6336 } 6337 } else { 6338 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6339 "Wrong input/output vector types"); 6340 // First do a narrowing conversion to an integer half the size, then 6341 // truncate if needed. 6342 6343 if (DstEltSize == 1) { 6344 // First convert to the same size integer, then convert to mask using 6345 // setcc. 6346 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6347 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6348 DstVT.getVectorElementCount()); 6349 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6350 6351 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6352 // otherwise the conversion was undefined. 6353 MVT XLenVT = Subtarget.getXLenVT(); 6354 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6355 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6356 DAG.getUNDEF(InterimIVT), SplatZero); 6357 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6358 DAG.getCondCode(ISD::SETNE), Mask, VL); 6359 } else { 6360 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6361 DstVT.getVectorElementCount()); 6362 6363 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6364 6365 while (InterimIVT != DstVT) { 6366 SrcEltSize /= 2; 6367 Src = Result; 6368 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6369 DstVT.getVectorElementCount()); 6370 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6371 Src, Mask, VL); 6372 } 6373 } 6374 } 6375 } 6376 6377 MVT VT = Op.getSimpleValueType(); 6378 if (!VT.isFixedLengthVector()) 6379 return Result; 6380 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6381 } 6382 6383 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6384 unsigned MaskOpc, 6385 unsigned VecOpc) const { 6386 MVT VT = Op.getSimpleValueType(); 6387 if (VT.getVectorElementType() != MVT::i1) 6388 return lowerVPOp(Op, DAG, VecOpc); 6389 6390 // It is safe to drop mask parameter as masked-off elements are undef. 6391 SDValue Op1 = Op->getOperand(0); 6392 SDValue Op2 = Op->getOperand(1); 6393 SDValue VL = Op->getOperand(3); 6394 6395 MVT ContainerVT = VT; 6396 const bool IsFixed = VT.isFixedLengthVector(); 6397 if (IsFixed) { 6398 ContainerVT = getContainerForFixedLengthVector(VT); 6399 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6400 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6401 } 6402 6403 SDLoc DL(Op); 6404 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6405 if (!IsFixed) 6406 return Val; 6407 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6408 } 6409 6410 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6411 // matched to a RVV indexed load. The RVV indexed load instructions only 6412 // support the "unsigned unscaled" addressing mode; indices are implicitly 6413 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6414 // signed or scaled indexing is extended to the XLEN value type and scaled 6415 // accordingly. 6416 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6417 SelectionDAG &DAG) const { 6418 SDLoc DL(Op); 6419 MVT VT = Op.getSimpleValueType(); 6420 6421 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6422 EVT MemVT = MemSD->getMemoryVT(); 6423 MachineMemOperand *MMO = MemSD->getMemOperand(); 6424 SDValue Chain = MemSD->getChain(); 6425 SDValue BasePtr = MemSD->getBasePtr(); 6426 6427 ISD::LoadExtType LoadExtType; 6428 SDValue Index, Mask, PassThru, VL; 6429 6430 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6431 Index = VPGN->getIndex(); 6432 Mask = VPGN->getMask(); 6433 PassThru = DAG.getUNDEF(VT); 6434 VL = VPGN->getVectorLength(); 6435 // VP doesn't support extending loads. 6436 LoadExtType = ISD::NON_EXTLOAD; 6437 } else { 6438 // Else it must be a MGATHER. 6439 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6440 Index = MGN->getIndex(); 6441 Mask = MGN->getMask(); 6442 PassThru = MGN->getPassThru(); 6443 LoadExtType = MGN->getExtensionType(); 6444 } 6445 6446 MVT IndexVT = Index.getSimpleValueType(); 6447 MVT XLenVT = Subtarget.getXLenVT(); 6448 6449 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6450 "Unexpected VTs!"); 6451 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6452 // Targets have to explicitly opt-in for extending vector loads. 6453 assert(LoadExtType == ISD::NON_EXTLOAD && 6454 "Unexpected extending MGATHER/VP_GATHER"); 6455 (void)LoadExtType; 6456 6457 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6458 // the selection of the masked intrinsics doesn't do this for us. 6459 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6460 6461 MVT ContainerVT = VT; 6462 if (VT.isFixedLengthVector()) { 6463 // We need to use the larger of the result and index type to determine the 6464 // scalable type to use so we don't increase LMUL for any operand/result. 6465 if (VT.bitsGE(IndexVT)) { 6466 ContainerVT = getContainerForFixedLengthVector(VT); 6467 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6468 ContainerVT.getVectorElementCount()); 6469 } else { 6470 IndexVT = getContainerForFixedLengthVector(IndexVT); 6471 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6472 IndexVT.getVectorElementCount()); 6473 } 6474 6475 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6476 6477 if (!IsUnmasked) { 6478 MVT MaskVT = 6479 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6480 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6481 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6482 } 6483 } 6484 6485 if (!VL) 6486 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6487 6488 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6489 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6490 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6491 VL); 6492 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6493 TrueMask, VL); 6494 } 6495 6496 unsigned IntID = 6497 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6498 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6499 if (IsUnmasked) 6500 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6501 else 6502 Ops.push_back(PassThru); 6503 Ops.push_back(BasePtr); 6504 Ops.push_back(Index); 6505 if (!IsUnmasked) 6506 Ops.push_back(Mask); 6507 Ops.push_back(VL); 6508 if (!IsUnmasked) 6509 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6510 6511 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6512 SDValue Result = 6513 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6514 Chain = Result.getValue(1); 6515 6516 if (VT.isFixedLengthVector()) 6517 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6518 6519 return DAG.getMergeValues({Result, Chain}, DL); 6520 } 6521 6522 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6523 // matched to a RVV indexed store. The RVV indexed store instructions only 6524 // support the "unsigned unscaled" addressing mode; indices are implicitly 6525 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6526 // signed or scaled indexing is extended to the XLEN value type and scaled 6527 // accordingly. 6528 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6529 SelectionDAG &DAG) const { 6530 SDLoc DL(Op); 6531 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6532 EVT MemVT = MemSD->getMemoryVT(); 6533 MachineMemOperand *MMO = MemSD->getMemOperand(); 6534 SDValue Chain = MemSD->getChain(); 6535 SDValue BasePtr = MemSD->getBasePtr(); 6536 6537 bool IsTruncatingStore = false; 6538 SDValue Index, Mask, Val, VL; 6539 6540 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6541 Index = VPSN->getIndex(); 6542 Mask = VPSN->getMask(); 6543 Val = VPSN->getValue(); 6544 VL = VPSN->getVectorLength(); 6545 // VP doesn't support truncating stores. 6546 IsTruncatingStore = false; 6547 } else { 6548 // Else it must be a MSCATTER. 6549 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6550 Index = MSN->getIndex(); 6551 Mask = MSN->getMask(); 6552 Val = MSN->getValue(); 6553 IsTruncatingStore = MSN->isTruncatingStore(); 6554 } 6555 6556 MVT VT = Val.getSimpleValueType(); 6557 MVT IndexVT = Index.getSimpleValueType(); 6558 MVT XLenVT = Subtarget.getXLenVT(); 6559 6560 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6561 "Unexpected VTs!"); 6562 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6563 // Targets have to explicitly opt-in for extending vector loads and 6564 // truncating vector stores. 6565 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6566 (void)IsTruncatingStore; 6567 6568 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6569 // the selection of the masked intrinsics doesn't do this for us. 6570 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6571 6572 MVT ContainerVT = VT; 6573 if (VT.isFixedLengthVector()) { 6574 // We need to use the larger of the value and index type to determine the 6575 // scalable type to use so we don't increase LMUL for any operand/result. 6576 if (VT.bitsGE(IndexVT)) { 6577 ContainerVT = getContainerForFixedLengthVector(VT); 6578 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6579 ContainerVT.getVectorElementCount()); 6580 } else { 6581 IndexVT = getContainerForFixedLengthVector(IndexVT); 6582 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6583 IndexVT.getVectorElementCount()); 6584 } 6585 6586 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6587 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6588 6589 if (!IsUnmasked) { 6590 MVT MaskVT = 6591 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6592 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6593 } 6594 } 6595 6596 if (!VL) 6597 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6598 6599 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6600 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6601 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6602 VL); 6603 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6604 TrueMask, VL); 6605 } 6606 6607 unsigned IntID = 6608 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6609 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6610 Ops.push_back(Val); 6611 Ops.push_back(BasePtr); 6612 Ops.push_back(Index); 6613 if (!IsUnmasked) 6614 Ops.push_back(Mask); 6615 Ops.push_back(VL); 6616 6617 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6618 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6619 } 6620 6621 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6622 SelectionDAG &DAG) const { 6623 const MVT XLenVT = Subtarget.getXLenVT(); 6624 SDLoc DL(Op); 6625 SDValue Chain = Op->getOperand(0); 6626 SDValue SysRegNo = DAG.getTargetConstant( 6627 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6628 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6629 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6630 6631 // Encoding used for rounding mode in RISCV differs from that used in 6632 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6633 // table, which consists of a sequence of 4-bit fields, each representing 6634 // corresponding FLT_ROUNDS mode. 6635 static const int Table = 6636 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6637 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6638 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6639 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6640 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6641 6642 SDValue Shift = 6643 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6644 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6645 DAG.getConstant(Table, DL, XLenVT), Shift); 6646 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6647 DAG.getConstant(7, DL, XLenVT)); 6648 6649 return DAG.getMergeValues({Masked, Chain}, DL); 6650 } 6651 6652 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6653 SelectionDAG &DAG) const { 6654 const MVT XLenVT = Subtarget.getXLenVT(); 6655 SDLoc DL(Op); 6656 SDValue Chain = Op->getOperand(0); 6657 SDValue RMValue = Op->getOperand(1); 6658 SDValue SysRegNo = DAG.getTargetConstant( 6659 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6660 6661 // Encoding used for rounding mode in RISCV differs from that used in 6662 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6663 // a table, which consists of a sequence of 4-bit fields, each representing 6664 // corresponding RISCV mode. 6665 static const unsigned Table = 6666 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6667 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6668 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6669 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6670 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6671 6672 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6673 DAG.getConstant(2, DL, XLenVT)); 6674 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6675 DAG.getConstant(Table, DL, XLenVT), Shift); 6676 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6677 DAG.getConstant(0x7, DL, XLenVT)); 6678 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6679 RMValue); 6680 } 6681 6682 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6683 switch (IntNo) { 6684 default: 6685 llvm_unreachable("Unexpected Intrinsic"); 6686 case Intrinsic::riscv_bcompress: 6687 return RISCVISD::BCOMPRESSW; 6688 case Intrinsic::riscv_bdecompress: 6689 return RISCVISD::BDECOMPRESSW; 6690 case Intrinsic::riscv_bfp: 6691 return RISCVISD::BFPW; 6692 case Intrinsic::riscv_fsl: 6693 return RISCVISD::FSLW; 6694 case Intrinsic::riscv_fsr: 6695 return RISCVISD::FSRW; 6696 } 6697 } 6698 6699 // Converts the given intrinsic to a i64 operation with any extension. 6700 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6701 unsigned IntNo) { 6702 SDLoc DL(N); 6703 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6704 // Deal with the Instruction Operands 6705 SmallVector<SDValue, 3> NewOps; 6706 for (SDValue Op : drop_begin(N->ops())) 6707 // Promote the operand to i64 type 6708 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6709 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6710 // ReplaceNodeResults requires we maintain the same type for the return value. 6711 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6712 } 6713 6714 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6715 // form of the given Opcode. 6716 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6717 switch (Opcode) { 6718 default: 6719 llvm_unreachable("Unexpected opcode"); 6720 case ISD::SHL: 6721 return RISCVISD::SLLW; 6722 case ISD::SRA: 6723 return RISCVISD::SRAW; 6724 case ISD::SRL: 6725 return RISCVISD::SRLW; 6726 case ISD::SDIV: 6727 return RISCVISD::DIVW; 6728 case ISD::UDIV: 6729 return RISCVISD::DIVUW; 6730 case ISD::UREM: 6731 return RISCVISD::REMUW; 6732 case ISD::ROTL: 6733 return RISCVISD::ROLW; 6734 case ISD::ROTR: 6735 return RISCVISD::RORW; 6736 } 6737 } 6738 6739 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6740 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6741 // otherwise be promoted to i64, making it difficult to select the 6742 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6743 // type i8/i16/i32 is lost. 6744 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6745 unsigned ExtOpc = ISD::ANY_EXTEND) { 6746 SDLoc DL(N); 6747 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6748 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6749 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6750 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6751 // ReplaceNodeResults requires we maintain the same type for the return value. 6752 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6753 } 6754 6755 // Converts the given 32-bit operation to a i64 operation with signed extension 6756 // semantic to reduce the signed extension instructions. 6757 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6758 SDLoc DL(N); 6759 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6760 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6761 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6762 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6763 DAG.getValueType(MVT::i32)); 6764 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6765 } 6766 6767 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6768 SmallVectorImpl<SDValue> &Results, 6769 SelectionDAG &DAG) const { 6770 SDLoc DL(N); 6771 switch (N->getOpcode()) { 6772 default: 6773 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6774 case ISD::STRICT_FP_TO_SINT: 6775 case ISD::STRICT_FP_TO_UINT: 6776 case ISD::FP_TO_SINT: 6777 case ISD::FP_TO_UINT: { 6778 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6779 "Unexpected custom legalisation"); 6780 bool IsStrict = N->isStrictFPOpcode(); 6781 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6782 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6783 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6784 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6785 TargetLowering::TypeSoftenFloat) { 6786 if (!isTypeLegal(Op0.getValueType())) 6787 return; 6788 if (IsStrict) { 6789 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6790 : RISCVISD::STRICT_FCVT_WU_RV64; 6791 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6792 SDValue Res = DAG.getNode( 6793 Opc, DL, VTs, N->getOperand(0), Op0, 6794 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6795 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6796 Results.push_back(Res.getValue(1)); 6797 return; 6798 } 6799 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6800 SDValue Res = 6801 DAG.getNode(Opc, DL, MVT::i64, Op0, 6802 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6803 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6804 return; 6805 } 6806 // If the FP type needs to be softened, emit a library call using the 'si' 6807 // version. If we left it to default legalization we'd end up with 'di'. If 6808 // the FP type doesn't need to be softened just let generic type 6809 // legalization promote the result type. 6810 RTLIB::Libcall LC; 6811 if (IsSigned) 6812 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6813 else 6814 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6815 MakeLibCallOptions CallOptions; 6816 EVT OpVT = Op0.getValueType(); 6817 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6818 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6819 SDValue Result; 6820 std::tie(Result, Chain) = 6821 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6822 Results.push_back(Result); 6823 if (IsStrict) 6824 Results.push_back(Chain); 6825 break; 6826 } 6827 case ISD::READCYCLECOUNTER: { 6828 assert(!Subtarget.is64Bit() && 6829 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6830 6831 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6832 SDValue RCW = 6833 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6834 6835 Results.push_back( 6836 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6837 Results.push_back(RCW.getValue(2)); 6838 break; 6839 } 6840 case ISD::MUL: { 6841 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6842 unsigned XLen = Subtarget.getXLen(); 6843 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6844 if (Size > XLen) { 6845 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6846 SDValue LHS = N->getOperand(0); 6847 SDValue RHS = N->getOperand(1); 6848 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6849 6850 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6851 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6852 // We need exactly one side to be unsigned. 6853 if (LHSIsU == RHSIsU) 6854 return; 6855 6856 auto MakeMULPair = [&](SDValue S, SDValue U) { 6857 MVT XLenVT = Subtarget.getXLenVT(); 6858 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6859 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6860 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6861 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6862 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6863 }; 6864 6865 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6866 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6867 6868 // The other operand should be signed, but still prefer MULH when 6869 // possible. 6870 if (RHSIsU && LHSIsS && !RHSIsS) 6871 Results.push_back(MakeMULPair(LHS, RHS)); 6872 else if (LHSIsU && RHSIsS && !LHSIsS) 6873 Results.push_back(MakeMULPair(RHS, LHS)); 6874 6875 return; 6876 } 6877 LLVM_FALLTHROUGH; 6878 } 6879 case ISD::ADD: 6880 case ISD::SUB: 6881 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6882 "Unexpected custom legalisation"); 6883 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6884 break; 6885 case ISD::SHL: 6886 case ISD::SRA: 6887 case ISD::SRL: 6888 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6889 "Unexpected custom legalisation"); 6890 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6891 Results.push_back(customLegalizeToWOp(N, DAG)); 6892 break; 6893 } 6894 6895 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6896 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6897 // shift amount. 6898 if (N->getOpcode() == ISD::SHL) { 6899 SDLoc DL(N); 6900 SDValue NewOp0 = 6901 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6902 SDValue NewOp1 = 6903 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6904 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6905 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6906 DAG.getValueType(MVT::i32)); 6907 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6908 } 6909 6910 break; 6911 case ISD::ROTL: 6912 case ISD::ROTR: 6913 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6914 "Unexpected custom legalisation"); 6915 Results.push_back(customLegalizeToWOp(N, DAG)); 6916 break; 6917 case ISD::CTTZ: 6918 case ISD::CTTZ_ZERO_UNDEF: 6919 case ISD::CTLZ: 6920 case ISD::CTLZ_ZERO_UNDEF: { 6921 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6922 "Unexpected custom legalisation"); 6923 6924 SDValue NewOp0 = 6925 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6926 bool IsCTZ = 6927 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6928 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6929 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6930 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6931 return; 6932 } 6933 case ISD::SDIV: 6934 case ISD::UDIV: 6935 case ISD::UREM: { 6936 MVT VT = N->getSimpleValueType(0); 6937 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6938 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6939 "Unexpected custom legalisation"); 6940 // Don't promote division/remainder by constant since we should expand those 6941 // to multiply by magic constant. 6942 // FIXME: What if the expansion is disabled for minsize. 6943 if (N->getOperand(1).getOpcode() == ISD::Constant) 6944 return; 6945 6946 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6947 // the upper 32 bits. For other types we need to sign or zero extend 6948 // based on the opcode. 6949 unsigned ExtOpc = ISD::ANY_EXTEND; 6950 if (VT != MVT::i32) 6951 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6952 : ISD::ZERO_EXTEND; 6953 6954 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6955 break; 6956 } 6957 case ISD::UADDO: 6958 case ISD::USUBO: { 6959 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6960 "Unexpected custom legalisation"); 6961 bool IsAdd = N->getOpcode() == ISD::UADDO; 6962 // Create an ADDW or SUBW. 6963 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6964 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6965 SDValue Res = 6966 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6967 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6968 DAG.getValueType(MVT::i32)); 6969 6970 SDValue Overflow; 6971 if (IsAdd && isOneConstant(RHS)) { 6972 // Special case uaddo X, 1 overflowed if the addition result is 0. 6973 // FIXME: We can do this for any constant RHS by using (X + C) < C. 6974 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6975 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6976 } else { 6977 // Sign extend the LHS and perform an unsigned compare with the ADDW 6978 // result. Since the inputs are sign extended from i32, this is equivalent 6979 // to comparing the lower 32 bits. 6980 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6981 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6982 IsAdd ? ISD::SETULT : ISD::SETUGT); 6983 } 6984 6985 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6986 Results.push_back(Overflow); 6987 return; 6988 } 6989 case ISD::UADDSAT: 6990 case ISD::USUBSAT: { 6991 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6992 "Unexpected custom legalisation"); 6993 if (Subtarget.hasStdExtZbb()) { 6994 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6995 // sign extend allows overflow of the lower 32 bits to be detected on 6996 // the promoted size. 6997 SDValue LHS = 6998 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6999 SDValue RHS = 7000 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7001 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7002 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7003 return; 7004 } 7005 7006 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7007 // promotion for UADDO/USUBO. 7008 Results.push_back(expandAddSubSat(N, DAG)); 7009 return; 7010 } 7011 case ISD::ABS: { 7012 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7013 "Unexpected custom legalisation"); 7014 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7015 7016 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7017 7018 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7019 7020 // Freeze the source so we can increase it's use count. 7021 Src = DAG.getFreeze(Src); 7022 7023 // Copy sign bit to all bits using the sraiw pattern. 7024 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7025 DAG.getValueType(MVT::i32)); 7026 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7027 DAG.getConstant(31, DL, MVT::i64)); 7028 7029 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7030 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7031 7032 // NOTE: The result is only required to be anyextended, but sext is 7033 // consistent with type legalization of sub. 7034 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7035 DAG.getValueType(MVT::i32)); 7036 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7037 return; 7038 } 7039 case ISD::BITCAST: { 7040 EVT VT = N->getValueType(0); 7041 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7042 SDValue Op0 = N->getOperand(0); 7043 EVT Op0VT = Op0.getValueType(); 7044 MVT XLenVT = Subtarget.getXLenVT(); 7045 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7046 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7047 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7048 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7049 Subtarget.hasStdExtF()) { 7050 SDValue FPConv = 7051 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7052 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7053 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7054 isTypeLegal(Op0VT)) { 7055 // Custom-legalize bitcasts from fixed-length vector types to illegal 7056 // scalar types in order to improve codegen. Bitcast the vector to a 7057 // one-element vector type whose element type is the same as the result 7058 // type, and extract the first element. 7059 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7060 if (isTypeLegal(BVT)) { 7061 SDValue BVec = DAG.getBitcast(BVT, Op0); 7062 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7063 DAG.getConstant(0, DL, XLenVT))); 7064 } 7065 } 7066 break; 7067 } 7068 case RISCVISD::GREV: 7069 case RISCVISD::GORC: 7070 case RISCVISD::SHFL: { 7071 MVT VT = N->getSimpleValueType(0); 7072 MVT XLenVT = Subtarget.getXLenVT(); 7073 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7074 "Unexpected custom legalisation"); 7075 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7076 assert((Subtarget.hasStdExtZbp() || 7077 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7078 N->getConstantOperandVal(1) == 7)) && 7079 "Unexpected extension"); 7080 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7081 SDValue NewOp1 = 7082 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7083 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7084 // ReplaceNodeResults requires we maintain the same type for the return 7085 // value. 7086 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7087 break; 7088 } 7089 case ISD::BSWAP: 7090 case ISD::BITREVERSE: { 7091 MVT VT = N->getSimpleValueType(0); 7092 MVT XLenVT = Subtarget.getXLenVT(); 7093 assert((VT == MVT::i8 || VT == MVT::i16 || 7094 (VT == MVT::i32 && Subtarget.is64Bit())) && 7095 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7096 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7097 unsigned Imm = VT.getSizeInBits() - 1; 7098 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7099 if (N->getOpcode() == ISD::BSWAP) 7100 Imm &= ~0x7U; 7101 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7102 DAG.getConstant(Imm, DL, XLenVT)); 7103 // ReplaceNodeResults requires we maintain the same type for the return 7104 // value. 7105 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7106 break; 7107 } 7108 case ISD::FSHL: 7109 case ISD::FSHR: { 7110 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7111 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7112 SDValue NewOp0 = 7113 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7114 SDValue NewOp1 = 7115 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7116 SDValue NewShAmt = 7117 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7118 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7119 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7120 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7121 DAG.getConstant(0x1f, DL, MVT::i64)); 7122 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7123 // instruction use different orders. fshl will return its first operand for 7124 // shift of zero, fshr will return its second operand. fsl and fsr both 7125 // return rs1 so the ISD nodes need to have different operand orders. 7126 // Shift amount is in rs2. 7127 unsigned Opc = RISCVISD::FSLW; 7128 if (N->getOpcode() == ISD::FSHR) { 7129 std::swap(NewOp0, NewOp1); 7130 Opc = RISCVISD::FSRW; 7131 } 7132 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7133 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7134 break; 7135 } 7136 case ISD::EXTRACT_VECTOR_ELT: { 7137 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7138 // type is illegal (currently only vXi64 RV32). 7139 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7140 // transferred to the destination register. We issue two of these from the 7141 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7142 // first element. 7143 SDValue Vec = N->getOperand(0); 7144 SDValue Idx = N->getOperand(1); 7145 7146 // The vector type hasn't been legalized yet so we can't issue target 7147 // specific nodes if it needs legalization. 7148 // FIXME: We would manually legalize if it's important. 7149 if (!isTypeLegal(Vec.getValueType())) 7150 return; 7151 7152 MVT VecVT = Vec.getSimpleValueType(); 7153 7154 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7155 VecVT.getVectorElementType() == MVT::i64 && 7156 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7157 7158 // If this is a fixed vector, we need to convert it to a scalable vector. 7159 MVT ContainerVT = VecVT; 7160 if (VecVT.isFixedLengthVector()) { 7161 ContainerVT = getContainerForFixedLengthVector(VecVT); 7162 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7163 } 7164 7165 MVT XLenVT = Subtarget.getXLenVT(); 7166 7167 // Use a VL of 1 to avoid processing more elements than we need. 7168 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 7169 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7170 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7171 7172 // Unless the index is known to be 0, we must slide the vector down to get 7173 // the desired element into index 0. 7174 if (!isNullConstant(Idx)) { 7175 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7176 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7177 } 7178 7179 // Extract the lower XLEN bits of the correct vector element. 7180 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7181 7182 // To extract the upper XLEN bits of the vector element, shift the first 7183 // element right by 32 bits and re-extract the lower XLEN bits. 7184 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7185 DAG.getUNDEF(ContainerVT), 7186 DAG.getConstant(32, DL, XLenVT), VL); 7187 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7188 ThirtyTwoV, Mask, VL); 7189 7190 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7191 7192 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7193 break; 7194 } 7195 case ISD::INTRINSIC_WO_CHAIN: { 7196 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7197 switch (IntNo) { 7198 default: 7199 llvm_unreachable( 7200 "Don't know how to custom type legalize this intrinsic!"); 7201 case Intrinsic::riscv_grev: 7202 case Intrinsic::riscv_gorc: { 7203 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7204 "Unexpected custom legalisation"); 7205 SDValue NewOp1 = 7206 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7207 SDValue NewOp2 = 7208 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7209 unsigned Opc = 7210 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7211 // If the control is a constant, promote the node by clearing any extra 7212 // bits bits in the control. isel will form greviw/gorciw if the result is 7213 // sign extended. 7214 if (isa<ConstantSDNode>(NewOp2)) { 7215 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7216 DAG.getConstant(0x1f, DL, MVT::i64)); 7217 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7218 } 7219 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7220 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7221 break; 7222 } 7223 case Intrinsic::riscv_bcompress: 7224 case Intrinsic::riscv_bdecompress: 7225 case Intrinsic::riscv_bfp: 7226 case Intrinsic::riscv_fsl: 7227 case Intrinsic::riscv_fsr: { 7228 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7229 "Unexpected custom legalisation"); 7230 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7231 break; 7232 } 7233 case Intrinsic::riscv_orc_b: { 7234 // Lower to the GORCI encoding for orc.b with the operand extended. 7235 SDValue NewOp = 7236 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7237 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7238 DAG.getConstant(7, DL, MVT::i64)); 7239 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7240 return; 7241 } 7242 case Intrinsic::riscv_shfl: 7243 case Intrinsic::riscv_unshfl: { 7244 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7245 "Unexpected custom legalisation"); 7246 SDValue NewOp1 = 7247 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7248 SDValue NewOp2 = 7249 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7250 unsigned Opc = 7251 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7252 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7253 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7254 // will be shuffled the same way as the lower 32 bit half, but the two 7255 // halves won't cross. 7256 if (isa<ConstantSDNode>(NewOp2)) { 7257 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7258 DAG.getConstant(0xf, DL, MVT::i64)); 7259 Opc = 7260 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7261 } 7262 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7263 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7264 break; 7265 } 7266 case Intrinsic::riscv_vmv_x_s: { 7267 EVT VT = N->getValueType(0); 7268 MVT XLenVT = Subtarget.getXLenVT(); 7269 if (VT.bitsLT(XLenVT)) { 7270 // Simple case just extract using vmv.x.s and truncate. 7271 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7272 Subtarget.getXLenVT(), N->getOperand(1)); 7273 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7274 return; 7275 } 7276 7277 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7278 "Unexpected custom legalization"); 7279 7280 // We need to do the move in two steps. 7281 SDValue Vec = N->getOperand(1); 7282 MVT VecVT = Vec.getSimpleValueType(); 7283 7284 // First extract the lower XLEN bits of the element. 7285 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7286 7287 // To extract the upper XLEN bits of the vector element, shift the first 7288 // element right by 32 bits and re-extract the lower XLEN bits. 7289 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7290 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7291 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 7292 SDValue ThirtyTwoV = 7293 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7294 DAG.getConstant(32, DL, XLenVT), VL); 7295 SDValue LShr32 = 7296 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7297 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7298 7299 Results.push_back( 7300 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7301 break; 7302 } 7303 } 7304 break; 7305 } 7306 case ISD::VECREDUCE_ADD: 7307 case ISD::VECREDUCE_AND: 7308 case ISD::VECREDUCE_OR: 7309 case ISD::VECREDUCE_XOR: 7310 case ISD::VECREDUCE_SMAX: 7311 case ISD::VECREDUCE_UMAX: 7312 case ISD::VECREDUCE_SMIN: 7313 case ISD::VECREDUCE_UMIN: 7314 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7315 Results.push_back(V); 7316 break; 7317 case ISD::VP_REDUCE_ADD: 7318 case ISD::VP_REDUCE_AND: 7319 case ISD::VP_REDUCE_OR: 7320 case ISD::VP_REDUCE_XOR: 7321 case ISD::VP_REDUCE_SMAX: 7322 case ISD::VP_REDUCE_UMAX: 7323 case ISD::VP_REDUCE_SMIN: 7324 case ISD::VP_REDUCE_UMIN: 7325 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7326 Results.push_back(V); 7327 break; 7328 case ISD::FLT_ROUNDS_: { 7329 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7330 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7331 Results.push_back(Res.getValue(0)); 7332 Results.push_back(Res.getValue(1)); 7333 break; 7334 } 7335 } 7336 } 7337 7338 // A structure to hold one of the bit-manipulation patterns below. Together, a 7339 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7340 // (or (and (shl x, 1), 0xAAAAAAAA), 7341 // (and (srl x, 1), 0x55555555)) 7342 struct RISCVBitmanipPat { 7343 SDValue Op; 7344 unsigned ShAmt; 7345 bool IsSHL; 7346 7347 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7348 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7349 } 7350 }; 7351 7352 // Matches patterns of the form 7353 // (and (shl x, C2), (C1 << C2)) 7354 // (and (srl x, C2), C1) 7355 // (shl (and x, C1), C2) 7356 // (srl (and x, (C1 << C2)), C2) 7357 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7358 // The expected masks for each shift amount are specified in BitmanipMasks where 7359 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7360 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7361 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7362 // XLen is 64. 7363 static Optional<RISCVBitmanipPat> 7364 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7365 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7366 "Unexpected number of masks"); 7367 Optional<uint64_t> Mask; 7368 // Optionally consume a mask around the shift operation. 7369 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7370 Mask = Op.getConstantOperandVal(1); 7371 Op = Op.getOperand(0); 7372 } 7373 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7374 return None; 7375 bool IsSHL = Op.getOpcode() == ISD::SHL; 7376 7377 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7378 return None; 7379 uint64_t ShAmt = Op.getConstantOperandVal(1); 7380 7381 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7382 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7383 return None; 7384 // If we don't have enough masks for 64 bit, then we must be trying to 7385 // match SHFL so we're only allowed to shift 1/4 of the width. 7386 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7387 return None; 7388 7389 SDValue Src = Op.getOperand(0); 7390 7391 // The expected mask is shifted left when the AND is found around SHL 7392 // patterns. 7393 // ((x >> 1) & 0x55555555) 7394 // ((x << 1) & 0xAAAAAAAA) 7395 bool SHLExpMask = IsSHL; 7396 7397 if (!Mask) { 7398 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7399 // the mask is all ones: consume that now. 7400 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7401 Mask = Src.getConstantOperandVal(1); 7402 Src = Src.getOperand(0); 7403 // The expected mask is now in fact shifted left for SRL, so reverse the 7404 // decision. 7405 // ((x & 0xAAAAAAAA) >> 1) 7406 // ((x & 0x55555555) << 1) 7407 SHLExpMask = !SHLExpMask; 7408 } else { 7409 // Use a default shifted mask of all-ones if there's no AND, truncated 7410 // down to the expected width. This simplifies the logic later on. 7411 Mask = maskTrailingOnes<uint64_t>(Width); 7412 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7413 } 7414 } 7415 7416 unsigned MaskIdx = Log2_32(ShAmt); 7417 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7418 7419 if (SHLExpMask) 7420 ExpMask <<= ShAmt; 7421 7422 if (Mask != ExpMask) 7423 return None; 7424 7425 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7426 } 7427 7428 // Matches any of the following bit-manipulation patterns: 7429 // (and (shl x, 1), (0x55555555 << 1)) 7430 // (and (srl x, 1), 0x55555555) 7431 // (shl (and x, 0x55555555), 1) 7432 // (srl (and x, (0x55555555 << 1)), 1) 7433 // where the shift amount and mask may vary thus: 7434 // [1] = 0x55555555 / 0xAAAAAAAA 7435 // [2] = 0x33333333 / 0xCCCCCCCC 7436 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7437 // [8] = 0x00FF00FF / 0xFF00FF00 7438 // [16] = 0x0000FFFF / 0xFFFFFFFF 7439 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7440 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7441 // These are the unshifted masks which we use to match bit-manipulation 7442 // patterns. They may be shifted left in certain circumstances. 7443 static const uint64_t BitmanipMasks[] = { 7444 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7445 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7446 7447 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7448 } 7449 7450 // Match the following pattern as a GREVI(W) operation 7451 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7452 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7453 const RISCVSubtarget &Subtarget) { 7454 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7455 EVT VT = Op.getValueType(); 7456 7457 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7458 auto LHS = matchGREVIPat(Op.getOperand(0)); 7459 auto RHS = matchGREVIPat(Op.getOperand(1)); 7460 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7461 SDLoc DL(Op); 7462 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7463 DAG.getConstant(LHS->ShAmt, DL, VT)); 7464 } 7465 } 7466 return SDValue(); 7467 } 7468 7469 // Matches any the following pattern as a GORCI(W) operation 7470 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7471 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7472 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7473 // Note that with the variant of 3., 7474 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7475 // the inner pattern will first be matched as GREVI and then the outer 7476 // pattern will be matched to GORC via the first rule above. 7477 // 4. (or (rotl/rotr x, bitwidth/2), x) 7478 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7479 const RISCVSubtarget &Subtarget) { 7480 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7481 EVT VT = Op.getValueType(); 7482 7483 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7484 SDLoc DL(Op); 7485 SDValue Op0 = Op.getOperand(0); 7486 SDValue Op1 = Op.getOperand(1); 7487 7488 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7489 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7490 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7491 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7492 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7493 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7494 if ((Reverse.getOpcode() == ISD::ROTL || 7495 Reverse.getOpcode() == ISD::ROTR) && 7496 Reverse.getOperand(0) == X && 7497 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7498 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7499 if (RotAmt == (VT.getSizeInBits() / 2)) 7500 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7501 DAG.getConstant(RotAmt, DL, VT)); 7502 } 7503 return SDValue(); 7504 }; 7505 7506 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7507 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7508 return V; 7509 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7510 return V; 7511 7512 // OR is commutable so canonicalize its OR operand to the left 7513 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7514 std::swap(Op0, Op1); 7515 if (Op0.getOpcode() != ISD::OR) 7516 return SDValue(); 7517 SDValue OrOp0 = Op0.getOperand(0); 7518 SDValue OrOp1 = Op0.getOperand(1); 7519 auto LHS = matchGREVIPat(OrOp0); 7520 // OR is commutable so swap the operands and try again: x might have been 7521 // on the left 7522 if (!LHS) { 7523 std::swap(OrOp0, OrOp1); 7524 LHS = matchGREVIPat(OrOp0); 7525 } 7526 auto RHS = matchGREVIPat(Op1); 7527 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7528 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7529 DAG.getConstant(LHS->ShAmt, DL, VT)); 7530 } 7531 } 7532 return SDValue(); 7533 } 7534 7535 // Matches any of the following bit-manipulation patterns: 7536 // (and (shl x, 1), (0x22222222 << 1)) 7537 // (and (srl x, 1), 0x22222222) 7538 // (shl (and x, 0x22222222), 1) 7539 // (srl (and x, (0x22222222 << 1)), 1) 7540 // where the shift amount and mask may vary thus: 7541 // [1] = 0x22222222 / 0x44444444 7542 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7543 // [4] = 0x00F000F0 / 0x0F000F00 7544 // [8] = 0x0000FF00 / 0x00FF0000 7545 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7546 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7547 // These are the unshifted masks which we use to match bit-manipulation 7548 // patterns. They may be shifted left in certain circumstances. 7549 static const uint64_t BitmanipMasks[] = { 7550 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7551 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7552 7553 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7554 } 7555 7556 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7557 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7558 const RISCVSubtarget &Subtarget) { 7559 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7560 EVT VT = Op.getValueType(); 7561 7562 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7563 return SDValue(); 7564 7565 SDValue Op0 = Op.getOperand(0); 7566 SDValue Op1 = Op.getOperand(1); 7567 7568 // Or is commutable so canonicalize the second OR to the LHS. 7569 if (Op0.getOpcode() != ISD::OR) 7570 std::swap(Op0, Op1); 7571 if (Op0.getOpcode() != ISD::OR) 7572 return SDValue(); 7573 7574 // We found an inner OR, so our operands are the operands of the inner OR 7575 // and the other operand of the outer OR. 7576 SDValue A = Op0.getOperand(0); 7577 SDValue B = Op0.getOperand(1); 7578 SDValue C = Op1; 7579 7580 auto Match1 = matchSHFLPat(A); 7581 auto Match2 = matchSHFLPat(B); 7582 7583 // If neither matched, we failed. 7584 if (!Match1 && !Match2) 7585 return SDValue(); 7586 7587 // We had at least one match. if one failed, try the remaining C operand. 7588 if (!Match1) { 7589 std::swap(A, C); 7590 Match1 = matchSHFLPat(A); 7591 if (!Match1) 7592 return SDValue(); 7593 } else if (!Match2) { 7594 std::swap(B, C); 7595 Match2 = matchSHFLPat(B); 7596 if (!Match2) 7597 return SDValue(); 7598 } 7599 assert(Match1 && Match2); 7600 7601 // Make sure our matches pair up. 7602 if (!Match1->formsPairWith(*Match2)) 7603 return SDValue(); 7604 7605 // All the remains is to make sure C is an AND with the same input, that masks 7606 // out the bits that are being shuffled. 7607 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7608 C.getOperand(0) != Match1->Op) 7609 return SDValue(); 7610 7611 uint64_t Mask = C.getConstantOperandVal(1); 7612 7613 static const uint64_t BitmanipMasks[] = { 7614 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7615 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7616 }; 7617 7618 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7619 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7620 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7621 7622 if (Mask != ExpMask) 7623 return SDValue(); 7624 7625 SDLoc DL(Op); 7626 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7627 DAG.getConstant(Match1->ShAmt, DL, VT)); 7628 } 7629 7630 // Optimize (add (shl x, c0), (shl y, c1)) -> 7631 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7632 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7633 const RISCVSubtarget &Subtarget) { 7634 // Perform this optimization only in the zba extension. 7635 if (!Subtarget.hasStdExtZba()) 7636 return SDValue(); 7637 7638 // Skip for vector types and larger types. 7639 EVT VT = N->getValueType(0); 7640 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7641 return SDValue(); 7642 7643 // The two operand nodes must be SHL and have no other use. 7644 SDValue N0 = N->getOperand(0); 7645 SDValue N1 = N->getOperand(1); 7646 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7647 !N0->hasOneUse() || !N1->hasOneUse()) 7648 return SDValue(); 7649 7650 // Check c0 and c1. 7651 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7652 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7653 if (!N0C || !N1C) 7654 return SDValue(); 7655 int64_t C0 = N0C->getSExtValue(); 7656 int64_t C1 = N1C->getSExtValue(); 7657 if (C0 <= 0 || C1 <= 0) 7658 return SDValue(); 7659 7660 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7661 int64_t Bits = std::min(C0, C1); 7662 int64_t Diff = std::abs(C0 - C1); 7663 if (Diff != 1 && Diff != 2 && Diff != 3) 7664 return SDValue(); 7665 7666 // Build nodes. 7667 SDLoc DL(N); 7668 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7669 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7670 SDValue NA0 = 7671 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7672 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7673 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7674 } 7675 7676 // Combine 7677 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7678 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7679 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7680 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7681 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7682 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7683 // The grev patterns represents BSWAP. 7684 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7685 // off the grev. 7686 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7687 const RISCVSubtarget &Subtarget) { 7688 bool IsWInstruction = 7689 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7690 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7691 IsWInstruction) && 7692 "Unexpected opcode!"); 7693 SDValue Src = N->getOperand(0); 7694 EVT VT = N->getValueType(0); 7695 SDLoc DL(N); 7696 7697 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7698 return SDValue(); 7699 7700 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7701 !isa<ConstantSDNode>(Src.getOperand(1))) 7702 return SDValue(); 7703 7704 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7705 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7706 7707 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7708 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7709 unsigned ShAmt1 = N->getConstantOperandVal(1); 7710 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7711 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7712 return SDValue(); 7713 7714 Src = Src.getOperand(0); 7715 7716 // Toggle bit the MSB of the shift. 7717 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7718 if (CombinedShAmt == 0) 7719 return Src; 7720 7721 SDValue Res = DAG.getNode( 7722 RISCVISD::GREV, DL, VT, Src, 7723 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7724 if (!IsWInstruction) 7725 return Res; 7726 7727 // Sign extend the result to match the behavior of the rotate. This will be 7728 // selected to GREVIW in isel. 7729 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7730 DAG.getValueType(MVT::i32)); 7731 } 7732 7733 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7734 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7735 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7736 // not undo itself, but they are redundant. 7737 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7738 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7739 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7740 SDValue Src = N->getOperand(0); 7741 7742 if (Src.getOpcode() != N->getOpcode()) 7743 return SDValue(); 7744 7745 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7746 !isa<ConstantSDNode>(Src.getOperand(1))) 7747 return SDValue(); 7748 7749 unsigned ShAmt1 = N->getConstantOperandVal(1); 7750 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7751 Src = Src.getOperand(0); 7752 7753 unsigned CombinedShAmt; 7754 if (IsGORC) 7755 CombinedShAmt = ShAmt1 | ShAmt2; 7756 else 7757 CombinedShAmt = ShAmt1 ^ ShAmt2; 7758 7759 if (CombinedShAmt == 0) 7760 return Src; 7761 7762 SDLoc DL(N); 7763 return DAG.getNode( 7764 N->getOpcode(), DL, N->getValueType(0), Src, 7765 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7766 } 7767 7768 // Combine a constant select operand into its use: 7769 // 7770 // (and (select cond, -1, c), x) 7771 // -> (select cond, x, (and x, c)) [AllOnes=1] 7772 // (or (select cond, 0, c), x) 7773 // -> (select cond, x, (or x, c)) [AllOnes=0] 7774 // (xor (select cond, 0, c), x) 7775 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7776 // (add (select cond, 0, c), x) 7777 // -> (select cond, x, (add x, c)) [AllOnes=0] 7778 // (sub x, (select cond, 0, c)) 7779 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7780 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7781 SelectionDAG &DAG, bool AllOnes) { 7782 EVT VT = N->getValueType(0); 7783 7784 // Skip vectors. 7785 if (VT.isVector()) 7786 return SDValue(); 7787 7788 if ((Slct.getOpcode() != ISD::SELECT && 7789 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7790 !Slct.hasOneUse()) 7791 return SDValue(); 7792 7793 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7794 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7795 }; 7796 7797 bool SwapSelectOps; 7798 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7799 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7800 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7801 SDValue NonConstantVal; 7802 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7803 SwapSelectOps = false; 7804 NonConstantVal = FalseVal; 7805 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7806 SwapSelectOps = true; 7807 NonConstantVal = TrueVal; 7808 } else 7809 return SDValue(); 7810 7811 // Slct is now know to be the desired identity constant when CC is true. 7812 TrueVal = OtherOp; 7813 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7814 // Unless SwapSelectOps says the condition should be false. 7815 if (SwapSelectOps) 7816 std::swap(TrueVal, FalseVal); 7817 7818 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7819 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7820 {Slct.getOperand(0), Slct.getOperand(1), 7821 Slct.getOperand(2), TrueVal, FalseVal}); 7822 7823 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7824 {Slct.getOperand(0), TrueVal, FalseVal}); 7825 } 7826 7827 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7828 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7829 bool AllOnes) { 7830 SDValue N0 = N->getOperand(0); 7831 SDValue N1 = N->getOperand(1); 7832 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7833 return Result; 7834 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7835 return Result; 7836 return SDValue(); 7837 } 7838 7839 // Transform (add (mul x, c0), c1) -> 7840 // (add (mul (add x, c1/c0), c0), c1%c0). 7841 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7842 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7843 // to an infinite loop in DAGCombine if transformed. 7844 // Or transform (add (mul x, c0), c1) -> 7845 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7846 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7847 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7848 // lead to an infinite loop in DAGCombine if transformed. 7849 // Or transform (add (mul x, c0), c1) -> 7850 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7851 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7852 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7853 // lead to an infinite loop in DAGCombine if transformed. 7854 // Or transform (add (mul x, c0), c1) -> 7855 // (mul (add x, c1/c0), c0). 7856 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7857 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7858 const RISCVSubtarget &Subtarget) { 7859 // Skip for vector types and larger types. 7860 EVT VT = N->getValueType(0); 7861 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7862 return SDValue(); 7863 // The first operand node must be a MUL and has no other use. 7864 SDValue N0 = N->getOperand(0); 7865 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7866 return SDValue(); 7867 // Check if c0 and c1 match above conditions. 7868 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7869 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7870 if (!N0C || !N1C) 7871 return SDValue(); 7872 // If N0C has multiple uses it's possible one of the cases in 7873 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7874 // in an infinite loop. 7875 if (!N0C->hasOneUse()) 7876 return SDValue(); 7877 int64_t C0 = N0C->getSExtValue(); 7878 int64_t C1 = N1C->getSExtValue(); 7879 int64_t CA, CB; 7880 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7881 return SDValue(); 7882 // Search for proper CA (non-zero) and CB that both are simm12. 7883 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7884 !isInt<12>(C0 * (C1 / C0))) { 7885 CA = C1 / C0; 7886 CB = C1 % C0; 7887 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7888 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7889 CA = C1 / C0 + 1; 7890 CB = C1 % C0 - C0; 7891 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7892 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7893 CA = C1 / C0 - 1; 7894 CB = C1 % C0 + C0; 7895 } else 7896 return SDValue(); 7897 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7898 SDLoc DL(N); 7899 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7900 DAG.getConstant(CA, DL, VT)); 7901 SDValue New1 = 7902 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7903 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7904 } 7905 7906 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7907 const RISCVSubtarget &Subtarget) { 7908 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7909 return V; 7910 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7911 return V; 7912 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7913 // (select lhs, rhs, cc, x, (add x, y)) 7914 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7915 } 7916 7917 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7918 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7919 // (select lhs, rhs, cc, x, (sub x, y)) 7920 SDValue N0 = N->getOperand(0); 7921 SDValue N1 = N->getOperand(1); 7922 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7923 } 7924 7925 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7926 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7927 // (select lhs, rhs, cc, x, (and x, y)) 7928 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7929 } 7930 7931 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7932 const RISCVSubtarget &Subtarget) { 7933 if (Subtarget.hasStdExtZbp()) { 7934 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7935 return GREV; 7936 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7937 return GORC; 7938 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7939 return SHFL; 7940 } 7941 7942 // fold (or (select cond, 0, y), x) -> 7943 // (select cond, x, (or x, y)) 7944 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7945 } 7946 7947 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7948 SDValue N0 = N->getOperand(0); 7949 SDValue N1 = N->getOperand(1); 7950 7951 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 7952 // NOTE: Assumes ROL being legal means ROLW is legal. 7953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7954 if (N0.getOpcode() == RISCVISD::SLLW && 7955 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 7956 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 7957 SDLoc DL(N); 7958 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 7959 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 7960 } 7961 7962 // fold (xor (select cond, 0, y), x) -> 7963 // (select cond, x, (xor x, y)) 7964 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7965 } 7966 7967 static SDValue 7968 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7969 const RISCVSubtarget &Subtarget) { 7970 SDValue Src = N->getOperand(0); 7971 EVT VT = N->getValueType(0); 7972 7973 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7974 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7975 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7976 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7977 Src.getOperand(0)); 7978 7979 // Fold (i64 (sext_inreg (abs X), i32)) -> 7980 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7981 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7982 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7983 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7984 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7985 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7986 // may get combined into an earlier operation so we need to use 7987 // ComputeNumSignBits. 7988 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7989 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7990 // we can't assume that X has 33 sign bits. We must check. 7991 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7992 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7993 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7994 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7995 SDLoc DL(N); 7996 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7997 SDValue Neg = 7998 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7999 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8000 DAG.getValueType(MVT::i32)); 8001 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8002 } 8003 8004 return SDValue(); 8005 } 8006 8007 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8008 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8009 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8010 bool Commute = false) { 8011 assert((N->getOpcode() == RISCVISD::ADD_VL || 8012 N->getOpcode() == RISCVISD::SUB_VL) && 8013 "Unexpected opcode"); 8014 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8015 SDValue Op0 = N->getOperand(0); 8016 SDValue Op1 = N->getOperand(1); 8017 if (Commute) 8018 std::swap(Op0, Op1); 8019 8020 MVT VT = N->getSimpleValueType(0); 8021 8022 // Determine the narrow size for a widening add/sub. 8023 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8024 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8025 VT.getVectorElementCount()); 8026 8027 SDValue Mask = N->getOperand(2); 8028 SDValue VL = N->getOperand(3); 8029 8030 SDLoc DL(N); 8031 8032 // If the RHS is a sext or zext, we can form a widening op. 8033 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8034 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8035 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8036 unsigned ExtOpc = Op1.getOpcode(); 8037 Op1 = Op1.getOperand(0); 8038 // Re-introduce narrower extends if needed. 8039 if (Op1.getValueType() != NarrowVT) 8040 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8041 8042 unsigned WOpc; 8043 if (ExtOpc == RISCVISD::VSEXT_VL) 8044 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8045 else 8046 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8047 8048 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8049 } 8050 8051 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8052 // sext/zext? 8053 8054 return SDValue(); 8055 } 8056 8057 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8058 // vwsub(u).vv/vx. 8059 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8060 SDValue Op0 = N->getOperand(0); 8061 SDValue Op1 = N->getOperand(1); 8062 SDValue Mask = N->getOperand(2); 8063 SDValue VL = N->getOperand(3); 8064 8065 MVT VT = N->getSimpleValueType(0); 8066 MVT NarrowVT = Op1.getSimpleValueType(); 8067 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8068 8069 unsigned VOpc; 8070 switch (N->getOpcode()) { 8071 default: llvm_unreachable("Unexpected opcode"); 8072 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8073 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8074 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8075 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8076 } 8077 8078 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8079 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8080 8081 SDLoc DL(N); 8082 8083 // If the LHS is a sext or zext, we can narrow this op to the same size as 8084 // the RHS. 8085 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8086 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8087 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8088 unsigned ExtOpc = Op0.getOpcode(); 8089 Op0 = Op0.getOperand(0); 8090 // Re-introduce narrower extends if needed. 8091 if (Op0.getValueType() != NarrowVT) 8092 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8093 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8094 } 8095 8096 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8097 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8098 8099 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8100 // to commute and use a vwadd(u).vx instead. 8101 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8102 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8103 Op0 = Op0.getOperand(1); 8104 8105 // See if have enough sign bits or zero bits in the scalar to use a 8106 // widening add/sub by splatting to smaller element size. 8107 unsigned EltBits = VT.getScalarSizeInBits(); 8108 unsigned ScalarBits = Op0.getValueSizeInBits(); 8109 // Make sure we're getting all element bits from the scalar register. 8110 // FIXME: Support implicit sign extension of vmv.v.x? 8111 if (ScalarBits < EltBits) 8112 return SDValue(); 8113 8114 if (IsSigned) { 8115 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8116 return SDValue(); 8117 } else { 8118 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8119 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8120 return SDValue(); 8121 } 8122 8123 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8124 DAG.getUNDEF(NarrowVT), Op0, VL); 8125 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8126 } 8127 8128 return SDValue(); 8129 } 8130 8131 // Try to form VWMUL, VWMULU or VWMULSU. 8132 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8133 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8134 bool Commute) { 8135 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8136 SDValue Op0 = N->getOperand(0); 8137 SDValue Op1 = N->getOperand(1); 8138 if (Commute) 8139 std::swap(Op0, Op1); 8140 8141 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8142 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8143 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8144 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8145 return SDValue(); 8146 8147 SDValue Mask = N->getOperand(2); 8148 SDValue VL = N->getOperand(3); 8149 8150 // Make sure the mask and VL match. 8151 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8152 return SDValue(); 8153 8154 MVT VT = N->getSimpleValueType(0); 8155 8156 // Determine the narrow size for a widening multiply. 8157 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8158 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8159 VT.getVectorElementCount()); 8160 8161 SDLoc DL(N); 8162 8163 // See if the other operand is the same opcode. 8164 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8165 if (!Op1.hasOneUse()) 8166 return SDValue(); 8167 8168 // Make sure the mask and VL match. 8169 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8170 return SDValue(); 8171 8172 Op1 = Op1.getOperand(0); 8173 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8174 // The operand is a splat of a scalar. 8175 8176 // The pasthru must be undef for tail agnostic 8177 if (!Op1.getOperand(0).isUndef()) 8178 return SDValue(); 8179 // The VL must be the same. 8180 if (Op1.getOperand(2) != VL) 8181 return SDValue(); 8182 8183 // Get the scalar value. 8184 Op1 = Op1.getOperand(1); 8185 8186 // See if have enough sign bits or zero bits in the scalar to use a 8187 // widening multiply by splatting to smaller element size. 8188 unsigned EltBits = VT.getScalarSizeInBits(); 8189 unsigned ScalarBits = Op1.getValueSizeInBits(); 8190 // Make sure we're getting all element bits from the scalar register. 8191 // FIXME: Support implicit sign extension of vmv.v.x? 8192 if (ScalarBits < EltBits) 8193 return SDValue(); 8194 8195 // If the LHS is a sign extend, try to use vwmul. 8196 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8197 // Can use vwmul. 8198 } else { 8199 // Otherwise try to use vwmulu or vwmulsu. 8200 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8201 if (DAG.MaskedValueIsZero(Op1, Mask)) 8202 IsVWMULSU = IsSignExt; 8203 else 8204 return SDValue(); 8205 } 8206 8207 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8208 DAG.getUNDEF(NarrowVT), Op1, VL); 8209 } else 8210 return SDValue(); 8211 8212 Op0 = Op0.getOperand(0); 8213 8214 // Re-introduce narrower extends if needed. 8215 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8216 if (Op0.getValueType() != NarrowVT) 8217 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8218 // vwmulsu requires second operand to be zero extended. 8219 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8220 if (Op1.getValueType() != NarrowVT) 8221 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8222 8223 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8224 if (!IsVWMULSU) 8225 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8226 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8227 } 8228 8229 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8230 switch (Op.getOpcode()) { 8231 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8232 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8233 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8234 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8235 case ISD::FROUND: return RISCVFPRndMode::RMM; 8236 } 8237 8238 return RISCVFPRndMode::Invalid; 8239 } 8240 8241 // Fold 8242 // (fp_to_int (froundeven X)) -> fcvt X, rne 8243 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8244 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8245 // (fp_to_int (fceil X)) -> fcvt X, rup 8246 // (fp_to_int (fround X)) -> fcvt X, rmm 8247 static SDValue performFP_TO_INTCombine(SDNode *N, 8248 TargetLowering::DAGCombinerInfo &DCI, 8249 const RISCVSubtarget &Subtarget) { 8250 SelectionDAG &DAG = DCI.DAG; 8251 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8252 MVT XLenVT = Subtarget.getXLenVT(); 8253 8254 // Only handle XLen or i32 types. Other types narrower than XLen will 8255 // eventually be legalized to XLenVT. 8256 EVT VT = N->getValueType(0); 8257 if (VT != MVT::i32 && VT != XLenVT) 8258 return SDValue(); 8259 8260 SDValue Src = N->getOperand(0); 8261 8262 // Ensure the FP type is also legal. 8263 if (!TLI.isTypeLegal(Src.getValueType())) 8264 return SDValue(); 8265 8266 // Don't do this for f16 with Zfhmin and not Zfh. 8267 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8268 return SDValue(); 8269 8270 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8271 if (FRM == RISCVFPRndMode::Invalid) 8272 return SDValue(); 8273 8274 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8275 8276 unsigned Opc; 8277 if (VT == XLenVT) 8278 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8279 else 8280 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8281 8282 SDLoc DL(N); 8283 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8284 DAG.getTargetConstant(FRM, DL, XLenVT)); 8285 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8286 } 8287 8288 // Fold 8289 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8290 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8291 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8292 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8293 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8294 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8295 TargetLowering::DAGCombinerInfo &DCI, 8296 const RISCVSubtarget &Subtarget) { 8297 SelectionDAG &DAG = DCI.DAG; 8298 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8299 MVT XLenVT = Subtarget.getXLenVT(); 8300 8301 // Only handle XLen types. Other types narrower than XLen will eventually be 8302 // legalized to XLenVT. 8303 EVT DstVT = N->getValueType(0); 8304 if (DstVT != XLenVT) 8305 return SDValue(); 8306 8307 SDValue Src = N->getOperand(0); 8308 8309 // Ensure the FP type is also legal. 8310 if (!TLI.isTypeLegal(Src.getValueType())) 8311 return SDValue(); 8312 8313 // Don't do this for f16 with Zfhmin and not Zfh. 8314 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8315 return SDValue(); 8316 8317 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8318 8319 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8320 if (FRM == RISCVFPRndMode::Invalid) 8321 return SDValue(); 8322 8323 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8324 8325 unsigned Opc; 8326 if (SatVT == DstVT) 8327 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8328 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8329 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8330 else 8331 return SDValue(); 8332 // FIXME: Support other SatVTs by clamping before or after the conversion. 8333 8334 Src = Src.getOperand(0); 8335 8336 SDLoc DL(N); 8337 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8338 DAG.getTargetConstant(FRM, DL, XLenVT)); 8339 8340 // RISCV FP-to-int conversions saturate to the destination register size, but 8341 // don't produce 0 for nan. 8342 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8343 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8344 } 8345 8346 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8347 // smaller than XLenVT. 8348 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8349 const RISCVSubtarget &Subtarget) { 8350 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8351 8352 SDValue Src = N->getOperand(0); 8353 if (Src.getOpcode() != ISD::BSWAP) 8354 return SDValue(); 8355 8356 EVT VT = N->getValueType(0); 8357 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8358 !isPowerOf2_32(VT.getSizeInBits())) 8359 return SDValue(); 8360 8361 SDLoc DL(N); 8362 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8363 DAG.getConstant(7, DL, VT)); 8364 } 8365 8366 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8367 DAGCombinerInfo &DCI) const { 8368 SelectionDAG &DAG = DCI.DAG; 8369 8370 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8371 // bits are demanded. N will be added to the Worklist if it was not deleted. 8372 // Caller should return SDValue(N, 0) if this returns true. 8373 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8374 SDValue Op = N->getOperand(OpNo); 8375 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8376 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8377 return false; 8378 8379 if (N->getOpcode() != ISD::DELETED_NODE) 8380 DCI.AddToWorklist(N); 8381 return true; 8382 }; 8383 8384 switch (N->getOpcode()) { 8385 default: 8386 break; 8387 case RISCVISD::SplitF64: { 8388 SDValue Op0 = N->getOperand(0); 8389 // If the input to SplitF64 is just BuildPairF64 then the operation is 8390 // redundant. Instead, use BuildPairF64's operands directly. 8391 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8392 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8393 8394 if (Op0->isUndef()) { 8395 SDValue Lo = DAG.getUNDEF(MVT::i32); 8396 SDValue Hi = DAG.getUNDEF(MVT::i32); 8397 return DCI.CombineTo(N, Lo, Hi); 8398 } 8399 8400 SDLoc DL(N); 8401 8402 // It's cheaper to materialise two 32-bit integers than to load a double 8403 // from the constant pool and transfer it to integer registers through the 8404 // stack. 8405 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8406 APInt V = C->getValueAPF().bitcastToAPInt(); 8407 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8408 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8409 return DCI.CombineTo(N, Lo, Hi); 8410 } 8411 8412 // This is a target-specific version of a DAGCombine performed in 8413 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8414 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8415 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8416 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8417 !Op0.getNode()->hasOneUse()) 8418 break; 8419 SDValue NewSplitF64 = 8420 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8421 Op0.getOperand(0)); 8422 SDValue Lo = NewSplitF64.getValue(0); 8423 SDValue Hi = NewSplitF64.getValue(1); 8424 APInt SignBit = APInt::getSignMask(32); 8425 if (Op0.getOpcode() == ISD::FNEG) { 8426 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8427 DAG.getConstant(SignBit, DL, MVT::i32)); 8428 return DCI.CombineTo(N, Lo, NewHi); 8429 } 8430 assert(Op0.getOpcode() == ISD::FABS); 8431 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8432 DAG.getConstant(~SignBit, DL, MVT::i32)); 8433 return DCI.CombineTo(N, Lo, NewHi); 8434 } 8435 case RISCVISD::SLLW: 8436 case RISCVISD::SRAW: 8437 case RISCVISD::SRLW: { 8438 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8439 if (SimplifyDemandedLowBitsHelper(0, 32) || 8440 SimplifyDemandedLowBitsHelper(1, 5)) 8441 return SDValue(N, 0); 8442 8443 break; 8444 } 8445 case ISD::ROTR: 8446 case ISD::ROTL: 8447 case RISCVISD::RORW: 8448 case RISCVISD::ROLW: { 8449 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8450 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8451 if (SimplifyDemandedLowBitsHelper(0, 32) || 8452 SimplifyDemandedLowBitsHelper(1, 5)) 8453 return SDValue(N, 0); 8454 } 8455 8456 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8457 } 8458 case RISCVISD::CLZW: 8459 case RISCVISD::CTZW: { 8460 // Only the lower 32 bits of the first operand are read 8461 if (SimplifyDemandedLowBitsHelper(0, 32)) 8462 return SDValue(N, 0); 8463 break; 8464 } 8465 case RISCVISD::GREV: 8466 case RISCVISD::GORC: { 8467 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8468 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8469 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8470 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8471 return SDValue(N, 0); 8472 8473 return combineGREVI_GORCI(N, DAG); 8474 } 8475 case RISCVISD::GREVW: 8476 case RISCVISD::GORCW: { 8477 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8478 if (SimplifyDemandedLowBitsHelper(0, 32) || 8479 SimplifyDemandedLowBitsHelper(1, 5)) 8480 return SDValue(N, 0); 8481 8482 break; 8483 } 8484 case RISCVISD::SHFL: 8485 case RISCVISD::UNSHFL: { 8486 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8487 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8488 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8489 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8490 return SDValue(N, 0); 8491 8492 break; 8493 } 8494 case RISCVISD::SHFLW: 8495 case RISCVISD::UNSHFLW: { 8496 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8497 if (SimplifyDemandedLowBitsHelper(0, 32) || 8498 SimplifyDemandedLowBitsHelper(1, 4)) 8499 return SDValue(N, 0); 8500 8501 break; 8502 } 8503 case RISCVISD::BCOMPRESSW: 8504 case RISCVISD::BDECOMPRESSW: { 8505 // Only the lower 32 bits of LHS and RHS are read. 8506 if (SimplifyDemandedLowBitsHelper(0, 32) || 8507 SimplifyDemandedLowBitsHelper(1, 32)) 8508 return SDValue(N, 0); 8509 8510 break; 8511 } 8512 case RISCVISD::FSR: 8513 case RISCVISD::FSL: 8514 case RISCVISD::FSRW: 8515 case RISCVISD::FSLW: { 8516 bool IsWInstruction = 8517 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8518 unsigned BitWidth = 8519 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8520 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8521 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8522 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8523 return SDValue(N, 0); 8524 8525 break; 8526 } 8527 case RISCVISD::FMV_X_ANYEXTH: 8528 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8529 SDLoc DL(N); 8530 SDValue Op0 = N->getOperand(0); 8531 MVT VT = N->getSimpleValueType(0); 8532 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8533 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8534 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8535 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8536 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8537 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8538 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8539 assert(Op0.getOperand(0).getValueType() == VT && 8540 "Unexpected value type!"); 8541 return Op0.getOperand(0); 8542 } 8543 8544 // This is a target-specific version of a DAGCombine performed in 8545 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8546 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8547 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8548 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8549 !Op0.getNode()->hasOneUse()) 8550 break; 8551 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8552 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8553 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8554 if (Op0.getOpcode() == ISD::FNEG) 8555 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8556 DAG.getConstant(SignBit, DL, VT)); 8557 8558 assert(Op0.getOpcode() == ISD::FABS); 8559 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8560 DAG.getConstant(~SignBit, DL, VT)); 8561 } 8562 case ISD::ADD: 8563 return performADDCombine(N, DAG, Subtarget); 8564 case ISD::SUB: 8565 return performSUBCombine(N, DAG); 8566 case ISD::AND: 8567 return performANDCombine(N, DAG); 8568 case ISD::OR: 8569 return performORCombine(N, DAG, Subtarget); 8570 case ISD::XOR: 8571 return performXORCombine(N, DAG); 8572 case ISD::SIGN_EXTEND_INREG: 8573 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8574 case ISD::ZERO_EXTEND: 8575 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8576 // type legalization. This is safe because fp_to_uint produces poison if 8577 // it overflows. 8578 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8579 SDValue Src = N->getOperand(0); 8580 if (Src.getOpcode() == ISD::FP_TO_UINT && 8581 isTypeLegal(Src.getOperand(0).getValueType())) 8582 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8583 Src.getOperand(0)); 8584 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8585 isTypeLegal(Src.getOperand(1).getValueType())) { 8586 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8587 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8588 Src.getOperand(0), Src.getOperand(1)); 8589 DCI.CombineTo(N, Res); 8590 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8591 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8592 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8593 } 8594 } 8595 return SDValue(); 8596 case RISCVISD::SELECT_CC: { 8597 // Transform 8598 SDValue LHS = N->getOperand(0); 8599 SDValue RHS = N->getOperand(1); 8600 SDValue TrueV = N->getOperand(3); 8601 SDValue FalseV = N->getOperand(4); 8602 8603 // If the True and False values are the same, we don't need a select_cc. 8604 if (TrueV == FalseV) 8605 return TrueV; 8606 8607 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8608 if (!ISD::isIntEqualitySetCC(CCVal)) 8609 break; 8610 8611 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8612 // (select_cc X, Y, lt, trueV, falseV) 8613 // Sometimes the setcc is introduced after select_cc has been formed. 8614 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8615 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8616 // If we're looking for eq 0 instead of ne 0, we need to invert the 8617 // condition. 8618 bool Invert = CCVal == ISD::SETEQ; 8619 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8620 if (Invert) 8621 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8622 8623 SDLoc DL(N); 8624 RHS = LHS.getOperand(1); 8625 LHS = LHS.getOperand(0); 8626 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8627 8628 SDValue TargetCC = DAG.getCondCode(CCVal); 8629 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8630 {LHS, RHS, TargetCC, TrueV, FalseV}); 8631 } 8632 8633 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8634 // (select_cc X, Y, eq/ne, trueV, falseV) 8635 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8636 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8637 {LHS.getOperand(0), LHS.getOperand(1), 8638 N->getOperand(2), TrueV, FalseV}); 8639 // (select_cc X, 1, setne, trueV, falseV) -> 8640 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8641 // This can occur when legalizing some floating point comparisons. 8642 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8643 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8644 SDLoc DL(N); 8645 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8646 SDValue TargetCC = DAG.getCondCode(CCVal); 8647 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8648 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8649 {LHS, RHS, TargetCC, TrueV, FalseV}); 8650 } 8651 8652 break; 8653 } 8654 case RISCVISD::BR_CC: { 8655 SDValue LHS = N->getOperand(1); 8656 SDValue RHS = N->getOperand(2); 8657 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8658 if (!ISD::isIntEqualitySetCC(CCVal)) 8659 break; 8660 8661 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8662 // (br_cc X, Y, lt, dest) 8663 // Sometimes the setcc is introduced after br_cc has been formed. 8664 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8665 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8666 // If we're looking for eq 0 instead of ne 0, we need to invert the 8667 // condition. 8668 bool Invert = CCVal == ISD::SETEQ; 8669 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8670 if (Invert) 8671 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8672 8673 SDLoc DL(N); 8674 RHS = LHS.getOperand(1); 8675 LHS = LHS.getOperand(0); 8676 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8677 8678 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8679 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8680 N->getOperand(4)); 8681 } 8682 8683 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8684 // (br_cc X, Y, eq/ne, trueV, falseV) 8685 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8686 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8687 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8688 N->getOperand(3), N->getOperand(4)); 8689 8690 // (br_cc X, 1, setne, br_cc) -> 8691 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8692 // This can occur when legalizing some floating point comparisons. 8693 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8694 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8695 SDLoc DL(N); 8696 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8697 SDValue TargetCC = DAG.getCondCode(CCVal); 8698 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8699 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8700 N->getOperand(0), LHS, RHS, TargetCC, 8701 N->getOperand(4)); 8702 } 8703 break; 8704 } 8705 case ISD::BITREVERSE: 8706 return performBITREVERSECombine(N, DAG, Subtarget); 8707 case ISD::FP_TO_SINT: 8708 case ISD::FP_TO_UINT: 8709 return performFP_TO_INTCombine(N, DCI, Subtarget); 8710 case ISD::FP_TO_SINT_SAT: 8711 case ISD::FP_TO_UINT_SAT: 8712 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8713 case ISD::FCOPYSIGN: { 8714 EVT VT = N->getValueType(0); 8715 if (!VT.isVector()) 8716 break; 8717 // There is a form of VFSGNJ which injects the negated sign of its second 8718 // operand. Try and bubble any FNEG up after the extend/round to produce 8719 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8720 // TRUNC=1. 8721 SDValue In2 = N->getOperand(1); 8722 // Avoid cases where the extend/round has multiple uses, as duplicating 8723 // those is typically more expensive than removing a fneg. 8724 if (!In2.hasOneUse()) 8725 break; 8726 if (In2.getOpcode() != ISD::FP_EXTEND && 8727 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8728 break; 8729 In2 = In2.getOperand(0); 8730 if (In2.getOpcode() != ISD::FNEG) 8731 break; 8732 SDLoc DL(N); 8733 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8734 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8735 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8736 } 8737 case ISD::MGATHER: 8738 case ISD::MSCATTER: 8739 case ISD::VP_GATHER: 8740 case ISD::VP_SCATTER: { 8741 if (!DCI.isBeforeLegalize()) 8742 break; 8743 SDValue Index, ScaleOp; 8744 bool IsIndexScaled = false; 8745 bool IsIndexSigned = false; 8746 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8747 Index = VPGSN->getIndex(); 8748 ScaleOp = VPGSN->getScale(); 8749 IsIndexScaled = VPGSN->isIndexScaled(); 8750 IsIndexSigned = VPGSN->isIndexSigned(); 8751 } else { 8752 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8753 Index = MGSN->getIndex(); 8754 ScaleOp = MGSN->getScale(); 8755 IsIndexScaled = MGSN->isIndexScaled(); 8756 IsIndexSigned = MGSN->isIndexSigned(); 8757 } 8758 EVT IndexVT = Index.getValueType(); 8759 MVT XLenVT = Subtarget.getXLenVT(); 8760 // RISCV indexed loads only support the "unsigned unscaled" addressing 8761 // mode, so anything else must be manually legalized. 8762 bool NeedsIdxLegalization = 8763 IsIndexScaled || 8764 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8765 if (!NeedsIdxLegalization) 8766 break; 8767 8768 SDLoc DL(N); 8769 8770 // Any index legalization should first promote to XLenVT, so we don't lose 8771 // bits when scaling. This may create an illegal index type so we let 8772 // LLVM's legalization take care of the splitting. 8773 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8774 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8775 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8776 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8777 DL, IndexVT, Index); 8778 } 8779 8780 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8781 if (IsIndexScaled && Scale != 1) { 8782 // Manually scale the indices by the element size. 8783 // TODO: Sanitize the scale operand here? 8784 // TODO: For VP nodes, should we use VP_SHL here? 8785 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8786 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8787 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8788 } 8789 8790 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8791 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8792 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8793 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8794 VPGN->getScale(), VPGN->getMask(), 8795 VPGN->getVectorLength()}, 8796 VPGN->getMemOperand(), NewIndexTy); 8797 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8798 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8799 {VPSN->getChain(), VPSN->getValue(), 8800 VPSN->getBasePtr(), Index, VPSN->getScale(), 8801 VPSN->getMask(), VPSN->getVectorLength()}, 8802 VPSN->getMemOperand(), NewIndexTy); 8803 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8804 return DAG.getMaskedGather( 8805 N->getVTList(), MGN->getMemoryVT(), DL, 8806 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8807 MGN->getBasePtr(), Index, MGN->getScale()}, 8808 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8809 const auto *MSN = cast<MaskedScatterSDNode>(N); 8810 return DAG.getMaskedScatter( 8811 N->getVTList(), MSN->getMemoryVT(), DL, 8812 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8813 Index, MSN->getScale()}, 8814 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8815 } 8816 case RISCVISD::SRA_VL: 8817 case RISCVISD::SRL_VL: 8818 case RISCVISD::SHL_VL: { 8819 SDValue ShAmt = N->getOperand(1); 8820 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8821 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8822 SDLoc DL(N); 8823 SDValue VL = N->getOperand(3); 8824 EVT VT = N->getValueType(0); 8825 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8826 ShAmt.getOperand(1), VL); 8827 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8828 N->getOperand(2), N->getOperand(3)); 8829 } 8830 break; 8831 } 8832 case ISD::SRA: 8833 case ISD::SRL: 8834 case ISD::SHL: { 8835 SDValue ShAmt = N->getOperand(1); 8836 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8837 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8838 SDLoc DL(N); 8839 EVT VT = N->getValueType(0); 8840 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8841 ShAmt.getOperand(1), 8842 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8843 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8844 } 8845 break; 8846 } 8847 case RISCVISD::ADD_VL: 8848 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8849 return V; 8850 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8851 case RISCVISD::SUB_VL: 8852 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8853 case RISCVISD::VWADD_W_VL: 8854 case RISCVISD::VWADDU_W_VL: 8855 case RISCVISD::VWSUB_W_VL: 8856 case RISCVISD::VWSUBU_W_VL: 8857 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8858 case RISCVISD::MUL_VL: 8859 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8860 return V; 8861 // Mul is commutative. 8862 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8863 case ISD::STORE: { 8864 auto *Store = cast<StoreSDNode>(N); 8865 SDValue Val = Store->getValue(); 8866 // Combine store of vmv.x.s to vse with VL of 1. 8867 // FIXME: Support FP. 8868 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8869 SDValue Src = Val.getOperand(0); 8870 EVT VecVT = Src.getValueType(); 8871 EVT MemVT = Store->getMemoryVT(); 8872 // The memory VT and the element type must match. 8873 if (VecVT.getVectorElementType() == MemVT) { 8874 SDLoc DL(N); 8875 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8876 return DAG.getStoreVP( 8877 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8878 DAG.getConstant(1, DL, MaskVT), 8879 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8880 Store->getMemOperand(), Store->getAddressingMode(), 8881 Store->isTruncatingStore(), /*IsCompress*/ false); 8882 } 8883 } 8884 8885 break; 8886 } 8887 case ISD::SPLAT_VECTOR: { 8888 EVT VT = N->getValueType(0); 8889 // Only perform this combine on legal MVT types. 8890 if (!isTypeLegal(VT)) 8891 break; 8892 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8893 DAG, Subtarget)) 8894 return Gather; 8895 break; 8896 } 8897 case RISCVISD::VMV_V_X_VL: { 8898 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8899 // scalar input. 8900 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8901 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8902 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8903 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8904 return SDValue(N, 0); 8905 8906 break; 8907 } 8908 case ISD::INTRINSIC_WO_CHAIN: { 8909 unsigned IntNo = N->getConstantOperandVal(0); 8910 switch (IntNo) { 8911 // By default we do not combine any intrinsic. 8912 default: 8913 return SDValue(); 8914 case Intrinsic::riscv_vcpop: 8915 case Intrinsic::riscv_vcpop_mask: 8916 case Intrinsic::riscv_vfirst: 8917 case Intrinsic::riscv_vfirst_mask: { 8918 SDValue VL = N->getOperand(2); 8919 if (IntNo == Intrinsic::riscv_vcpop_mask || 8920 IntNo == Intrinsic::riscv_vfirst_mask) 8921 VL = N->getOperand(3); 8922 if (!isNullConstant(VL)) 8923 return SDValue(); 8924 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8925 SDLoc DL(N); 8926 EVT VT = N->getValueType(0); 8927 if (IntNo == Intrinsic::riscv_vfirst || 8928 IntNo == Intrinsic::riscv_vfirst_mask) 8929 return DAG.getConstant(-1, DL, VT); 8930 return DAG.getConstant(0, DL, VT); 8931 } 8932 } 8933 } 8934 } 8935 8936 return SDValue(); 8937 } 8938 8939 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8940 const SDNode *N, CombineLevel Level) const { 8941 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8942 // materialised in fewer instructions than `(OP _, c1)`: 8943 // 8944 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8945 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8946 SDValue N0 = N->getOperand(0); 8947 EVT Ty = N0.getValueType(); 8948 if (Ty.isScalarInteger() && 8949 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8950 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8951 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8952 if (C1 && C2) { 8953 const APInt &C1Int = C1->getAPIntValue(); 8954 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8955 8956 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8957 // and the combine should happen, to potentially allow further combines 8958 // later. 8959 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8960 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8961 return true; 8962 8963 // We can materialise `c1` in an add immediate, so it's "free", and the 8964 // combine should be prevented. 8965 if (C1Int.getMinSignedBits() <= 64 && 8966 isLegalAddImmediate(C1Int.getSExtValue())) 8967 return false; 8968 8969 // Neither constant will fit into an immediate, so find materialisation 8970 // costs. 8971 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8972 Subtarget.getFeatureBits(), 8973 /*CompressionCost*/true); 8974 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8975 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8976 /*CompressionCost*/true); 8977 8978 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8979 // combine should be prevented. 8980 if (C1Cost < ShiftedC1Cost) 8981 return false; 8982 } 8983 } 8984 return true; 8985 } 8986 8987 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8988 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8989 TargetLoweringOpt &TLO) const { 8990 // Delay this optimization as late as possible. 8991 if (!TLO.LegalOps) 8992 return false; 8993 8994 EVT VT = Op.getValueType(); 8995 if (VT.isVector()) 8996 return false; 8997 8998 // Only handle AND for now. 8999 if (Op.getOpcode() != ISD::AND) 9000 return false; 9001 9002 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9003 if (!C) 9004 return false; 9005 9006 const APInt &Mask = C->getAPIntValue(); 9007 9008 // Clear all non-demanded bits initially. 9009 APInt ShrunkMask = Mask & DemandedBits; 9010 9011 // Try to make a smaller immediate by setting undemanded bits. 9012 9013 APInt ExpandedMask = Mask | ~DemandedBits; 9014 9015 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9016 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9017 }; 9018 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9019 if (NewMask == Mask) 9020 return true; 9021 SDLoc DL(Op); 9022 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9023 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9024 return TLO.CombineTo(Op, NewOp); 9025 }; 9026 9027 // If the shrunk mask fits in sign extended 12 bits, let the target 9028 // independent code apply it. 9029 if (ShrunkMask.isSignedIntN(12)) 9030 return false; 9031 9032 // Preserve (and X, 0xffff) when zext.h is supported. 9033 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9034 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9035 if (IsLegalMask(NewMask)) 9036 return UseMask(NewMask); 9037 } 9038 9039 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9040 if (VT == MVT::i64) { 9041 APInt NewMask = APInt(64, 0xffffffff); 9042 if (IsLegalMask(NewMask)) 9043 return UseMask(NewMask); 9044 } 9045 9046 // For the remaining optimizations, we need to be able to make a negative 9047 // number through a combination of mask and undemanded bits. 9048 if (!ExpandedMask.isNegative()) 9049 return false; 9050 9051 // What is the fewest number of bits we need to represent the negative number. 9052 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9053 9054 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9055 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9056 APInt NewMask = ShrunkMask; 9057 if (MinSignedBits <= 12) 9058 NewMask.setBitsFrom(11); 9059 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9060 NewMask.setBitsFrom(31); 9061 else 9062 return false; 9063 9064 // Check that our new mask is a subset of the demanded mask. 9065 assert(IsLegalMask(NewMask)); 9066 return UseMask(NewMask); 9067 } 9068 9069 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9070 static const uint64_t GREVMasks[] = { 9071 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9072 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9073 9074 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9075 unsigned Shift = 1 << Stage; 9076 if (ShAmt & Shift) { 9077 uint64_t Mask = GREVMasks[Stage]; 9078 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9079 if (IsGORC) 9080 Res |= x; 9081 x = Res; 9082 } 9083 } 9084 9085 return x; 9086 } 9087 9088 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9089 KnownBits &Known, 9090 const APInt &DemandedElts, 9091 const SelectionDAG &DAG, 9092 unsigned Depth) const { 9093 unsigned BitWidth = Known.getBitWidth(); 9094 unsigned Opc = Op.getOpcode(); 9095 assert((Opc >= ISD::BUILTIN_OP_END || 9096 Opc == ISD::INTRINSIC_WO_CHAIN || 9097 Opc == ISD::INTRINSIC_W_CHAIN || 9098 Opc == ISD::INTRINSIC_VOID) && 9099 "Should use MaskedValueIsZero if you don't know whether Op" 9100 " is a target node!"); 9101 9102 Known.resetAll(); 9103 switch (Opc) { 9104 default: break; 9105 case RISCVISD::SELECT_CC: { 9106 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9107 // If we don't know any bits, early out. 9108 if (Known.isUnknown()) 9109 break; 9110 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9111 9112 // Only known if known in both the LHS and RHS. 9113 Known = KnownBits::commonBits(Known, Known2); 9114 break; 9115 } 9116 case RISCVISD::REMUW: { 9117 KnownBits Known2; 9118 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9119 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9120 // We only care about the lower 32 bits. 9121 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9122 // Restore the original width by sign extending. 9123 Known = Known.sext(BitWidth); 9124 break; 9125 } 9126 case RISCVISD::DIVUW: { 9127 KnownBits Known2; 9128 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9129 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9130 // We only care about the lower 32 bits. 9131 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9132 // Restore the original width by sign extending. 9133 Known = Known.sext(BitWidth); 9134 break; 9135 } 9136 case RISCVISD::CTZW: { 9137 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9138 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9139 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9140 Known.Zero.setBitsFrom(LowBits); 9141 break; 9142 } 9143 case RISCVISD::CLZW: { 9144 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9145 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9146 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9147 Known.Zero.setBitsFrom(LowBits); 9148 break; 9149 } 9150 case RISCVISD::GREV: 9151 case RISCVISD::GORC: { 9152 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9153 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9154 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9155 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9156 // To compute zeros, we need to invert the value and invert it back after. 9157 Known.Zero = 9158 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9159 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9160 } 9161 break; 9162 } 9163 case RISCVISD::READ_VLENB: { 9164 // If we know the minimum VLen from Zvl extensions, we can use that to 9165 // determine the trailing zeros of VLENB. 9166 // FIXME: Limit to 128 bit vectors until we have more testing. 9167 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9168 if (MinVLenB > 0) 9169 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9170 // We assume VLENB is no more than 65536 / 8 bytes. 9171 Known.Zero.setBitsFrom(14); 9172 break; 9173 } 9174 case ISD::INTRINSIC_W_CHAIN: 9175 case ISD::INTRINSIC_WO_CHAIN: { 9176 unsigned IntNo = 9177 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9178 switch (IntNo) { 9179 default: 9180 // We can't do anything for most intrinsics. 9181 break; 9182 case Intrinsic::riscv_vsetvli: 9183 case Intrinsic::riscv_vsetvlimax: 9184 case Intrinsic::riscv_vsetvli_opt: 9185 case Intrinsic::riscv_vsetvlimax_opt: 9186 // Assume that VL output is positive and would fit in an int32_t. 9187 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9188 if (BitWidth >= 32) 9189 Known.Zero.setBitsFrom(31); 9190 break; 9191 } 9192 break; 9193 } 9194 } 9195 } 9196 9197 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9198 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9199 unsigned Depth) const { 9200 switch (Op.getOpcode()) { 9201 default: 9202 break; 9203 case RISCVISD::SELECT_CC: { 9204 unsigned Tmp = 9205 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9206 if (Tmp == 1) return 1; // Early out. 9207 unsigned Tmp2 = 9208 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9209 return std::min(Tmp, Tmp2); 9210 } 9211 case RISCVISD::SLLW: 9212 case RISCVISD::SRAW: 9213 case RISCVISD::SRLW: 9214 case RISCVISD::DIVW: 9215 case RISCVISD::DIVUW: 9216 case RISCVISD::REMUW: 9217 case RISCVISD::ROLW: 9218 case RISCVISD::RORW: 9219 case RISCVISD::GREVW: 9220 case RISCVISD::GORCW: 9221 case RISCVISD::FSLW: 9222 case RISCVISD::FSRW: 9223 case RISCVISD::SHFLW: 9224 case RISCVISD::UNSHFLW: 9225 case RISCVISD::BCOMPRESSW: 9226 case RISCVISD::BDECOMPRESSW: 9227 case RISCVISD::BFPW: 9228 case RISCVISD::FCVT_W_RV64: 9229 case RISCVISD::FCVT_WU_RV64: 9230 case RISCVISD::STRICT_FCVT_W_RV64: 9231 case RISCVISD::STRICT_FCVT_WU_RV64: 9232 // TODO: As the result is sign-extended, this is conservatively correct. A 9233 // more precise answer could be calculated for SRAW depending on known 9234 // bits in the shift amount. 9235 return 33; 9236 case RISCVISD::SHFL: 9237 case RISCVISD::UNSHFL: { 9238 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9239 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9240 // will stay within the upper 32 bits. If there were more than 32 sign bits 9241 // before there will be at least 33 sign bits after. 9242 if (Op.getValueType() == MVT::i64 && 9243 isa<ConstantSDNode>(Op.getOperand(1)) && 9244 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9245 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9246 if (Tmp > 32) 9247 return 33; 9248 } 9249 break; 9250 } 9251 case RISCVISD::VMV_X_S: { 9252 // The number of sign bits of the scalar result is computed by obtaining the 9253 // element type of the input vector operand, subtracting its width from the 9254 // XLEN, and then adding one (sign bit within the element type). If the 9255 // element type is wider than XLen, the least-significant XLEN bits are 9256 // taken. 9257 unsigned XLen = Subtarget.getXLen(); 9258 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9259 if (EltBits <= XLen) 9260 return XLen - EltBits + 1; 9261 break; 9262 } 9263 } 9264 9265 return 1; 9266 } 9267 9268 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9269 MachineBasicBlock *BB) { 9270 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9271 9272 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9273 // Should the count have wrapped while it was being read, we need to try 9274 // again. 9275 // ... 9276 // read: 9277 // rdcycleh x3 # load high word of cycle 9278 // rdcycle x2 # load low word of cycle 9279 // rdcycleh x4 # load high word of cycle 9280 // bne x3, x4, read # check if high word reads match, otherwise try again 9281 // ... 9282 9283 MachineFunction &MF = *BB->getParent(); 9284 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9285 MachineFunction::iterator It = ++BB->getIterator(); 9286 9287 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9288 MF.insert(It, LoopMBB); 9289 9290 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9291 MF.insert(It, DoneMBB); 9292 9293 // Transfer the remainder of BB and its successor edges to DoneMBB. 9294 DoneMBB->splice(DoneMBB->begin(), BB, 9295 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9296 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9297 9298 BB->addSuccessor(LoopMBB); 9299 9300 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9301 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9302 Register LoReg = MI.getOperand(0).getReg(); 9303 Register HiReg = MI.getOperand(1).getReg(); 9304 DebugLoc DL = MI.getDebugLoc(); 9305 9306 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9307 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9308 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9309 .addReg(RISCV::X0); 9310 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9311 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9312 .addReg(RISCV::X0); 9313 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9314 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9315 .addReg(RISCV::X0); 9316 9317 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9318 .addReg(HiReg) 9319 .addReg(ReadAgainReg) 9320 .addMBB(LoopMBB); 9321 9322 LoopMBB->addSuccessor(LoopMBB); 9323 LoopMBB->addSuccessor(DoneMBB); 9324 9325 MI.eraseFromParent(); 9326 9327 return DoneMBB; 9328 } 9329 9330 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9331 MachineBasicBlock *BB) { 9332 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9333 9334 MachineFunction &MF = *BB->getParent(); 9335 DebugLoc DL = MI.getDebugLoc(); 9336 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9337 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9338 Register LoReg = MI.getOperand(0).getReg(); 9339 Register HiReg = MI.getOperand(1).getReg(); 9340 Register SrcReg = MI.getOperand(2).getReg(); 9341 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9342 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9343 9344 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9345 RI); 9346 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9347 MachineMemOperand *MMOLo = 9348 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9349 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9350 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9351 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9352 .addFrameIndex(FI) 9353 .addImm(0) 9354 .addMemOperand(MMOLo); 9355 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9356 .addFrameIndex(FI) 9357 .addImm(4) 9358 .addMemOperand(MMOHi); 9359 MI.eraseFromParent(); // The pseudo instruction is gone now. 9360 return BB; 9361 } 9362 9363 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9364 MachineBasicBlock *BB) { 9365 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9366 "Unexpected instruction"); 9367 9368 MachineFunction &MF = *BB->getParent(); 9369 DebugLoc DL = MI.getDebugLoc(); 9370 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9371 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9372 Register DstReg = MI.getOperand(0).getReg(); 9373 Register LoReg = MI.getOperand(1).getReg(); 9374 Register HiReg = MI.getOperand(2).getReg(); 9375 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9376 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9377 9378 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9379 MachineMemOperand *MMOLo = 9380 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9381 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9382 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9383 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9384 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9385 .addFrameIndex(FI) 9386 .addImm(0) 9387 .addMemOperand(MMOLo); 9388 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9389 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9390 .addFrameIndex(FI) 9391 .addImm(4) 9392 .addMemOperand(MMOHi); 9393 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9394 MI.eraseFromParent(); // The pseudo instruction is gone now. 9395 return BB; 9396 } 9397 9398 static bool isSelectPseudo(MachineInstr &MI) { 9399 switch (MI.getOpcode()) { 9400 default: 9401 return false; 9402 case RISCV::Select_GPR_Using_CC_GPR: 9403 case RISCV::Select_FPR16_Using_CC_GPR: 9404 case RISCV::Select_FPR32_Using_CC_GPR: 9405 case RISCV::Select_FPR64_Using_CC_GPR: 9406 return true; 9407 } 9408 } 9409 9410 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9411 unsigned RelOpcode, unsigned EqOpcode, 9412 const RISCVSubtarget &Subtarget) { 9413 DebugLoc DL = MI.getDebugLoc(); 9414 Register DstReg = MI.getOperand(0).getReg(); 9415 Register Src1Reg = MI.getOperand(1).getReg(); 9416 Register Src2Reg = MI.getOperand(2).getReg(); 9417 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9418 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9419 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9420 9421 // Save the current FFLAGS. 9422 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9423 9424 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9425 .addReg(Src1Reg) 9426 .addReg(Src2Reg); 9427 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9428 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9429 9430 // Restore the FFLAGS. 9431 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9432 .addReg(SavedFFlags, RegState::Kill); 9433 9434 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9435 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9436 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9437 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9438 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9439 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9440 9441 // Erase the pseudoinstruction. 9442 MI.eraseFromParent(); 9443 return BB; 9444 } 9445 9446 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9447 MachineBasicBlock *BB, 9448 const RISCVSubtarget &Subtarget) { 9449 // To "insert" Select_* instructions, we actually have to insert the triangle 9450 // control-flow pattern. The incoming instructions know the destination vreg 9451 // to set, the condition code register to branch on, the true/false values to 9452 // select between, and the condcode to use to select the appropriate branch. 9453 // 9454 // We produce the following control flow: 9455 // HeadMBB 9456 // | \ 9457 // | IfFalseMBB 9458 // | / 9459 // TailMBB 9460 // 9461 // When we find a sequence of selects we attempt to optimize their emission 9462 // by sharing the control flow. Currently we only handle cases where we have 9463 // multiple selects with the exact same condition (same LHS, RHS and CC). 9464 // The selects may be interleaved with other instructions if the other 9465 // instructions meet some requirements we deem safe: 9466 // - They are debug instructions. Otherwise, 9467 // - They do not have side-effects, do not access memory and their inputs do 9468 // not depend on the results of the select pseudo-instructions. 9469 // The TrueV/FalseV operands of the selects cannot depend on the result of 9470 // previous selects in the sequence. 9471 // These conditions could be further relaxed. See the X86 target for a 9472 // related approach and more information. 9473 Register LHS = MI.getOperand(1).getReg(); 9474 Register RHS = MI.getOperand(2).getReg(); 9475 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9476 9477 SmallVector<MachineInstr *, 4> SelectDebugValues; 9478 SmallSet<Register, 4> SelectDests; 9479 SelectDests.insert(MI.getOperand(0).getReg()); 9480 9481 MachineInstr *LastSelectPseudo = &MI; 9482 9483 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9484 SequenceMBBI != E; ++SequenceMBBI) { 9485 if (SequenceMBBI->isDebugInstr()) 9486 continue; 9487 else if (isSelectPseudo(*SequenceMBBI)) { 9488 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9489 SequenceMBBI->getOperand(2).getReg() != RHS || 9490 SequenceMBBI->getOperand(3).getImm() != CC || 9491 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9492 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9493 break; 9494 LastSelectPseudo = &*SequenceMBBI; 9495 SequenceMBBI->collectDebugValues(SelectDebugValues); 9496 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9497 } else { 9498 if (SequenceMBBI->hasUnmodeledSideEffects() || 9499 SequenceMBBI->mayLoadOrStore()) 9500 break; 9501 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9502 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9503 })) 9504 break; 9505 } 9506 } 9507 9508 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9509 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9510 DebugLoc DL = MI.getDebugLoc(); 9511 MachineFunction::iterator I = ++BB->getIterator(); 9512 9513 MachineBasicBlock *HeadMBB = BB; 9514 MachineFunction *F = BB->getParent(); 9515 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9516 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9517 9518 F->insert(I, IfFalseMBB); 9519 F->insert(I, TailMBB); 9520 9521 // Transfer debug instructions associated with the selects to TailMBB. 9522 for (MachineInstr *DebugInstr : SelectDebugValues) { 9523 TailMBB->push_back(DebugInstr->removeFromParent()); 9524 } 9525 9526 // Move all instructions after the sequence to TailMBB. 9527 TailMBB->splice(TailMBB->end(), HeadMBB, 9528 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9529 // Update machine-CFG edges by transferring all successors of the current 9530 // block to the new block which will contain the Phi nodes for the selects. 9531 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9532 // Set the successors for HeadMBB. 9533 HeadMBB->addSuccessor(IfFalseMBB); 9534 HeadMBB->addSuccessor(TailMBB); 9535 9536 // Insert appropriate branch. 9537 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9538 .addReg(LHS) 9539 .addReg(RHS) 9540 .addMBB(TailMBB); 9541 9542 // IfFalseMBB just falls through to TailMBB. 9543 IfFalseMBB->addSuccessor(TailMBB); 9544 9545 // Create PHIs for all of the select pseudo-instructions. 9546 auto SelectMBBI = MI.getIterator(); 9547 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9548 auto InsertionPoint = TailMBB->begin(); 9549 while (SelectMBBI != SelectEnd) { 9550 auto Next = std::next(SelectMBBI); 9551 if (isSelectPseudo(*SelectMBBI)) { 9552 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9553 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9554 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9555 .addReg(SelectMBBI->getOperand(4).getReg()) 9556 .addMBB(HeadMBB) 9557 .addReg(SelectMBBI->getOperand(5).getReg()) 9558 .addMBB(IfFalseMBB); 9559 SelectMBBI->eraseFromParent(); 9560 } 9561 SelectMBBI = Next; 9562 } 9563 9564 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9565 return TailMBB; 9566 } 9567 9568 MachineBasicBlock * 9569 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9570 MachineBasicBlock *BB) const { 9571 switch (MI.getOpcode()) { 9572 default: 9573 llvm_unreachable("Unexpected instr type to insert"); 9574 case RISCV::ReadCycleWide: 9575 assert(!Subtarget.is64Bit() && 9576 "ReadCycleWrite is only to be used on riscv32"); 9577 return emitReadCycleWidePseudo(MI, BB); 9578 case RISCV::Select_GPR_Using_CC_GPR: 9579 case RISCV::Select_FPR16_Using_CC_GPR: 9580 case RISCV::Select_FPR32_Using_CC_GPR: 9581 case RISCV::Select_FPR64_Using_CC_GPR: 9582 return emitSelectPseudo(MI, BB, Subtarget); 9583 case RISCV::BuildPairF64Pseudo: 9584 return emitBuildPairF64Pseudo(MI, BB); 9585 case RISCV::SplitF64Pseudo: 9586 return emitSplitF64Pseudo(MI, BB); 9587 case RISCV::PseudoQuietFLE_H: 9588 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9589 case RISCV::PseudoQuietFLT_H: 9590 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9591 case RISCV::PseudoQuietFLE_S: 9592 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9593 case RISCV::PseudoQuietFLT_S: 9594 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9595 case RISCV::PseudoQuietFLE_D: 9596 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9597 case RISCV::PseudoQuietFLT_D: 9598 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9599 } 9600 } 9601 9602 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9603 SDNode *Node) const { 9604 // Add FRM dependency to any instructions with dynamic rounding mode. 9605 unsigned Opc = MI.getOpcode(); 9606 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9607 if (Idx < 0) 9608 return; 9609 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9610 return; 9611 // If the instruction already reads FRM, don't add another read. 9612 if (MI.readsRegister(RISCV::FRM)) 9613 return; 9614 MI.addOperand( 9615 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9616 } 9617 9618 // Calling Convention Implementation. 9619 // The expectations for frontend ABI lowering vary from target to target. 9620 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9621 // details, but this is a longer term goal. For now, we simply try to keep the 9622 // role of the frontend as simple and well-defined as possible. The rules can 9623 // be summarised as: 9624 // * Never split up large scalar arguments. We handle them here. 9625 // * If a hardfloat calling convention is being used, and the struct may be 9626 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9627 // available, then pass as two separate arguments. If either the GPRs or FPRs 9628 // are exhausted, then pass according to the rule below. 9629 // * If a struct could never be passed in registers or directly in a stack 9630 // slot (as it is larger than 2*XLEN and the floating point rules don't 9631 // apply), then pass it using a pointer with the byval attribute. 9632 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9633 // word-sized array or a 2*XLEN scalar (depending on alignment). 9634 // * The frontend can determine whether a struct is returned by reference or 9635 // not based on its size and fields. If it will be returned by reference, the 9636 // frontend must modify the prototype so a pointer with the sret annotation is 9637 // passed as the first argument. This is not necessary for large scalar 9638 // returns. 9639 // * Struct return values and varargs should be coerced to structs containing 9640 // register-size fields in the same situations they would be for fixed 9641 // arguments. 9642 9643 static const MCPhysReg ArgGPRs[] = { 9644 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9645 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9646 }; 9647 static const MCPhysReg ArgFPR16s[] = { 9648 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9649 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9650 }; 9651 static const MCPhysReg ArgFPR32s[] = { 9652 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9653 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9654 }; 9655 static const MCPhysReg ArgFPR64s[] = { 9656 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9657 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9658 }; 9659 // This is an interim calling convention and it may be changed in the future. 9660 static const MCPhysReg ArgVRs[] = { 9661 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9662 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9663 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9664 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9665 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9666 RISCV::V20M2, RISCV::V22M2}; 9667 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9668 RISCV::V20M4}; 9669 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9670 9671 // Pass a 2*XLEN argument that has been split into two XLEN values through 9672 // registers or the stack as necessary. 9673 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9674 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9675 MVT ValVT2, MVT LocVT2, 9676 ISD::ArgFlagsTy ArgFlags2) { 9677 unsigned XLenInBytes = XLen / 8; 9678 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9679 // At least one half can be passed via register. 9680 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9681 VA1.getLocVT(), CCValAssign::Full)); 9682 } else { 9683 // Both halves must be passed on the stack, with proper alignment. 9684 Align StackAlign = 9685 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9686 State.addLoc( 9687 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9688 State.AllocateStack(XLenInBytes, StackAlign), 9689 VA1.getLocVT(), CCValAssign::Full)); 9690 State.addLoc(CCValAssign::getMem( 9691 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9692 LocVT2, CCValAssign::Full)); 9693 return false; 9694 } 9695 9696 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9697 // The second half can also be passed via register. 9698 State.addLoc( 9699 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9700 } else { 9701 // The second half is passed via the stack, without additional alignment. 9702 State.addLoc(CCValAssign::getMem( 9703 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9704 LocVT2, CCValAssign::Full)); 9705 } 9706 9707 return false; 9708 } 9709 9710 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9711 Optional<unsigned> FirstMaskArgument, 9712 CCState &State, const RISCVTargetLowering &TLI) { 9713 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9714 if (RC == &RISCV::VRRegClass) { 9715 // Assign the first mask argument to V0. 9716 // This is an interim calling convention and it may be changed in the 9717 // future. 9718 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9719 return State.AllocateReg(RISCV::V0); 9720 return State.AllocateReg(ArgVRs); 9721 } 9722 if (RC == &RISCV::VRM2RegClass) 9723 return State.AllocateReg(ArgVRM2s); 9724 if (RC == &RISCV::VRM4RegClass) 9725 return State.AllocateReg(ArgVRM4s); 9726 if (RC == &RISCV::VRM8RegClass) 9727 return State.AllocateReg(ArgVRM8s); 9728 llvm_unreachable("Unhandled register class for ValueType"); 9729 } 9730 9731 // Implements the RISC-V calling convention. Returns true upon failure. 9732 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9733 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9734 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9735 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9736 Optional<unsigned> FirstMaskArgument) { 9737 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9738 assert(XLen == 32 || XLen == 64); 9739 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9740 9741 // Any return value split in to more than two values can't be returned 9742 // directly. Vectors are returned via the available vector registers. 9743 if (!LocVT.isVector() && IsRet && ValNo > 1) 9744 return true; 9745 9746 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9747 // variadic argument, or if no F16/F32 argument registers are available. 9748 bool UseGPRForF16_F32 = true; 9749 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9750 // variadic argument, or if no F64 argument registers are available. 9751 bool UseGPRForF64 = true; 9752 9753 switch (ABI) { 9754 default: 9755 llvm_unreachable("Unexpected ABI"); 9756 case RISCVABI::ABI_ILP32: 9757 case RISCVABI::ABI_LP64: 9758 break; 9759 case RISCVABI::ABI_ILP32F: 9760 case RISCVABI::ABI_LP64F: 9761 UseGPRForF16_F32 = !IsFixed; 9762 break; 9763 case RISCVABI::ABI_ILP32D: 9764 case RISCVABI::ABI_LP64D: 9765 UseGPRForF16_F32 = !IsFixed; 9766 UseGPRForF64 = !IsFixed; 9767 break; 9768 } 9769 9770 // FPR16, FPR32, and FPR64 alias each other. 9771 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9772 UseGPRForF16_F32 = true; 9773 UseGPRForF64 = true; 9774 } 9775 9776 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9777 // similar local variables rather than directly checking against the target 9778 // ABI. 9779 9780 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9781 LocVT = XLenVT; 9782 LocInfo = CCValAssign::BCvt; 9783 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9784 LocVT = MVT::i64; 9785 LocInfo = CCValAssign::BCvt; 9786 } 9787 9788 // If this is a variadic argument, the RISC-V calling convention requires 9789 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9790 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9791 // be used regardless of whether the original argument was split during 9792 // legalisation or not. The argument will not be passed by registers if the 9793 // original type is larger than 2*XLEN, so the register alignment rule does 9794 // not apply. 9795 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9796 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9797 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9798 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9799 // Skip 'odd' register if necessary. 9800 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9801 State.AllocateReg(ArgGPRs); 9802 } 9803 9804 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9805 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9806 State.getPendingArgFlags(); 9807 9808 assert(PendingLocs.size() == PendingArgFlags.size() && 9809 "PendingLocs and PendingArgFlags out of sync"); 9810 9811 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9812 // registers are exhausted. 9813 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9814 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9815 "Can't lower f64 if it is split"); 9816 // Depending on available argument GPRS, f64 may be passed in a pair of 9817 // GPRs, split between a GPR and the stack, or passed completely on the 9818 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9819 // cases. 9820 Register Reg = State.AllocateReg(ArgGPRs); 9821 LocVT = MVT::i32; 9822 if (!Reg) { 9823 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9824 State.addLoc( 9825 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9826 return false; 9827 } 9828 if (!State.AllocateReg(ArgGPRs)) 9829 State.AllocateStack(4, Align(4)); 9830 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9831 return false; 9832 } 9833 9834 // Fixed-length vectors are located in the corresponding scalable-vector 9835 // container types. 9836 if (ValVT.isFixedLengthVector()) 9837 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9838 9839 // Split arguments might be passed indirectly, so keep track of the pending 9840 // values. Split vectors are passed via a mix of registers and indirectly, so 9841 // treat them as we would any other argument. 9842 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9843 LocVT = XLenVT; 9844 LocInfo = CCValAssign::Indirect; 9845 PendingLocs.push_back( 9846 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9847 PendingArgFlags.push_back(ArgFlags); 9848 if (!ArgFlags.isSplitEnd()) { 9849 return false; 9850 } 9851 } 9852 9853 // If the split argument only had two elements, it should be passed directly 9854 // in registers or on the stack. 9855 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9856 PendingLocs.size() <= 2) { 9857 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9858 // Apply the normal calling convention rules to the first half of the 9859 // split argument. 9860 CCValAssign VA = PendingLocs[0]; 9861 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9862 PendingLocs.clear(); 9863 PendingArgFlags.clear(); 9864 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9865 ArgFlags); 9866 } 9867 9868 // Allocate to a register if possible, or else a stack slot. 9869 Register Reg; 9870 unsigned StoreSizeBytes = XLen / 8; 9871 Align StackAlign = Align(XLen / 8); 9872 9873 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9874 Reg = State.AllocateReg(ArgFPR16s); 9875 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9876 Reg = State.AllocateReg(ArgFPR32s); 9877 else if (ValVT == MVT::f64 && !UseGPRForF64) 9878 Reg = State.AllocateReg(ArgFPR64s); 9879 else if (ValVT.isVector()) { 9880 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9881 if (!Reg) { 9882 // For return values, the vector must be passed fully via registers or 9883 // via the stack. 9884 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9885 // but we're using all of them. 9886 if (IsRet) 9887 return true; 9888 // Try using a GPR to pass the address 9889 if ((Reg = State.AllocateReg(ArgGPRs))) { 9890 LocVT = XLenVT; 9891 LocInfo = CCValAssign::Indirect; 9892 } else if (ValVT.isScalableVector()) { 9893 LocVT = XLenVT; 9894 LocInfo = CCValAssign::Indirect; 9895 } else { 9896 // Pass fixed-length vectors on the stack. 9897 LocVT = ValVT; 9898 StoreSizeBytes = ValVT.getStoreSize(); 9899 // Align vectors to their element sizes, being careful for vXi1 9900 // vectors. 9901 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9902 } 9903 } 9904 } else { 9905 Reg = State.AllocateReg(ArgGPRs); 9906 } 9907 9908 unsigned StackOffset = 9909 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9910 9911 // If we reach this point and PendingLocs is non-empty, we must be at the 9912 // end of a split argument that must be passed indirectly. 9913 if (!PendingLocs.empty()) { 9914 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9915 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9916 9917 for (auto &It : PendingLocs) { 9918 if (Reg) 9919 It.convertToReg(Reg); 9920 else 9921 It.convertToMem(StackOffset); 9922 State.addLoc(It); 9923 } 9924 PendingLocs.clear(); 9925 PendingArgFlags.clear(); 9926 return false; 9927 } 9928 9929 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9930 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9931 "Expected an XLenVT or vector types at this stage"); 9932 9933 if (Reg) { 9934 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9935 return false; 9936 } 9937 9938 // When a floating-point value is passed on the stack, no bit-conversion is 9939 // needed. 9940 if (ValVT.isFloatingPoint()) { 9941 LocVT = ValVT; 9942 LocInfo = CCValAssign::Full; 9943 } 9944 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9945 return false; 9946 } 9947 9948 template <typename ArgTy> 9949 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9950 for (const auto &ArgIdx : enumerate(Args)) { 9951 MVT ArgVT = ArgIdx.value().VT; 9952 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9953 return ArgIdx.index(); 9954 } 9955 return None; 9956 } 9957 9958 void RISCVTargetLowering::analyzeInputArgs( 9959 MachineFunction &MF, CCState &CCInfo, 9960 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9961 RISCVCCAssignFn Fn) const { 9962 unsigned NumArgs = Ins.size(); 9963 FunctionType *FType = MF.getFunction().getFunctionType(); 9964 9965 Optional<unsigned> FirstMaskArgument; 9966 if (Subtarget.hasVInstructions()) 9967 FirstMaskArgument = preAssignMask(Ins); 9968 9969 for (unsigned i = 0; i != NumArgs; ++i) { 9970 MVT ArgVT = Ins[i].VT; 9971 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9972 9973 Type *ArgTy = nullptr; 9974 if (IsRet) 9975 ArgTy = FType->getReturnType(); 9976 else if (Ins[i].isOrigArg()) 9977 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9978 9979 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9980 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9981 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9982 FirstMaskArgument)) { 9983 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9984 << EVT(ArgVT).getEVTString() << '\n'); 9985 llvm_unreachable(nullptr); 9986 } 9987 } 9988 } 9989 9990 void RISCVTargetLowering::analyzeOutputArgs( 9991 MachineFunction &MF, CCState &CCInfo, 9992 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9993 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9994 unsigned NumArgs = Outs.size(); 9995 9996 Optional<unsigned> FirstMaskArgument; 9997 if (Subtarget.hasVInstructions()) 9998 FirstMaskArgument = preAssignMask(Outs); 9999 10000 for (unsigned i = 0; i != NumArgs; i++) { 10001 MVT ArgVT = Outs[i].VT; 10002 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10003 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10004 10005 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10006 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10007 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10008 FirstMaskArgument)) { 10009 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10010 << EVT(ArgVT).getEVTString() << "\n"); 10011 llvm_unreachable(nullptr); 10012 } 10013 } 10014 } 10015 10016 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10017 // values. 10018 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10019 const CCValAssign &VA, const SDLoc &DL, 10020 const RISCVSubtarget &Subtarget) { 10021 switch (VA.getLocInfo()) { 10022 default: 10023 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10024 case CCValAssign::Full: 10025 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10026 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10027 break; 10028 case CCValAssign::BCvt: 10029 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10030 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10031 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10032 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10033 else 10034 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10035 break; 10036 } 10037 return Val; 10038 } 10039 10040 // The caller is responsible for loading the full value if the argument is 10041 // passed with CCValAssign::Indirect. 10042 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10043 const CCValAssign &VA, const SDLoc &DL, 10044 const RISCVTargetLowering &TLI) { 10045 MachineFunction &MF = DAG.getMachineFunction(); 10046 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10047 EVT LocVT = VA.getLocVT(); 10048 SDValue Val; 10049 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10050 Register VReg = RegInfo.createVirtualRegister(RC); 10051 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10052 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10053 10054 if (VA.getLocInfo() == CCValAssign::Indirect) 10055 return Val; 10056 10057 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10058 } 10059 10060 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10061 const CCValAssign &VA, const SDLoc &DL, 10062 const RISCVSubtarget &Subtarget) { 10063 EVT LocVT = VA.getLocVT(); 10064 10065 switch (VA.getLocInfo()) { 10066 default: 10067 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10068 case CCValAssign::Full: 10069 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10070 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10071 break; 10072 case CCValAssign::BCvt: 10073 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10074 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10075 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10076 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10077 else 10078 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10079 break; 10080 } 10081 return Val; 10082 } 10083 10084 // The caller is responsible for loading the full value if the argument is 10085 // passed with CCValAssign::Indirect. 10086 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10087 const CCValAssign &VA, const SDLoc &DL) { 10088 MachineFunction &MF = DAG.getMachineFunction(); 10089 MachineFrameInfo &MFI = MF.getFrameInfo(); 10090 EVT LocVT = VA.getLocVT(); 10091 EVT ValVT = VA.getValVT(); 10092 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10093 if (ValVT.isScalableVector()) { 10094 // When the value is a scalable vector, we save the pointer which points to 10095 // the scalable vector value in the stack. The ValVT will be the pointer 10096 // type, instead of the scalable vector type. 10097 ValVT = LocVT; 10098 } 10099 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10100 /*IsImmutable=*/true); 10101 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10102 SDValue Val; 10103 10104 ISD::LoadExtType ExtType; 10105 switch (VA.getLocInfo()) { 10106 default: 10107 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10108 case CCValAssign::Full: 10109 case CCValAssign::Indirect: 10110 case CCValAssign::BCvt: 10111 ExtType = ISD::NON_EXTLOAD; 10112 break; 10113 } 10114 Val = DAG.getExtLoad( 10115 ExtType, DL, LocVT, Chain, FIN, 10116 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10117 return Val; 10118 } 10119 10120 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10121 const CCValAssign &VA, const SDLoc &DL) { 10122 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10123 "Unexpected VA"); 10124 MachineFunction &MF = DAG.getMachineFunction(); 10125 MachineFrameInfo &MFI = MF.getFrameInfo(); 10126 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10127 10128 if (VA.isMemLoc()) { 10129 // f64 is passed on the stack. 10130 int FI = 10131 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10132 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10133 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10134 MachinePointerInfo::getFixedStack(MF, FI)); 10135 } 10136 10137 assert(VA.isRegLoc() && "Expected register VA assignment"); 10138 10139 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10140 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10141 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10142 SDValue Hi; 10143 if (VA.getLocReg() == RISCV::X17) { 10144 // Second half of f64 is passed on the stack. 10145 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10146 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10147 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10148 MachinePointerInfo::getFixedStack(MF, FI)); 10149 } else { 10150 // Second half of f64 is passed in another GPR. 10151 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10152 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10153 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10154 } 10155 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10156 } 10157 10158 // FastCC has less than 1% performance improvement for some particular 10159 // benchmark. But theoretically, it may has benenfit for some cases. 10160 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10161 unsigned ValNo, MVT ValVT, MVT LocVT, 10162 CCValAssign::LocInfo LocInfo, 10163 ISD::ArgFlagsTy ArgFlags, CCState &State, 10164 bool IsFixed, bool IsRet, Type *OrigTy, 10165 const RISCVTargetLowering &TLI, 10166 Optional<unsigned> FirstMaskArgument) { 10167 10168 // X5 and X6 might be used for save-restore libcall. 10169 static const MCPhysReg GPRList[] = { 10170 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10171 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10172 RISCV::X29, RISCV::X30, RISCV::X31}; 10173 10174 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10175 if (unsigned Reg = State.AllocateReg(GPRList)) { 10176 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10177 return false; 10178 } 10179 } 10180 10181 if (LocVT == MVT::f16) { 10182 static const MCPhysReg FPR16List[] = { 10183 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10184 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10185 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10186 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10187 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10188 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10189 return false; 10190 } 10191 } 10192 10193 if (LocVT == MVT::f32) { 10194 static const MCPhysReg FPR32List[] = { 10195 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10196 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10197 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10198 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10199 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10200 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10201 return false; 10202 } 10203 } 10204 10205 if (LocVT == MVT::f64) { 10206 static const MCPhysReg FPR64List[] = { 10207 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10208 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10209 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10210 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10211 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10212 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10213 return false; 10214 } 10215 } 10216 10217 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10218 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10219 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10220 return false; 10221 } 10222 10223 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10224 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10225 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10226 return false; 10227 } 10228 10229 if (LocVT.isVector()) { 10230 if (unsigned Reg = 10231 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10232 // Fixed-length vectors are located in the corresponding scalable-vector 10233 // container types. 10234 if (ValVT.isFixedLengthVector()) 10235 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10236 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10237 } else { 10238 // Try and pass the address via a "fast" GPR. 10239 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10240 LocInfo = CCValAssign::Indirect; 10241 LocVT = TLI.getSubtarget().getXLenVT(); 10242 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10243 } else if (ValVT.isFixedLengthVector()) { 10244 auto StackAlign = 10245 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10246 unsigned StackOffset = 10247 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10248 State.addLoc( 10249 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10250 } else { 10251 // Can't pass scalable vectors on the stack. 10252 return true; 10253 } 10254 } 10255 10256 return false; 10257 } 10258 10259 return true; // CC didn't match. 10260 } 10261 10262 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10263 CCValAssign::LocInfo LocInfo, 10264 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10265 10266 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10267 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10268 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10269 static const MCPhysReg GPRList[] = { 10270 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10271 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10272 if (unsigned Reg = State.AllocateReg(GPRList)) { 10273 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10274 return false; 10275 } 10276 } 10277 10278 if (LocVT == MVT::f32) { 10279 // Pass in STG registers: F1, ..., F6 10280 // fs0 ... fs5 10281 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10282 RISCV::F18_F, RISCV::F19_F, 10283 RISCV::F20_F, RISCV::F21_F}; 10284 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10285 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10286 return false; 10287 } 10288 } 10289 10290 if (LocVT == MVT::f64) { 10291 // Pass in STG registers: D1, ..., D6 10292 // fs6 ... fs11 10293 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10294 RISCV::F24_D, RISCV::F25_D, 10295 RISCV::F26_D, RISCV::F27_D}; 10296 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10297 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10298 return false; 10299 } 10300 } 10301 10302 report_fatal_error("No registers left in GHC calling convention"); 10303 return true; 10304 } 10305 10306 // Transform physical registers into virtual registers. 10307 SDValue RISCVTargetLowering::LowerFormalArguments( 10308 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10309 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10310 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10311 10312 MachineFunction &MF = DAG.getMachineFunction(); 10313 10314 switch (CallConv) { 10315 default: 10316 report_fatal_error("Unsupported calling convention"); 10317 case CallingConv::C: 10318 case CallingConv::Fast: 10319 break; 10320 case CallingConv::GHC: 10321 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10322 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10323 report_fatal_error( 10324 "GHC calling convention requires the F and D instruction set extensions"); 10325 } 10326 10327 const Function &Func = MF.getFunction(); 10328 if (Func.hasFnAttribute("interrupt")) { 10329 if (!Func.arg_empty()) 10330 report_fatal_error( 10331 "Functions with the interrupt attribute cannot have arguments!"); 10332 10333 StringRef Kind = 10334 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10335 10336 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10337 report_fatal_error( 10338 "Function interrupt attribute argument not supported!"); 10339 } 10340 10341 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10342 MVT XLenVT = Subtarget.getXLenVT(); 10343 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10344 // Used with vargs to acumulate store chains. 10345 std::vector<SDValue> OutChains; 10346 10347 // Assign locations to all of the incoming arguments. 10348 SmallVector<CCValAssign, 16> ArgLocs; 10349 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10350 10351 if (CallConv == CallingConv::GHC) 10352 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10353 else 10354 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10355 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10356 : CC_RISCV); 10357 10358 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10359 CCValAssign &VA = ArgLocs[i]; 10360 SDValue ArgValue; 10361 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10362 // case. 10363 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10364 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10365 else if (VA.isRegLoc()) 10366 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10367 else 10368 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10369 10370 if (VA.getLocInfo() == CCValAssign::Indirect) { 10371 // If the original argument was split and passed by reference (e.g. i128 10372 // on RV32), we need to load all parts of it here (using the same 10373 // address). Vectors may be partly split to registers and partly to the 10374 // stack, in which case the base address is partly offset and subsequent 10375 // stores are relative to that. 10376 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10377 MachinePointerInfo())); 10378 unsigned ArgIndex = Ins[i].OrigArgIndex; 10379 unsigned ArgPartOffset = Ins[i].PartOffset; 10380 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10381 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10382 CCValAssign &PartVA = ArgLocs[i + 1]; 10383 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10384 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10385 if (PartVA.getValVT().isScalableVector()) 10386 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10387 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10388 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10389 MachinePointerInfo())); 10390 ++i; 10391 } 10392 continue; 10393 } 10394 InVals.push_back(ArgValue); 10395 } 10396 10397 if (IsVarArg) { 10398 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10399 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10400 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10401 MachineFrameInfo &MFI = MF.getFrameInfo(); 10402 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10403 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10404 10405 // Offset of the first variable argument from stack pointer, and size of 10406 // the vararg save area. For now, the varargs save area is either zero or 10407 // large enough to hold a0-a7. 10408 int VaArgOffset, VarArgsSaveSize; 10409 10410 // If all registers are allocated, then all varargs must be passed on the 10411 // stack and we don't need to save any argregs. 10412 if (ArgRegs.size() == Idx) { 10413 VaArgOffset = CCInfo.getNextStackOffset(); 10414 VarArgsSaveSize = 0; 10415 } else { 10416 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10417 VaArgOffset = -VarArgsSaveSize; 10418 } 10419 10420 // Record the frame index of the first variable argument 10421 // which is a value necessary to VASTART. 10422 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10423 RVFI->setVarArgsFrameIndex(FI); 10424 10425 // If saving an odd number of registers then create an extra stack slot to 10426 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10427 // offsets to even-numbered registered remain 2*XLEN-aligned. 10428 if (Idx % 2) { 10429 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10430 VarArgsSaveSize += XLenInBytes; 10431 } 10432 10433 // Copy the integer registers that may have been used for passing varargs 10434 // to the vararg save area. 10435 for (unsigned I = Idx; I < ArgRegs.size(); 10436 ++I, VaArgOffset += XLenInBytes) { 10437 const Register Reg = RegInfo.createVirtualRegister(RC); 10438 RegInfo.addLiveIn(ArgRegs[I], Reg); 10439 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10440 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10441 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10442 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10443 MachinePointerInfo::getFixedStack(MF, FI)); 10444 cast<StoreSDNode>(Store.getNode()) 10445 ->getMemOperand() 10446 ->setValue((Value *)nullptr); 10447 OutChains.push_back(Store); 10448 } 10449 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10450 } 10451 10452 // All stores are grouped in one node to allow the matching between 10453 // the size of Ins and InVals. This only happens for vararg functions. 10454 if (!OutChains.empty()) { 10455 OutChains.push_back(Chain); 10456 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10457 } 10458 10459 return Chain; 10460 } 10461 10462 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10463 /// for tail call optimization. 10464 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10465 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10466 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10467 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10468 10469 auto &Callee = CLI.Callee; 10470 auto CalleeCC = CLI.CallConv; 10471 auto &Outs = CLI.Outs; 10472 auto &Caller = MF.getFunction(); 10473 auto CallerCC = Caller.getCallingConv(); 10474 10475 // Exception-handling functions need a special set of instructions to 10476 // indicate a return to the hardware. Tail-calling another function would 10477 // probably break this. 10478 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10479 // should be expanded as new function attributes are introduced. 10480 if (Caller.hasFnAttribute("interrupt")) 10481 return false; 10482 10483 // Do not tail call opt if the stack is used to pass parameters. 10484 if (CCInfo.getNextStackOffset() != 0) 10485 return false; 10486 10487 // Do not tail call opt if any parameters need to be passed indirectly. 10488 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10489 // passed indirectly. So the address of the value will be passed in a 10490 // register, or if not available, then the address is put on the stack. In 10491 // order to pass indirectly, space on the stack often needs to be allocated 10492 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10493 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10494 // are passed CCValAssign::Indirect. 10495 for (auto &VA : ArgLocs) 10496 if (VA.getLocInfo() == CCValAssign::Indirect) 10497 return false; 10498 10499 // Do not tail call opt if either caller or callee uses struct return 10500 // semantics. 10501 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10502 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10503 if (IsCallerStructRet || IsCalleeStructRet) 10504 return false; 10505 10506 // Externally-defined functions with weak linkage should not be 10507 // tail-called. The behaviour of branch instructions in this situation (as 10508 // used for tail calls) is implementation-defined, so we cannot rely on the 10509 // linker replacing the tail call with a return. 10510 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10511 const GlobalValue *GV = G->getGlobal(); 10512 if (GV->hasExternalWeakLinkage()) 10513 return false; 10514 } 10515 10516 // The callee has to preserve all registers the caller needs to preserve. 10517 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10518 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10519 if (CalleeCC != CallerCC) { 10520 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10521 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10522 return false; 10523 } 10524 10525 // Byval parameters hand the function a pointer directly into the stack area 10526 // we want to reuse during a tail call. Working around this *is* possible 10527 // but less efficient and uglier in LowerCall. 10528 for (auto &Arg : Outs) 10529 if (Arg.Flags.isByVal()) 10530 return false; 10531 10532 return true; 10533 } 10534 10535 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10536 return DAG.getDataLayout().getPrefTypeAlign( 10537 VT.getTypeForEVT(*DAG.getContext())); 10538 } 10539 10540 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10541 // and output parameter nodes. 10542 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10543 SmallVectorImpl<SDValue> &InVals) const { 10544 SelectionDAG &DAG = CLI.DAG; 10545 SDLoc &DL = CLI.DL; 10546 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10547 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10548 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10549 SDValue Chain = CLI.Chain; 10550 SDValue Callee = CLI.Callee; 10551 bool &IsTailCall = CLI.IsTailCall; 10552 CallingConv::ID CallConv = CLI.CallConv; 10553 bool IsVarArg = CLI.IsVarArg; 10554 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10555 MVT XLenVT = Subtarget.getXLenVT(); 10556 10557 MachineFunction &MF = DAG.getMachineFunction(); 10558 10559 // Analyze the operands of the call, assigning locations to each operand. 10560 SmallVector<CCValAssign, 16> ArgLocs; 10561 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10562 10563 if (CallConv == CallingConv::GHC) 10564 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10565 else 10566 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10567 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10568 : CC_RISCV); 10569 10570 // Check if it's really possible to do a tail call. 10571 if (IsTailCall) 10572 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10573 10574 if (IsTailCall) 10575 ++NumTailCalls; 10576 else if (CLI.CB && CLI.CB->isMustTailCall()) 10577 report_fatal_error("failed to perform tail call elimination on a call " 10578 "site marked musttail"); 10579 10580 // Get a count of how many bytes are to be pushed on the stack. 10581 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10582 10583 // Create local copies for byval args 10584 SmallVector<SDValue, 8> ByValArgs; 10585 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10586 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10587 if (!Flags.isByVal()) 10588 continue; 10589 10590 SDValue Arg = OutVals[i]; 10591 unsigned Size = Flags.getByValSize(); 10592 Align Alignment = Flags.getNonZeroByValAlign(); 10593 10594 int FI = 10595 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10596 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10597 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10598 10599 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10600 /*IsVolatile=*/false, 10601 /*AlwaysInline=*/false, IsTailCall, 10602 MachinePointerInfo(), MachinePointerInfo()); 10603 ByValArgs.push_back(FIPtr); 10604 } 10605 10606 if (!IsTailCall) 10607 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10608 10609 // Copy argument values to their designated locations. 10610 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10611 SmallVector<SDValue, 8> MemOpChains; 10612 SDValue StackPtr; 10613 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10614 CCValAssign &VA = ArgLocs[i]; 10615 SDValue ArgValue = OutVals[i]; 10616 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10617 10618 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10619 bool IsF64OnRV32DSoftABI = 10620 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10621 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10622 SDValue SplitF64 = DAG.getNode( 10623 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10624 SDValue Lo = SplitF64.getValue(0); 10625 SDValue Hi = SplitF64.getValue(1); 10626 10627 Register RegLo = VA.getLocReg(); 10628 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10629 10630 if (RegLo == RISCV::X17) { 10631 // Second half of f64 is passed on the stack. 10632 // Work out the address of the stack slot. 10633 if (!StackPtr.getNode()) 10634 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10635 // Emit the store. 10636 MemOpChains.push_back( 10637 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10638 } else { 10639 // Second half of f64 is passed in another GPR. 10640 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10641 Register RegHigh = RegLo + 1; 10642 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10643 } 10644 continue; 10645 } 10646 10647 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10648 // as any other MemLoc. 10649 10650 // Promote the value if needed. 10651 // For now, only handle fully promoted and indirect arguments. 10652 if (VA.getLocInfo() == CCValAssign::Indirect) { 10653 // Store the argument in a stack slot and pass its address. 10654 Align StackAlign = 10655 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10656 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10657 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10658 // If the original argument was split (e.g. i128), we need 10659 // to store the required parts of it here (and pass just one address). 10660 // Vectors may be partly split to registers and partly to the stack, in 10661 // which case the base address is partly offset and subsequent stores are 10662 // relative to that. 10663 unsigned ArgIndex = Outs[i].OrigArgIndex; 10664 unsigned ArgPartOffset = Outs[i].PartOffset; 10665 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10666 // Calculate the total size to store. We don't have access to what we're 10667 // actually storing other than performing the loop and collecting the 10668 // info. 10669 SmallVector<std::pair<SDValue, SDValue>> Parts; 10670 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10671 SDValue PartValue = OutVals[i + 1]; 10672 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10673 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10674 EVT PartVT = PartValue.getValueType(); 10675 if (PartVT.isScalableVector()) 10676 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10677 StoredSize += PartVT.getStoreSize(); 10678 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10679 Parts.push_back(std::make_pair(PartValue, Offset)); 10680 ++i; 10681 } 10682 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10683 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10684 MemOpChains.push_back( 10685 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10686 MachinePointerInfo::getFixedStack(MF, FI))); 10687 for (const auto &Part : Parts) { 10688 SDValue PartValue = Part.first; 10689 SDValue PartOffset = Part.second; 10690 SDValue Address = 10691 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10692 MemOpChains.push_back( 10693 DAG.getStore(Chain, DL, PartValue, Address, 10694 MachinePointerInfo::getFixedStack(MF, FI))); 10695 } 10696 ArgValue = SpillSlot; 10697 } else { 10698 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10699 } 10700 10701 // Use local copy if it is a byval arg. 10702 if (Flags.isByVal()) 10703 ArgValue = ByValArgs[j++]; 10704 10705 if (VA.isRegLoc()) { 10706 // Queue up the argument copies and emit them at the end. 10707 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10708 } else { 10709 assert(VA.isMemLoc() && "Argument not register or memory"); 10710 assert(!IsTailCall && "Tail call not allowed if stack is used " 10711 "for passing parameters"); 10712 10713 // Work out the address of the stack slot. 10714 if (!StackPtr.getNode()) 10715 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10716 SDValue Address = 10717 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10718 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10719 10720 // Emit the store. 10721 MemOpChains.push_back( 10722 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10723 } 10724 } 10725 10726 // Join the stores, which are independent of one another. 10727 if (!MemOpChains.empty()) 10728 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10729 10730 SDValue Glue; 10731 10732 // Build a sequence of copy-to-reg nodes, chained and glued together. 10733 for (auto &Reg : RegsToPass) { 10734 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10735 Glue = Chain.getValue(1); 10736 } 10737 10738 // Validate that none of the argument registers have been marked as 10739 // reserved, if so report an error. Do the same for the return address if this 10740 // is not a tailcall. 10741 validateCCReservedRegs(RegsToPass, MF); 10742 if (!IsTailCall && 10743 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10744 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10745 MF.getFunction(), 10746 "Return address register required, but has been reserved."}); 10747 10748 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10749 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10750 // split it and then direct call can be matched by PseudoCALL. 10751 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10752 const GlobalValue *GV = S->getGlobal(); 10753 10754 unsigned OpFlags = RISCVII::MO_CALL; 10755 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10756 OpFlags = RISCVII::MO_PLT; 10757 10758 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10759 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10760 unsigned OpFlags = RISCVII::MO_CALL; 10761 10762 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10763 nullptr)) 10764 OpFlags = RISCVII::MO_PLT; 10765 10766 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10767 } 10768 10769 // The first call operand is the chain and the second is the target address. 10770 SmallVector<SDValue, 8> Ops; 10771 Ops.push_back(Chain); 10772 Ops.push_back(Callee); 10773 10774 // Add argument registers to the end of the list so that they are 10775 // known live into the call. 10776 for (auto &Reg : RegsToPass) 10777 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10778 10779 if (!IsTailCall) { 10780 // Add a register mask operand representing the call-preserved registers. 10781 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10782 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10783 assert(Mask && "Missing call preserved mask for calling convention"); 10784 Ops.push_back(DAG.getRegisterMask(Mask)); 10785 } 10786 10787 // Glue the call to the argument copies, if any. 10788 if (Glue.getNode()) 10789 Ops.push_back(Glue); 10790 10791 // Emit the call. 10792 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10793 10794 if (IsTailCall) { 10795 MF.getFrameInfo().setHasTailCall(); 10796 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10797 } 10798 10799 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10800 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10801 Glue = Chain.getValue(1); 10802 10803 // Mark the end of the call, which is glued to the call itself. 10804 Chain = DAG.getCALLSEQ_END(Chain, 10805 DAG.getConstant(NumBytes, DL, PtrVT, true), 10806 DAG.getConstant(0, DL, PtrVT, true), 10807 Glue, DL); 10808 Glue = Chain.getValue(1); 10809 10810 // Assign locations to each value returned by this call. 10811 SmallVector<CCValAssign, 16> RVLocs; 10812 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10813 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10814 10815 // Copy all of the result registers out of their specified physreg. 10816 for (auto &VA : RVLocs) { 10817 // Copy the value out 10818 SDValue RetValue = 10819 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10820 // Glue the RetValue to the end of the call sequence 10821 Chain = RetValue.getValue(1); 10822 Glue = RetValue.getValue(2); 10823 10824 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10825 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10826 SDValue RetValue2 = 10827 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10828 Chain = RetValue2.getValue(1); 10829 Glue = RetValue2.getValue(2); 10830 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10831 RetValue2); 10832 } 10833 10834 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10835 10836 InVals.push_back(RetValue); 10837 } 10838 10839 return Chain; 10840 } 10841 10842 bool RISCVTargetLowering::CanLowerReturn( 10843 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10844 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10845 SmallVector<CCValAssign, 16> RVLocs; 10846 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10847 10848 Optional<unsigned> FirstMaskArgument; 10849 if (Subtarget.hasVInstructions()) 10850 FirstMaskArgument = preAssignMask(Outs); 10851 10852 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10853 MVT VT = Outs[i].VT; 10854 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10855 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10856 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10857 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10858 *this, FirstMaskArgument)) 10859 return false; 10860 } 10861 return true; 10862 } 10863 10864 SDValue 10865 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10866 bool IsVarArg, 10867 const SmallVectorImpl<ISD::OutputArg> &Outs, 10868 const SmallVectorImpl<SDValue> &OutVals, 10869 const SDLoc &DL, SelectionDAG &DAG) const { 10870 const MachineFunction &MF = DAG.getMachineFunction(); 10871 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10872 10873 // Stores the assignment of the return value to a location. 10874 SmallVector<CCValAssign, 16> RVLocs; 10875 10876 // Info about the registers and stack slot. 10877 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10878 *DAG.getContext()); 10879 10880 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10881 nullptr, CC_RISCV); 10882 10883 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10884 report_fatal_error("GHC functions return void only"); 10885 10886 SDValue Glue; 10887 SmallVector<SDValue, 4> RetOps(1, Chain); 10888 10889 // Copy the result values into the output registers. 10890 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10891 SDValue Val = OutVals[i]; 10892 CCValAssign &VA = RVLocs[i]; 10893 assert(VA.isRegLoc() && "Can only return in registers!"); 10894 10895 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10896 // Handle returning f64 on RV32D with a soft float ABI. 10897 assert(VA.isRegLoc() && "Expected return via registers"); 10898 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10899 DAG.getVTList(MVT::i32, MVT::i32), Val); 10900 SDValue Lo = SplitF64.getValue(0); 10901 SDValue Hi = SplitF64.getValue(1); 10902 Register RegLo = VA.getLocReg(); 10903 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10904 Register RegHi = RegLo + 1; 10905 10906 if (STI.isRegisterReservedByUser(RegLo) || 10907 STI.isRegisterReservedByUser(RegHi)) 10908 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10909 MF.getFunction(), 10910 "Return value register required, but has been reserved."}); 10911 10912 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10913 Glue = Chain.getValue(1); 10914 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10915 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10916 Glue = Chain.getValue(1); 10917 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10918 } else { 10919 // Handle a 'normal' return. 10920 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10921 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10922 10923 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10924 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10925 MF.getFunction(), 10926 "Return value register required, but has been reserved."}); 10927 10928 // Guarantee that all emitted copies are stuck together. 10929 Glue = Chain.getValue(1); 10930 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10931 } 10932 } 10933 10934 RetOps[0] = Chain; // Update chain. 10935 10936 // Add the glue node if we have it. 10937 if (Glue.getNode()) { 10938 RetOps.push_back(Glue); 10939 } 10940 10941 unsigned RetOpc = RISCVISD::RET_FLAG; 10942 // Interrupt service routines use different return instructions. 10943 const Function &Func = DAG.getMachineFunction().getFunction(); 10944 if (Func.hasFnAttribute("interrupt")) { 10945 if (!Func.getReturnType()->isVoidTy()) 10946 report_fatal_error( 10947 "Functions with the interrupt attribute must have void return type!"); 10948 10949 MachineFunction &MF = DAG.getMachineFunction(); 10950 StringRef Kind = 10951 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10952 10953 if (Kind == "user") 10954 RetOpc = RISCVISD::URET_FLAG; 10955 else if (Kind == "supervisor") 10956 RetOpc = RISCVISD::SRET_FLAG; 10957 else 10958 RetOpc = RISCVISD::MRET_FLAG; 10959 } 10960 10961 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10962 } 10963 10964 void RISCVTargetLowering::validateCCReservedRegs( 10965 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10966 MachineFunction &MF) const { 10967 const Function &F = MF.getFunction(); 10968 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10969 10970 if (llvm::any_of(Regs, [&STI](auto Reg) { 10971 return STI.isRegisterReservedByUser(Reg.first); 10972 })) 10973 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10974 F, "Argument register required, but has been reserved."}); 10975 } 10976 10977 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10978 return CI->isTailCall(); 10979 } 10980 10981 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10982 #define NODE_NAME_CASE(NODE) \ 10983 case RISCVISD::NODE: \ 10984 return "RISCVISD::" #NODE; 10985 // clang-format off 10986 switch ((RISCVISD::NodeType)Opcode) { 10987 case RISCVISD::FIRST_NUMBER: 10988 break; 10989 NODE_NAME_CASE(RET_FLAG) 10990 NODE_NAME_CASE(URET_FLAG) 10991 NODE_NAME_CASE(SRET_FLAG) 10992 NODE_NAME_CASE(MRET_FLAG) 10993 NODE_NAME_CASE(CALL) 10994 NODE_NAME_CASE(SELECT_CC) 10995 NODE_NAME_CASE(BR_CC) 10996 NODE_NAME_CASE(BuildPairF64) 10997 NODE_NAME_CASE(SplitF64) 10998 NODE_NAME_CASE(TAIL) 10999 NODE_NAME_CASE(MULHSU) 11000 NODE_NAME_CASE(SLLW) 11001 NODE_NAME_CASE(SRAW) 11002 NODE_NAME_CASE(SRLW) 11003 NODE_NAME_CASE(DIVW) 11004 NODE_NAME_CASE(DIVUW) 11005 NODE_NAME_CASE(REMUW) 11006 NODE_NAME_CASE(ROLW) 11007 NODE_NAME_CASE(RORW) 11008 NODE_NAME_CASE(CLZW) 11009 NODE_NAME_CASE(CTZW) 11010 NODE_NAME_CASE(FSLW) 11011 NODE_NAME_CASE(FSRW) 11012 NODE_NAME_CASE(FSL) 11013 NODE_NAME_CASE(FSR) 11014 NODE_NAME_CASE(FMV_H_X) 11015 NODE_NAME_CASE(FMV_X_ANYEXTH) 11016 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11017 NODE_NAME_CASE(FMV_W_X_RV64) 11018 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11019 NODE_NAME_CASE(FCVT_X) 11020 NODE_NAME_CASE(FCVT_XU) 11021 NODE_NAME_CASE(FCVT_W_RV64) 11022 NODE_NAME_CASE(FCVT_WU_RV64) 11023 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11024 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11025 NODE_NAME_CASE(READ_CYCLE_WIDE) 11026 NODE_NAME_CASE(GREV) 11027 NODE_NAME_CASE(GREVW) 11028 NODE_NAME_CASE(GORC) 11029 NODE_NAME_CASE(GORCW) 11030 NODE_NAME_CASE(SHFL) 11031 NODE_NAME_CASE(SHFLW) 11032 NODE_NAME_CASE(UNSHFL) 11033 NODE_NAME_CASE(UNSHFLW) 11034 NODE_NAME_CASE(BFP) 11035 NODE_NAME_CASE(BFPW) 11036 NODE_NAME_CASE(BCOMPRESS) 11037 NODE_NAME_CASE(BCOMPRESSW) 11038 NODE_NAME_CASE(BDECOMPRESS) 11039 NODE_NAME_CASE(BDECOMPRESSW) 11040 NODE_NAME_CASE(VMV_V_X_VL) 11041 NODE_NAME_CASE(VFMV_V_F_VL) 11042 NODE_NAME_CASE(VMV_X_S) 11043 NODE_NAME_CASE(VMV_S_X_VL) 11044 NODE_NAME_CASE(VFMV_S_F_VL) 11045 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11046 NODE_NAME_CASE(READ_VLENB) 11047 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11048 NODE_NAME_CASE(VSLIDEUP_VL) 11049 NODE_NAME_CASE(VSLIDE1UP_VL) 11050 NODE_NAME_CASE(VSLIDEDOWN_VL) 11051 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11052 NODE_NAME_CASE(VID_VL) 11053 NODE_NAME_CASE(VFNCVT_ROD_VL) 11054 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11055 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11056 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11057 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11058 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11059 NODE_NAME_CASE(VECREDUCE_AND_VL) 11060 NODE_NAME_CASE(VECREDUCE_OR_VL) 11061 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11062 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11063 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11064 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11065 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11066 NODE_NAME_CASE(ADD_VL) 11067 NODE_NAME_CASE(AND_VL) 11068 NODE_NAME_CASE(MUL_VL) 11069 NODE_NAME_CASE(OR_VL) 11070 NODE_NAME_CASE(SDIV_VL) 11071 NODE_NAME_CASE(SHL_VL) 11072 NODE_NAME_CASE(SREM_VL) 11073 NODE_NAME_CASE(SRA_VL) 11074 NODE_NAME_CASE(SRL_VL) 11075 NODE_NAME_CASE(SUB_VL) 11076 NODE_NAME_CASE(UDIV_VL) 11077 NODE_NAME_CASE(UREM_VL) 11078 NODE_NAME_CASE(XOR_VL) 11079 NODE_NAME_CASE(SADDSAT_VL) 11080 NODE_NAME_CASE(UADDSAT_VL) 11081 NODE_NAME_CASE(SSUBSAT_VL) 11082 NODE_NAME_CASE(USUBSAT_VL) 11083 NODE_NAME_CASE(FADD_VL) 11084 NODE_NAME_CASE(FSUB_VL) 11085 NODE_NAME_CASE(FMUL_VL) 11086 NODE_NAME_CASE(FDIV_VL) 11087 NODE_NAME_CASE(FNEG_VL) 11088 NODE_NAME_CASE(FABS_VL) 11089 NODE_NAME_CASE(FSQRT_VL) 11090 NODE_NAME_CASE(FMA_VL) 11091 NODE_NAME_CASE(FCOPYSIGN_VL) 11092 NODE_NAME_CASE(SMIN_VL) 11093 NODE_NAME_CASE(SMAX_VL) 11094 NODE_NAME_CASE(UMIN_VL) 11095 NODE_NAME_CASE(UMAX_VL) 11096 NODE_NAME_CASE(FMINNUM_VL) 11097 NODE_NAME_CASE(FMAXNUM_VL) 11098 NODE_NAME_CASE(MULHS_VL) 11099 NODE_NAME_CASE(MULHU_VL) 11100 NODE_NAME_CASE(FP_TO_SINT_VL) 11101 NODE_NAME_CASE(FP_TO_UINT_VL) 11102 NODE_NAME_CASE(SINT_TO_FP_VL) 11103 NODE_NAME_CASE(UINT_TO_FP_VL) 11104 NODE_NAME_CASE(FP_EXTEND_VL) 11105 NODE_NAME_CASE(FP_ROUND_VL) 11106 NODE_NAME_CASE(VWMUL_VL) 11107 NODE_NAME_CASE(VWMULU_VL) 11108 NODE_NAME_CASE(VWMULSU_VL) 11109 NODE_NAME_CASE(VWADD_VL) 11110 NODE_NAME_CASE(VWADDU_VL) 11111 NODE_NAME_CASE(VWSUB_VL) 11112 NODE_NAME_CASE(VWSUBU_VL) 11113 NODE_NAME_CASE(VWADD_W_VL) 11114 NODE_NAME_CASE(VWADDU_W_VL) 11115 NODE_NAME_CASE(VWSUB_W_VL) 11116 NODE_NAME_CASE(VWSUBU_W_VL) 11117 NODE_NAME_CASE(SETCC_VL) 11118 NODE_NAME_CASE(VSELECT_VL) 11119 NODE_NAME_CASE(VP_MERGE_VL) 11120 NODE_NAME_CASE(VMAND_VL) 11121 NODE_NAME_CASE(VMOR_VL) 11122 NODE_NAME_CASE(VMXOR_VL) 11123 NODE_NAME_CASE(VMCLR_VL) 11124 NODE_NAME_CASE(VMSET_VL) 11125 NODE_NAME_CASE(VRGATHER_VX_VL) 11126 NODE_NAME_CASE(VRGATHER_VV_VL) 11127 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11128 NODE_NAME_CASE(VSEXT_VL) 11129 NODE_NAME_CASE(VZEXT_VL) 11130 NODE_NAME_CASE(VCPOP_VL) 11131 NODE_NAME_CASE(READ_CSR) 11132 NODE_NAME_CASE(WRITE_CSR) 11133 NODE_NAME_CASE(SWAP_CSR) 11134 } 11135 // clang-format on 11136 return nullptr; 11137 #undef NODE_NAME_CASE 11138 } 11139 11140 /// getConstraintType - Given a constraint letter, return the type of 11141 /// constraint it is for this target. 11142 RISCVTargetLowering::ConstraintType 11143 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11144 if (Constraint.size() == 1) { 11145 switch (Constraint[0]) { 11146 default: 11147 break; 11148 case 'f': 11149 return C_RegisterClass; 11150 case 'I': 11151 case 'J': 11152 case 'K': 11153 return C_Immediate; 11154 case 'A': 11155 return C_Memory; 11156 case 'S': // A symbolic address 11157 return C_Other; 11158 } 11159 } else { 11160 if (Constraint == "vr" || Constraint == "vm") 11161 return C_RegisterClass; 11162 } 11163 return TargetLowering::getConstraintType(Constraint); 11164 } 11165 11166 std::pair<unsigned, const TargetRegisterClass *> 11167 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11168 StringRef Constraint, 11169 MVT VT) const { 11170 // First, see if this is a constraint that directly corresponds to a 11171 // RISCV register class. 11172 if (Constraint.size() == 1) { 11173 switch (Constraint[0]) { 11174 case 'r': 11175 // TODO: Support fixed vectors up to XLen for P extension? 11176 if (VT.isVector()) 11177 break; 11178 return std::make_pair(0U, &RISCV::GPRRegClass); 11179 case 'f': 11180 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11181 return std::make_pair(0U, &RISCV::FPR16RegClass); 11182 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11183 return std::make_pair(0U, &RISCV::FPR32RegClass); 11184 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11185 return std::make_pair(0U, &RISCV::FPR64RegClass); 11186 break; 11187 default: 11188 break; 11189 } 11190 } else if (Constraint == "vr") { 11191 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11192 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11193 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11194 return std::make_pair(0U, RC); 11195 } 11196 } else if (Constraint == "vm") { 11197 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11198 return std::make_pair(0U, &RISCV::VMV0RegClass); 11199 } 11200 11201 // Clang will correctly decode the usage of register name aliases into their 11202 // official names. However, other frontends like `rustc` do not. This allows 11203 // users of these frontends to use the ABI names for registers in LLVM-style 11204 // register constraints. 11205 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11206 .Case("{zero}", RISCV::X0) 11207 .Case("{ra}", RISCV::X1) 11208 .Case("{sp}", RISCV::X2) 11209 .Case("{gp}", RISCV::X3) 11210 .Case("{tp}", RISCV::X4) 11211 .Case("{t0}", RISCV::X5) 11212 .Case("{t1}", RISCV::X6) 11213 .Case("{t2}", RISCV::X7) 11214 .Cases("{s0}", "{fp}", RISCV::X8) 11215 .Case("{s1}", RISCV::X9) 11216 .Case("{a0}", RISCV::X10) 11217 .Case("{a1}", RISCV::X11) 11218 .Case("{a2}", RISCV::X12) 11219 .Case("{a3}", RISCV::X13) 11220 .Case("{a4}", RISCV::X14) 11221 .Case("{a5}", RISCV::X15) 11222 .Case("{a6}", RISCV::X16) 11223 .Case("{a7}", RISCV::X17) 11224 .Case("{s2}", RISCV::X18) 11225 .Case("{s3}", RISCV::X19) 11226 .Case("{s4}", RISCV::X20) 11227 .Case("{s5}", RISCV::X21) 11228 .Case("{s6}", RISCV::X22) 11229 .Case("{s7}", RISCV::X23) 11230 .Case("{s8}", RISCV::X24) 11231 .Case("{s9}", RISCV::X25) 11232 .Case("{s10}", RISCV::X26) 11233 .Case("{s11}", RISCV::X27) 11234 .Case("{t3}", RISCV::X28) 11235 .Case("{t4}", RISCV::X29) 11236 .Case("{t5}", RISCV::X30) 11237 .Case("{t6}", RISCV::X31) 11238 .Default(RISCV::NoRegister); 11239 if (XRegFromAlias != RISCV::NoRegister) 11240 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11241 11242 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11243 // TableGen record rather than the AsmName to choose registers for InlineAsm 11244 // constraints, plus we want to match those names to the widest floating point 11245 // register type available, manually select floating point registers here. 11246 // 11247 // The second case is the ABI name of the register, so that frontends can also 11248 // use the ABI names in register constraint lists. 11249 if (Subtarget.hasStdExtF()) { 11250 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11251 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11252 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11253 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11254 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11255 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11256 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11257 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11258 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11259 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11260 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11261 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11262 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11263 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11264 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11265 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11266 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11267 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11268 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11269 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11270 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11271 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11272 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11273 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11274 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11275 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11276 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11277 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11278 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11279 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11280 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11281 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11282 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11283 .Default(RISCV::NoRegister); 11284 if (FReg != RISCV::NoRegister) { 11285 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11286 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11287 unsigned RegNo = FReg - RISCV::F0_F; 11288 unsigned DReg = RISCV::F0_D + RegNo; 11289 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11290 } 11291 if (VT == MVT::f32 || VT == MVT::Other) 11292 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11293 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11294 unsigned RegNo = FReg - RISCV::F0_F; 11295 unsigned HReg = RISCV::F0_H + RegNo; 11296 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11297 } 11298 } 11299 } 11300 11301 if (Subtarget.hasVInstructions()) { 11302 Register VReg = StringSwitch<Register>(Constraint.lower()) 11303 .Case("{v0}", RISCV::V0) 11304 .Case("{v1}", RISCV::V1) 11305 .Case("{v2}", RISCV::V2) 11306 .Case("{v3}", RISCV::V3) 11307 .Case("{v4}", RISCV::V4) 11308 .Case("{v5}", RISCV::V5) 11309 .Case("{v6}", RISCV::V6) 11310 .Case("{v7}", RISCV::V7) 11311 .Case("{v8}", RISCV::V8) 11312 .Case("{v9}", RISCV::V9) 11313 .Case("{v10}", RISCV::V10) 11314 .Case("{v11}", RISCV::V11) 11315 .Case("{v12}", RISCV::V12) 11316 .Case("{v13}", RISCV::V13) 11317 .Case("{v14}", RISCV::V14) 11318 .Case("{v15}", RISCV::V15) 11319 .Case("{v16}", RISCV::V16) 11320 .Case("{v17}", RISCV::V17) 11321 .Case("{v18}", RISCV::V18) 11322 .Case("{v19}", RISCV::V19) 11323 .Case("{v20}", RISCV::V20) 11324 .Case("{v21}", RISCV::V21) 11325 .Case("{v22}", RISCV::V22) 11326 .Case("{v23}", RISCV::V23) 11327 .Case("{v24}", RISCV::V24) 11328 .Case("{v25}", RISCV::V25) 11329 .Case("{v26}", RISCV::V26) 11330 .Case("{v27}", RISCV::V27) 11331 .Case("{v28}", RISCV::V28) 11332 .Case("{v29}", RISCV::V29) 11333 .Case("{v30}", RISCV::V30) 11334 .Case("{v31}", RISCV::V31) 11335 .Default(RISCV::NoRegister); 11336 if (VReg != RISCV::NoRegister) { 11337 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11338 return std::make_pair(VReg, &RISCV::VMRegClass); 11339 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11340 return std::make_pair(VReg, &RISCV::VRRegClass); 11341 for (const auto *RC : 11342 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11343 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11344 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11345 return std::make_pair(VReg, RC); 11346 } 11347 } 11348 } 11349 } 11350 11351 std::pair<Register, const TargetRegisterClass *> Res = 11352 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11353 11354 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11355 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11356 // Subtarget into account. 11357 if (Res.second == &RISCV::GPRF16RegClass || 11358 Res.second == &RISCV::GPRF32RegClass || 11359 Res.second == &RISCV::GPRF64RegClass) 11360 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11361 11362 return Res; 11363 } 11364 11365 unsigned 11366 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11367 // Currently only support length 1 constraints. 11368 if (ConstraintCode.size() == 1) { 11369 switch (ConstraintCode[0]) { 11370 case 'A': 11371 return InlineAsm::Constraint_A; 11372 default: 11373 break; 11374 } 11375 } 11376 11377 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11378 } 11379 11380 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11381 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11382 SelectionDAG &DAG) const { 11383 // Currently only support length 1 constraints. 11384 if (Constraint.length() == 1) { 11385 switch (Constraint[0]) { 11386 case 'I': 11387 // Validate & create a 12-bit signed immediate operand. 11388 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11389 uint64_t CVal = C->getSExtValue(); 11390 if (isInt<12>(CVal)) 11391 Ops.push_back( 11392 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11393 } 11394 return; 11395 case 'J': 11396 // Validate & create an integer zero operand. 11397 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11398 if (C->getZExtValue() == 0) 11399 Ops.push_back( 11400 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11401 return; 11402 case 'K': 11403 // Validate & create a 5-bit unsigned immediate operand. 11404 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11405 uint64_t CVal = C->getZExtValue(); 11406 if (isUInt<5>(CVal)) 11407 Ops.push_back( 11408 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11409 } 11410 return; 11411 case 'S': 11412 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11413 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11414 GA->getValueType(0))); 11415 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11416 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11417 BA->getValueType(0))); 11418 } 11419 return; 11420 default: 11421 break; 11422 } 11423 } 11424 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11425 } 11426 11427 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11428 Instruction *Inst, 11429 AtomicOrdering Ord) const { 11430 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11431 return Builder.CreateFence(Ord); 11432 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11433 return Builder.CreateFence(AtomicOrdering::Release); 11434 return nullptr; 11435 } 11436 11437 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11438 Instruction *Inst, 11439 AtomicOrdering Ord) const { 11440 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11441 return Builder.CreateFence(AtomicOrdering::Acquire); 11442 return nullptr; 11443 } 11444 11445 TargetLowering::AtomicExpansionKind 11446 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11447 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11448 // point operations can't be used in an lr/sc sequence without breaking the 11449 // forward-progress guarantee. 11450 if (AI->isFloatingPointOperation()) 11451 return AtomicExpansionKind::CmpXChg; 11452 11453 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11454 if (Size == 8 || Size == 16) 11455 return AtomicExpansionKind::MaskedIntrinsic; 11456 return AtomicExpansionKind::None; 11457 } 11458 11459 static Intrinsic::ID 11460 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11461 if (XLen == 32) { 11462 switch (BinOp) { 11463 default: 11464 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11465 case AtomicRMWInst::Xchg: 11466 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11467 case AtomicRMWInst::Add: 11468 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11469 case AtomicRMWInst::Sub: 11470 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11471 case AtomicRMWInst::Nand: 11472 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11473 case AtomicRMWInst::Max: 11474 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11475 case AtomicRMWInst::Min: 11476 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11477 case AtomicRMWInst::UMax: 11478 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11479 case AtomicRMWInst::UMin: 11480 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11481 } 11482 } 11483 11484 if (XLen == 64) { 11485 switch (BinOp) { 11486 default: 11487 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11488 case AtomicRMWInst::Xchg: 11489 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11490 case AtomicRMWInst::Add: 11491 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11492 case AtomicRMWInst::Sub: 11493 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11494 case AtomicRMWInst::Nand: 11495 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11496 case AtomicRMWInst::Max: 11497 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11498 case AtomicRMWInst::Min: 11499 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11500 case AtomicRMWInst::UMax: 11501 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11502 case AtomicRMWInst::UMin: 11503 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11504 } 11505 } 11506 11507 llvm_unreachable("Unexpected XLen\n"); 11508 } 11509 11510 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11511 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11512 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11513 unsigned XLen = Subtarget.getXLen(); 11514 Value *Ordering = 11515 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11516 Type *Tys[] = {AlignedAddr->getType()}; 11517 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11518 AI->getModule(), 11519 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11520 11521 if (XLen == 64) { 11522 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11523 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11524 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11525 } 11526 11527 Value *Result; 11528 11529 // Must pass the shift amount needed to sign extend the loaded value prior 11530 // to performing a signed comparison for min/max. ShiftAmt is the number of 11531 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11532 // is the number of bits to left+right shift the value in order to 11533 // sign-extend. 11534 if (AI->getOperation() == AtomicRMWInst::Min || 11535 AI->getOperation() == AtomicRMWInst::Max) { 11536 const DataLayout &DL = AI->getModule()->getDataLayout(); 11537 unsigned ValWidth = 11538 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11539 Value *SextShamt = 11540 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11541 Result = Builder.CreateCall(LrwOpScwLoop, 11542 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11543 } else { 11544 Result = 11545 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11546 } 11547 11548 if (XLen == 64) 11549 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11550 return Result; 11551 } 11552 11553 TargetLowering::AtomicExpansionKind 11554 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11555 AtomicCmpXchgInst *CI) const { 11556 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11557 if (Size == 8 || Size == 16) 11558 return AtomicExpansionKind::MaskedIntrinsic; 11559 return AtomicExpansionKind::None; 11560 } 11561 11562 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11563 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11564 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11565 unsigned XLen = Subtarget.getXLen(); 11566 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11567 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11568 if (XLen == 64) { 11569 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11570 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11571 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11572 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11573 } 11574 Type *Tys[] = {AlignedAddr->getType()}; 11575 Function *MaskedCmpXchg = 11576 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11577 Value *Result = Builder.CreateCall( 11578 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11579 if (XLen == 64) 11580 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11581 return Result; 11582 } 11583 11584 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11585 return false; 11586 } 11587 11588 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11589 EVT VT) const { 11590 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11591 return false; 11592 11593 switch (FPVT.getSimpleVT().SimpleTy) { 11594 case MVT::f16: 11595 return Subtarget.hasStdExtZfh(); 11596 case MVT::f32: 11597 return Subtarget.hasStdExtF(); 11598 case MVT::f64: 11599 return Subtarget.hasStdExtD(); 11600 default: 11601 return false; 11602 } 11603 } 11604 11605 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11606 // If we are using the small code model, we can reduce size of jump table 11607 // entry to 4 bytes. 11608 if (Subtarget.is64Bit() && !isPositionIndependent() && 11609 getTargetMachine().getCodeModel() == CodeModel::Small) { 11610 return MachineJumpTableInfo::EK_Custom32; 11611 } 11612 return TargetLowering::getJumpTableEncoding(); 11613 } 11614 11615 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11616 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11617 unsigned uid, MCContext &Ctx) const { 11618 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11619 getTargetMachine().getCodeModel() == CodeModel::Small); 11620 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11621 } 11622 11623 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11624 EVT VT) const { 11625 VT = VT.getScalarType(); 11626 11627 if (!VT.isSimple()) 11628 return false; 11629 11630 switch (VT.getSimpleVT().SimpleTy) { 11631 case MVT::f16: 11632 return Subtarget.hasStdExtZfh(); 11633 case MVT::f32: 11634 return Subtarget.hasStdExtF(); 11635 case MVT::f64: 11636 return Subtarget.hasStdExtD(); 11637 default: 11638 break; 11639 } 11640 11641 return false; 11642 } 11643 11644 Register RISCVTargetLowering::getExceptionPointerRegister( 11645 const Constant *PersonalityFn) const { 11646 return RISCV::X10; 11647 } 11648 11649 Register RISCVTargetLowering::getExceptionSelectorRegister( 11650 const Constant *PersonalityFn) const { 11651 return RISCV::X11; 11652 } 11653 11654 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11655 // Return false to suppress the unnecessary extensions if the LibCall 11656 // arguments or return value is f32 type for LP64 ABI. 11657 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11658 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11659 return false; 11660 11661 return true; 11662 } 11663 11664 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11665 if (Subtarget.is64Bit() && Type == MVT::i32) 11666 return true; 11667 11668 return IsSigned; 11669 } 11670 11671 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11672 SDValue C) const { 11673 // Check integral scalar types. 11674 if (VT.isScalarInteger()) { 11675 // Omit the optimization if the sub target has the M extension and the data 11676 // size exceeds XLen. 11677 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11678 return false; 11679 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11680 // Break the MUL to a SLLI and an ADD/SUB. 11681 const APInt &Imm = ConstNode->getAPIntValue(); 11682 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11683 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11684 return true; 11685 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11686 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11687 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11688 (Imm - 8).isPowerOf2())) 11689 return true; 11690 // Omit the following optimization if the sub target has the M extension 11691 // and the data size >= XLen. 11692 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11693 return false; 11694 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11695 // a pair of LUI/ADDI. 11696 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11697 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11698 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11699 (1 - ImmS).isPowerOf2()) 11700 return true; 11701 } 11702 } 11703 } 11704 11705 return false; 11706 } 11707 11708 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11709 SDValue ConstNode) const { 11710 // Let the DAGCombiner decide for vectors. 11711 EVT VT = AddNode.getValueType(); 11712 if (VT.isVector()) 11713 return true; 11714 11715 // Let the DAGCombiner decide for larger types. 11716 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11717 return true; 11718 11719 // It is worse if c1 is simm12 while c1*c2 is not. 11720 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11721 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11722 const APInt &C1 = C1Node->getAPIntValue(); 11723 const APInt &C2 = C2Node->getAPIntValue(); 11724 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11725 return false; 11726 11727 // Default to true and let the DAGCombiner decide. 11728 return true; 11729 } 11730 11731 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11732 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11733 bool *Fast) const { 11734 if (!VT.isVector()) 11735 return false; 11736 11737 EVT ElemVT = VT.getVectorElementType(); 11738 if (Alignment >= ElemVT.getStoreSize()) { 11739 if (Fast) 11740 *Fast = true; 11741 return true; 11742 } 11743 11744 return false; 11745 } 11746 11747 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11748 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11749 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11750 bool IsABIRegCopy = CC.hasValue(); 11751 EVT ValueVT = Val.getValueType(); 11752 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11753 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11754 // and cast to f32. 11755 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11756 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11757 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11758 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11759 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11760 Parts[0] = Val; 11761 return true; 11762 } 11763 11764 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11765 LLVMContext &Context = *DAG.getContext(); 11766 EVT ValueEltVT = ValueVT.getVectorElementType(); 11767 EVT PartEltVT = PartVT.getVectorElementType(); 11768 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11769 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11770 if (PartVTBitSize % ValueVTBitSize == 0) { 11771 assert(PartVTBitSize >= ValueVTBitSize); 11772 // If the element types are different, bitcast to the same element type of 11773 // PartVT first. 11774 // Give an example here, we want copy a <vscale x 1 x i8> value to 11775 // <vscale x 4 x i16>. 11776 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11777 // subvector, then we can bitcast to <vscale x 4 x i16>. 11778 if (ValueEltVT != PartEltVT) { 11779 if (PartVTBitSize > ValueVTBitSize) { 11780 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11781 assert(Count != 0 && "The number of element should not be zero."); 11782 EVT SameEltTypeVT = 11783 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11784 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11785 DAG.getUNDEF(SameEltTypeVT), Val, 11786 DAG.getVectorIdxConstant(0, DL)); 11787 } 11788 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11789 } else { 11790 Val = 11791 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11792 Val, DAG.getVectorIdxConstant(0, DL)); 11793 } 11794 Parts[0] = Val; 11795 return true; 11796 } 11797 } 11798 return false; 11799 } 11800 11801 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11802 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11803 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11804 bool IsABIRegCopy = CC.hasValue(); 11805 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11806 SDValue Val = Parts[0]; 11807 11808 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11809 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11810 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11811 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11812 return Val; 11813 } 11814 11815 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11816 LLVMContext &Context = *DAG.getContext(); 11817 SDValue Val = Parts[0]; 11818 EVT ValueEltVT = ValueVT.getVectorElementType(); 11819 EVT PartEltVT = PartVT.getVectorElementType(); 11820 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11821 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11822 if (PartVTBitSize % ValueVTBitSize == 0) { 11823 assert(PartVTBitSize >= ValueVTBitSize); 11824 EVT SameEltTypeVT = ValueVT; 11825 // If the element types are different, convert it to the same element type 11826 // of PartVT. 11827 // Give an example here, we want copy a <vscale x 1 x i8> value from 11828 // <vscale x 4 x i16>. 11829 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11830 // then we can extract <vscale x 1 x i8>. 11831 if (ValueEltVT != PartEltVT) { 11832 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11833 assert(Count != 0 && "The number of element should not be zero."); 11834 SameEltTypeVT = 11835 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11836 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11837 } 11838 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11839 DAG.getVectorIdxConstant(0, DL)); 11840 return Val; 11841 } 11842 } 11843 return SDValue(); 11844 } 11845 11846 SDValue 11847 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11848 SelectionDAG &DAG, 11849 SmallVectorImpl<SDNode *> &Created) const { 11850 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11851 if (isIntDivCheap(N->getValueType(0), Attr)) 11852 return SDValue(N, 0); // Lower SDIV as SDIV 11853 11854 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11855 "Unexpected divisor!"); 11856 11857 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11858 if (!Subtarget.hasStdExtZbt()) 11859 return SDValue(); 11860 11861 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11862 // Besides, more critical path instructions will be generated when dividing 11863 // by 2. So we keep using the original DAGs for these cases. 11864 unsigned Lg2 = Divisor.countTrailingZeros(); 11865 if (Lg2 == 1 || Lg2 >= 12) 11866 return SDValue(); 11867 11868 // fold (sdiv X, pow2) 11869 EVT VT = N->getValueType(0); 11870 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11871 return SDValue(); 11872 11873 SDLoc DL(N); 11874 SDValue N0 = N->getOperand(0); 11875 SDValue Zero = DAG.getConstant(0, DL, VT); 11876 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11877 11878 // Add (N0 < 0) ? Pow2 - 1 : 0; 11879 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11880 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11881 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11882 11883 Created.push_back(Cmp.getNode()); 11884 Created.push_back(Add.getNode()); 11885 Created.push_back(Sel.getNode()); 11886 11887 // Divide by pow2. 11888 SDValue SRA = 11889 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11890 11891 // If we're dividing by a positive value, we're done. Otherwise, we must 11892 // negate the result. 11893 if (Divisor.isNonNegative()) 11894 return SRA; 11895 11896 Created.push_back(SRA.getNode()); 11897 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11898 } 11899 11900 #define GET_REGISTER_MATCHER 11901 #include "RISCVGenAsmMatcher.inc" 11902 11903 Register 11904 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11905 const MachineFunction &MF) const { 11906 Register Reg = MatchRegisterAltName(RegName); 11907 if (Reg == RISCV::NoRegister) 11908 Reg = MatchRegisterName(RegName); 11909 if (Reg == RISCV::NoRegister) 11910 report_fatal_error( 11911 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11912 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11913 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11914 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11915 StringRef(RegName) + "\".")); 11916 return Reg; 11917 } 11918 11919 namespace llvm { 11920 namespace RISCVVIntrinsicsTable { 11921 11922 #define GET_RISCVVIntrinsicsTable_IMPL 11923 #include "RISCVGenSearchableTables.inc" 11924 11925 } // namespace RISCVVIntrinsicsTable 11926 11927 } // namespace llvm 11928