1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT}; 494 495 static const unsigned FloatingPointVPOps[] = { 496 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 497 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 498 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 499 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 500 501 if (!Subtarget.is64Bit()) { 502 // We must custom-lower certain vXi64 operations on RV32 due to the vector 503 // element type being illegal. 504 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 505 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 506 507 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 508 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 509 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 512 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 513 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 515 516 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 517 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 518 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 521 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 522 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 524 } 525 526 for (MVT VT : BoolVecVTs) { 527 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 528 529 // Mask VTs are custom-expanded into a series of standard nodes 530 setOperationAction(ISD::TRUNCATE, VT, Custom); 531 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 532 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 533 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 534 535 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 536 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 537 538 setOperationAction(ISD::SELECT, VT, Custom); 539 setOperationAction(ISD::SELECT_CC, VT, Expand); 540 setOperationAction(ISD::VSELECT, VT, Expand); 541 setOperationAction(ISD::VP_MERGE, VT, Expand); 542 setOperationAction(ISD::VP_SELECT, VT, Expand); 543 544 setOperationAction(ISD::VP_AND, VT, Custom); 545 setOperationAction(ISD::VP_OR, VT, Custom); 546 setOperationAction(ISD::VP_XOR, VT, Custom); 547 548 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 549 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 550 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 551 552 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 553 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 554 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 555 556 // RVV has native int->float & float->int conversions where the 557 // element type sizes are within one power-of-two of each other. Any 558 // wider distances between type sizes have to be lowered as sequences 559 // which progressively narrow the gap in stages. 560 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 561 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 562 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 563 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 564 565 // Expand all extending loads to types larger than this, and truncating 566 // stores from types larger than this. 567 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 568 setTruncStoreAction(OtherVT, VT, Expand); 569 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 570 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 571 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 572 } 573 } 574 575 for (MVT VT : IntVecVTs) { 576 if (VT.getVectorElementType() == MVT::i64 && 577 !Subtarget.hasVInstructionsI64()) 578 continue; 579 580 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 581 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 582 583 // Vectors implement MULHS/MULHU. 584 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 585 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 586 587 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 588 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 589 setOperationAction(ISD::MULHU, VT, Expand); 590 setOperationAction(ISD::MULHS, VT, Expand); 591 } 592 593 setOperationAction(ISD::SMIN, VT, Legal); 594 setOperationAction(ISD::SMAX, VT, Legal); 595 setOperationAction(ISD::UMIN, VT, Legal); 596 setOperationAction(ISD::UMAX, VT, Legal); 597 598 setOperationAction(ISD::ROTL, VT, Expand); 599 setOperationAction(ISD::ROTR, VT, Expand); 600 601 setOperationAction(ISD::CTTZ, VT, Expand); 602 setOperationAction(ISD::CTLZ, VT, Expand); 603 setOperationAction(ISD::CTPOP, VT, Expand); 604 605 setOperationAction(ISD::BSWAP, VT, Expand); 606 607 // Custom-lower extensions and truncations from/to mask types. 608 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 609 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 610 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 611 612 // RVV has native int->float & float->int conversions where the 613 // element type sizes are within one power-of-two of each other. Any 614 // wider distances between type sizes have to be lowered as sequences 615 // which progressively narrow the gap in stages. 616 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 617 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 618 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 619 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 620 621 setOperationAction(ISD::SADDSAT, VT, Legal); 622 setOperationAction(ISD::UADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::USUBSAT, VT, Legal); 625 626 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 627 // nodes which truncate by one power of two at a time. 628 setOperationAction(ISD::TRUNCATE, VT, Custom); 629 630 // Custom-lower insert/extract operations to simplify patterns. 631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 633 634 // Custom-lower reduction operations to set up the corresponding custom 635 // nodes' operands. 636 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 644 645 for (unsigned VPOpc : IntegerVPOps) 646 setOperationAction(VPOpc, VT, Custom); 647 648 setOperationAction(ISD::LOAD, VT, Custom); 649 setOperationAction(ISD::STORE, VT, Custom); 650 651 setOperationAction(ISD::MLOAD, VT, Custom); 652 setOperationAction(ISD::MSTORE, VT, Custom); 653 setOperationAction(ISD::MGATHER, VT, Custom); 654 setOperationAction(ISD::MSCATTER, VT, Custom); 655 656 setOperationAction(ISD::VP_LOAD, VT, Custom); 657 setOperationAction(ISD::VP_STORE, VT, Custom); 658 setOperationAction(ISD::VP_GATHER, VT, Custom); 659 setOperationAction(ISD::VP_SCATTER, VT, Custom); 660 661 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 662 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 663 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 664 665 setOperationAction(ISD::SELECT, VT, Custom); 666 setOperationAction(ISD::SELECT_CC, VT, Expand); 667 668 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 669 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 670 671 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 672 setTruncStoreAction(VT, OtherVT, Expand); 673 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 674 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 675 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 676 } 677 678 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 679 // type that can represent the value exactly. 680 if (VT.getVectorElementType() != MVT::i64) { 681 MVT FloatEltVT = 682 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 683 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 684 if (isTypeLegal(FloatVT)) { 685 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 686 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 687 } 688 } 689 } 690 691 // Expand various CCs to best match the RVV ISA, which natively supports UNE 692 // but no other unordered comparisons, and supports all ordered comparisons 693 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 694 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 695 // and we pattern-match those back to the "original", swapping operands once 696 // more. This way we catch both operations and both "vf" and "fv" forms with 697 // fewer patterns. 698 static const ISD::CondCode VFPCCToExpand[] = { 699 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 700 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 701 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 702 }; 703 704 // Sets common operation actions on RVV floating-point vector types. 705 const auto SetCommonVFPActions = [&](MVT VT) { 706 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 707 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 708 // sizes are within one power-of-two of each other. Therefore conversions 709 // between vXf16 and vXf64 must be lowered as sequences which convert via 710 // vXf32. 711 setOperationAction(ISD::FP_ROUND, VT, Custom); 712 setOperationAction(ISD::FP_EXTEND, VT, Custom); 713 // Custom-lower insert/extract operations to simplify patterns. 714 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 716 // Expand various condition codes (explained above). 717 for (auto CC : VFPCCToExpand) 718 setCondCodeAction(CC, VT, Expand); 719 720 setOperationAction(ISD::FMINNUM, VT, Legal); 721 setOperationAction(ISD::FMAXNUM, VT, Legal); 722 723 setOperationAction(ISD::FTRUNC, VT, Custom); 724 setOperationAction(ISD::FCEIL, VT, Custom); 725 setOperationAction(ISD::FFLOOR, VT, Custom); 726 setOperationAction(ISD::FROUND, VT, Custom); 727 728 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 729 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 730 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 731 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 732 733 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 734 735 setOperationAction(ISD::LOAD, VT, Custom); 736 setOperationAction(ISD::STORE, VT, Custom); 737 738 setOperationAction(ISD::MLOAD, VT, Custom); 739 setOperationAction(ISD::MSTORE, VT, Custom); 740 setOperationAction(ISD::MGATHER, VT, Custom); 741 setOperationAction(ISD::MSCATTER, VT, Custom); 742 743 setOperationAction(ISD::VP_LOAD, VT, Custom); 744 setOperationAction(ISD::VP_STORE, VT, Custom); 745 setOperationAction(ISD::VP_GATHER, VT, Custom); 746 setOperationAction(ISD::VP_SCATTER, VT, Custom); 747 748 setOperationAction(ISD::SELECT, VT, Custom); 749 setOperationAction(ISD::SELECT_CC, VT, Expand); 750 751 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 752 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 753 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 754 755 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 756 757 for (unsigned VPOpc : FloatingPointVPOps) 758 setOperationAction(VPOpc, VT, Custom); 759 }; 760 761 // Sets common extload/truncstore actions on RVV floating-point vector 762 // types. 763 const auto SetCommonVFPExtLoadTruncStoreActions = 764 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 765 for (auto SmallVT : SmallerVTs) { 766 setTruncStoreAction(VT, SmallVT, Expand); 767 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 768 } 769 }; 770 771 if (Subtarget.hasVInstructionsF16()) 772 for (MVT VT : F16VecVTs) 773 SetCommonVFPActions(VT); 774 775 for (MVT VT : F32VecVTs) { 776 if (Subtarget.hasVInstructionsF32()) 777 SetCommonVFPActions(VT); 778 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 779 } 780 781 for (MVT VT : F64VecVTs) { 782 if (Subtarget.hasVInstructionsF64()) 783 SetCommonVFPActions(VT); 784 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 785 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 786 } 787 788 if (Subtarget.useRVVForFixedLengthVectors()) { 789 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 790 if (!useRVVForFixedLengthVectorVT(VT)) 791 continue; 792 793 // By default everything must be expanded. 794 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 795 setOperationAction(Op, VT, Expand); 796 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 797 setTruncStoreAction(VT, OtherVT, Expand); 798 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 799 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 800 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 801 } 802 803 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 804 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 805 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 806 807 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 808 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 809 810 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 812 813 setOperationAction(ISD::LOAD, VT, Custom); 814 setOperationAction(ISD::STORE, VT, Custom); 815 816 setOperationAction(ISD::SETCC, VT, Custom); 817 818 setOperationAction(ISD::SELECT, VT, Custom); 819 820 setOperationAction(ISD::TRUNCATE, VT, Custom); 821 822 setOperationAction(ISD::BITCAST, VT, Custom); 823 824 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 825 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 826 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 827 828 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 829 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 830 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 831 832 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 833 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 834 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 835 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 836 837 // Operations below are different for between masks and other vectors. 838 if (VT.getVectorElementType() == MVT::i1) { 839 setOperationAction(ISD::VP_AND, VT, Custom); 840 setOperationAction(ISD::VP_OR, VT, Custom); 841 setOperationAction(ISD::VP_XOR, VT, Custom); 842 setOperationAction(ISD::AND, VT, Custom); 843 setOperationAction(ISD::OR, VT, Custom); 844 setOperationAction(ISD::XOR, VT, Custom); 845 continue; 846 } 847 848 // Use SPLAT_VECTOR to prevent type legalization from destroying the 849 // splats when type legalizing i64 scalar on RV32. 850 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 851 // improvements first. 852 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 853 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 854 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 855 } 856 857 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 858 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 859 860 setOperationAction(ISD::MLOAD, VT, Custom); 861 setOperationAction(ISD::MSTORE, VT, Custom); 862 setOperationAction(ISD::MGATHER, VT, Custom); 863 setOperationAction(ISD::MSCATTER, VT, Custom); 864 865 setOperationAction(ISD::VP_LOAD, VT, Custom); 866 setOperationAction(ISD::VP_STORE, VT, Custom); 867 setOperationAction(ISD::VP_GATHER, VT, Custom); 868 setOperationAction(ISD::VP_SCATTER, VT, Custom); 869 870 setOperationAction(ISD::ADD, VT, Custom); 871 setOperationAction(ISD::MUL, VT, Custom); 872 setOperationAction(ISD::SUB, VT, Custom); 873 setOperationAction(ISD::AND, VT, Custom); 874 setOperationAction(ISD::OR, VT, Custom); 875 setOperationAction(ISD::XOR, VT, Custom); 876 setOperationAction(ISD::SDIV, VT, Custom); 877 setOperationAction(ISD::SREM, VT, Custom); 878 setOperationAction(ISD::UDIV, VT, Custom); 879 setOperationAction(ISD::UREM, VT, Custom); 880 setOperationAction(ISD::SHL, VT, Custom); 881 setOperationAction(ISD::SRA, VT, Custom); 882 setOperationAction(ISD::SRL, VT, Custom); 883 884 setOperationAction(ISD::SMIN, VT, Custom); 885 setOperationAction(ISD::SMAX, VT, Custom); 886 setOperationAction(ISD::UMIN, VT, Custom); 887 setOperationAction(ISD::UMAX, VT, Custom); 888 setOperationAction(ISD::ABS, VT, Custom); 889 890 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 891 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 892 setOperationAction(ISD::MULHS, VT, Custom); 893 setOperationAction(ISD::MULHU, VT, Custom); 894 } 895 896 setOperationAction(ISD::SADDSAT, VT, Custom); 897 setOperationAction(ISD::UADDSAT, VT, Custom); 898 setOperationAction(ISD::SSUBSAT, VT, Custom); 899 setOperationAction(ISD::USUBSAT, VT, Custom); 900 901 setOperationAction(ISD::VSELECT, VT, Custom); 902 setOperationAction(ISD::SELECT_CC, VT, Expand); 903 904 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 905 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 906 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 907 908 // Custom-lower reduction operations to set up the corresponding custom 909 // nodes' operands. 910 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 911 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 912 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 913 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 914 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 915 916 for (unsigned VPOpc : IntegerVPOps) 917 setOperationAction(VPOpc, VT, Custom); 918 919 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 920 // type that can represent the value exactly. 921 if (VT.getVectorElementType() != MVT::i64) { 922 MVT FloatEltVT = 923 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 924 EVT FloatVT = 925 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 926 if (isTypeLegal(FloatVT)) { 927 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 928 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 929 } 930 } 931 } 932 933 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 934 if (!useRVVForFixedLengthVectorVT(VT)) 935 continue; 936 937 // By default everything must be expanded. 938 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 939 setOperationAction(Op, VT, Expand); 940 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 941 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 942 setTruncStoreAction(VT, OtherVT, Expand); 943 } 944 945 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 946 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 947 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 948 949 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 950 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 951 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 952 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 953 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 954 955 setOperationAction(ISD::LOAD, VT, Custom); 956 setOperationAction(ISD::STORE, VT, Custom); 957 setOperationAction(ISD::MLOAD, VT, Custom); 958 setOperationAction(ISD::MSTORE, VT, Custom); 959 setOperationAction(ISD::MGATHER, VT, Custom); 960 setOperationAction(ISD::MSCATTER, VT, Custom); 961 962 setOperationAction(ISD::VP_LOAD, VT, Custom); 963 setOperationAction(ISD::VP_STORE, VT, Custom); 964 setOperationAction(ISD::VP_GATHER, VT, Custom); 965 setOperationAction(ISD::VP_SCATTER, VT, Custom); 966 967 setOperationAction(ISD::FADD, VT, Custom); 968 setOperationAction(ISD::FSUB, VT, Custom); 969 setOperationAction(ISD::FMUL, VT, Custom); 970 setOperationAction(ISD::FDIV, VT, Custom); 971 setOperationAction(ISD::FNEG, VT, Custom); 972 setOperationAction(ISD::FABS, VT, Custom); 973 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 974 setOperationAction(ISD::FSQRT, VT, Custom); 975 setOperationAction(ISD::FMA, VT, Custom); 976 setOperationAction(ISD::FMINNUM, VT, Custom); 977 setOperationAction(ISD::FMAXNUM, VT, Custom); 978 979 setOperationAction(ISD::FP_ROUND, VT, Custom); 980 setOperationAction(ISD::FP_EXTEND, VT, Custom); 981 982 setOperationAction(ISD::FTRUNC, VT, Custom); 983 setOperationAction(ISD::FCEIL, VT, Custom); 984 setOperationAction(ISD::FFLOOR, VT, Custom); 985 setOperationAction(ISD::FROUND, VT, Custom); 986 987 for (auto CC : VFPCCToExpand) 988 setCondCodeAction(CC, VT, Expand); 989 990 setOperationAction(ISD::VSELECT, VT, Custom); 991 setOperationAction(ISD::SELECT, VT, Custom); 992 setOperationAction(ISD::SELECT_CC, VT, Expand); 993 994 setOperationAction(ISD::BITCAST, VT, Custom); 995 996 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 997 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 998 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 999 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1000 1001 for (unsigned VPOpc : FloatingPointVPOps) 1002 setOperationAction(VPOpc, VT, Custom); 1003 } 1004 1005 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1006 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1007 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1008 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1009 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1010 if (Subtarget.hasStdExtZfh()) 1011 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1012 if (Subtarget.hasStdExtF()) 1013 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1014 if (Subtarget.hasStdExtD()) 1015 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1016 } 1017 } 1018 1019 // Function alignments. 1020 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1021 setMinFunctionAlignment(FunctionAlignment); 1022 setPrefFunctionAlignment(FunctionAlignment); 1023 1024 setMinimumJumpTableEntries(5); 1025 1026 // Jumps are expensive, compared to logic 1027 setJumpIsExpensive(); 1028 1029 setTargetDAGCombine(ISD::ADD); 1030 setTargetDAGCombine(ISD::SUB); 1031 setTargetDAGCombine(ISD::AND); 1032 setTargetDAGCombine(ISD::OR); 1033 setTargetDAGCombine(ISD::XOR); 1034 if (Subtarget.hasStdExtZbp()) { 1035 setTargetDAGCombine(ISD::ROTL); 1036 setTargetDAGCombine(ISD::ROTR); 1037 } 1038 setTargetDAGCombine(ISD::ANY_EXTEND); 1039 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1040 if (Subtarget.hasStdExtZfh()) 1041 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1042 if (Subtarget.hasStdExtF()) { 1043 setTargetDAGCombine(ISD::ZERO_EXTEND); 1044 setTargetDAGCombine(ISD::FP_TO_SINT); 1045 setTargetDAGCombine(ISD::FP_TO_UINT); 1046 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1047 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1048 } 1049 if (Subtarget.hasVInstructions()) { 1050 setTargetDAGCombine(ISD::FCOPYSIGN); 1051 setTargetDAGCombine(ISD::MGATHER); 1052 setTargetDAGCombine(ISD::MSCATTER); 1053 setTargetDAGCombine(ISD::VP_GATHER); 1054 setTargetDAGCombine(ISD::VP_SCATTER); 1055 setTargetDAGCombine(ISD::SRA); 1056 setTargetDAGCombine(ISD::SRL); 1057 setTargetDAGCombine(ISD::SHL); 1058 setTargetDAGCombine(ISD::STORE); 1059 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1060 } 1061 1062 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1063 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1064 } 1065 1066 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1067 LLVMContext &Context, 1068 EVT VT) const { 1069 if (!VT.isVector()) 1070 return getPointerTy(DL); 1071 if (Subtarget.hasVInstructions() && 1072 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1073 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1074 return VT.changeVectorElementTypeToInteger(); 1075 } 1076 1077 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1078 return Subtarget.getXLenVT(); 1079 } 1080 1081 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1082 const CallInst &I, 1083 MachineFunction &MF, 1084 unsigned Intrinsic) const { 1085 auto &DL = I.getModule()->getDataLayout(); 1086 switch (Intrinsic) { 1087 default: 1088 return false; 1089 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1090 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1091 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1092 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1093 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1094 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1097 case Intrinsic::riscv_masked_cmpxchg_i32: 1098 Info.opc = ISD::INTRINSIC_W_CHAIN; 1099 Info.memVT = MVT::i32; 1100 Info.ptrVal = I.getArgOperand(0); 1101 Info.offset = 0; 1102 Info.align = Align(4); 1103 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1104 MachineMemOperand::MOVolatile; 1105 return true; 1106 case Intrinsic::riscv_masked_strided_load: 1107 Info.opc = ISD::INTRINSIC_W_CHAIN; 1108 Info.ptrVal = I.getArgOperand(1); 1109 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1110 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1111 Info.size = MemoryLocation::UnknownSize; 1112 Info.flags |= MachineMemOperand::MOLoad; 1113 return true; 1114 case Intrinsic::riscv_masked_strided_store: 1115 Info.opc = ISD::INTRINSIC_VOID; 1116 Info.ptrVal = I.getArgOperand(1); 1117 Info.memVT = 1118 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1119 Info.align = Align( 1120 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1121 8); 1122 Info.size = MemoryLocation::UnknownSize; 1123 Info.flags |= MachineMemOperand::MOStore; 1124 return true; 1125 } 1126 } 1127 1128 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1129 const AddrMode &AM, Type *Ty, 1130 unsigned AS, 1131 Instruction *I) const { 1132 // No global is ever allowed as a base. 1133 if (AM.BaseGV) 1134 return false; 1135 1136 // Require a 12-bit signed offset. 1137 if (!isInt<12>(AM.BaseOffs)) 1138 return false; 1139 1140 switch (AM.Scale) { 1141 case 0: // "r+i" or just "i", depending on HasBaseReg. 1142 break; 1143 case 1: 1144 if (!AM.HasBaseReg) // allow "r+i". 1145 break; 1146 return false; // disallow "r+r" or "r+r+i". 1147 default: 1148 return false; 1149 } 1150 1151 return true; 1152 } 1153 1154 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1155 return isInt<12>(Imm); 1156 } 1157 1158 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1159 return isInt<12>(Imm); 1160 } 1161 1162 // On RV32, 64-bit integers are split into their high and low parts and held 1163 // in two different registers, so the trunc is free since the low register can 1164 // just be used. 1165 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1166 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1167 return false; 1168 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1169 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1170 return (SrcBits == 64 && DestBits == 32); 1171 } 1172 1173 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1174 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1175 !SrcVT.isInteger() || !DstVT.isInteger()) 1176 return false; 1177 unsigned SrcBits = SrcVT.getSizeInBits(); 1178 unsigned DestBits = DstVT.getSizeInBits(); 1179 return (SrcBits == 64 && DestBits == 32); 1180 } 1181 1182 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1183 // Zexts are free if they can be combined with a load. 1184 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1185 // poorly with type legalization of compares preferring sext. 1186 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1187 EVT MemVT = LD->getMemoryVT(); 1188 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1189 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1190 LD->getExtensionType() == ISD::ZEXTLOAD)) 1191 return true; 1192 } 1193 1194 return TargetLowering::isZExtFree(Val, VT2); 1195 } 1196 1197 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1198 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1199 } 1200 1201 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1202 return Subtarget.hasStdExtZbb(); 1203 } 1204 1205 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1206 return Subtarget.hasStdExtZbb(); 1207 } 1208 1209 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1210 EVT VT = Y.getValueType(); 1211 1212 // FIXME: Support vectors once we have tests. 1213 if (VT.isVector()) 1214 return false; 1215 1216 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1217 Subtarget.hasStdExtZbkb()) && 1218 !isa<ConstantSDNode>(Y); 1219 } 1220 1221 /// Check if sinking \p I's operands to I's basic block is profitable, because 1222 /// the operands can be folded into a target instruction, e.g. 1223 /// splats of scalars can fold into vector instructions. 1224 bool RISCVTargetLowering::shouldSinkOperands( 1225 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1226 using namespace llvm::PatternMatch; 1227 1228 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1229 return false; 1230 1231 auto IsSinker = [&](Instruction *I, int Operand) { 1232 switch (I->getOpcode()) { 1233 case Instruction::Add: 1234 case Instruction::Sub: 1235 case Instruction::Mul: 1236 case Instruction::And: 1237 case Instruction::Or: 1238 case Instruction::Xor: 1239 case Instruction::FAdd: 1240 case Instruction::FSub: 1241 case Instruction::FMul: 1242 case Instruction::FDiv: 1243 case Instruction::ICmp: 1244 case Instruction::FCmp: 1245 return true; 1246 case Instruction::Shl: 1247 case Instruction::LShr: 1248 case Instruction::AShr: 1249 case Instruction::UDiv: 1250 case Instruction::SDiv: 1251 case Instruction::URem: 1252 case Instruction::SRem: 1253 return Operand == 1; 1254 case Instruction::Call: 1255 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1256 switch (II->getIntrinsicID()) { 1257 case Intrinsic::fma: 1258 case Intrinsic::vp_fma: 1259 return Operand == 0 || Operand == 1; 1260 // FIXME: Our patterns can only match vx/vf instructions when the splat 1261 // it on the RHS, because TableGen doesn't recognize our VP operations 1262 // as commutative. 1263 case Intrinsic::vp_add: 1264 case Intrinsic::vp_mul: 1265 case Intrinsic::vp_and: 1266 case Intrinsic::vp_or: 1267 case Intrinsic::vp_xor: 1268 case Intrinsic::vp_fadd: 1269 case Intrinsic::vp_fmul: 1270 case Intrinsic::vp_shl: 1271 case Intrinsic::vp_lshr: 1272 case Intrinsic::vp_ashr: 1273 case Intrinsic::vp_udiv: 1274 case Intrinsic::vp_sdiv: 1275 case Intrinsic::vp_urem: 1276 case Intrinsic::vp_srem: 1277 return Operand == 1; 1278 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1279 // explicit patterns for both LHS and RHS (as 'vr' versions). 1280 case Intrinsic::vp_sub: 1281 case Intrinsic::vp_fsub: 1282 case Intrinsic::vp_fdiv: 1283 return Operand == 0 || Operand == 1; 1284 default: 1285 return false; 1286 } 1287 } 1288 return false; 1289 default: 1290 return false; 1291 } 1292 }; 1293 1294 for (auto OpIdx : enumerate(I->operands())) { 1295 if (!IsSinker(I, OpIdx.index())) 1296 continue; 1297 1298 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1299 // Make sure we are not already sinking this operand 1300 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1301 continue; 1302 1303 // We are looking for a splat that can be sunk. 1304 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1305 m_Undef(), m_ZeroMask()))) 1306 continue; 1307 1308 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1309 // and vector registers 1310 for (Use &U : Op->uses()) { 1311 Instruction *Insn = cast<Instruction>(U.getUser()); 1312 if (!IsSinker(Insn, U.getOperandNo())) 1313 return false; 1314 } 1315 1316 Ops.push_back(&Op->getOperandUse(0)); 1317 Ops.push_back(&OpIdx.value()); 1318 } 1319 return true; 1320 } 1321 1322 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1323 bool ForCodeSize) const { 1324 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1325 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1326 return false; 1327 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1328 return false; 1329 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1330 return false; 1331 return Imm.isZero(); 1332 } 1333 1334 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1335 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1336 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1337 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1338 } 1339 1340 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1341 CallingConv::ID CC, 1342 EVT VT) const { 1343 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1344 // We might still end up using a GPR but that will be decided based on ABI. 1345 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1346 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1347 return MVT::f32; 1348 1349 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1350 } 1351 1352 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1353 CallingConv::ID CC, 1354 EVT VT) const { 1355 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1356 // We might still end up using a GPR but that will be decided based on ABI. 1357 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1358 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1359 return 1; 1360 1361 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1362 } 1363 1364 // Changes the condition code and swaps operands if necessary, so the SetCC 1365 // operation matches one of the comparisons supported directly by branches 1366 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1367 // with 1/-1. 1368 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1369 ISD::CondCode &CC, SelectionDAG &DAG) { 1370 // Convert X > -1 to X >= 0. 1371 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1372 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1373 CC = ISD::SETGE; 1374 return; 1375 } 1376 // Convert X < 1 to 0 >= X. 1377 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1378 RHS = LHS; 1379 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1380 CC = ISD::SETGE; 1381 return; 1382 } 1383 1384 switch (CC) { 1385 default: 1386 break; 1387 case ISD::SETGT: 1388 case ISD::SETLE: 1389 case ISD::SETUGT: 1390 case ISD::SETULE: 1391 CC = ISD::getSetCCSwappedOperands(CC); 1392 std::swap(LHS, RHS); 1393 break; 1394 } 1395 } 1396 1397 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1398 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1399 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1400 if (VT.getVectorElementType() == MVT::i1) 1401 KnownSize *= 8; 1402 1403 switch (KnownSize) { 1404 default: 1405 llvm_unreachable("Invalid LMUL."); 1406 case 8: 1407 return RISCVII::VLMUL::LMUL_F8; 1408 case 16: 1409 return RISCVII::VLMUL::LMUL_F4; 1410 case 32: 1411 return RISCVII::VLMUL::LMUL_F2; 1412 case 64: 1413 return RISCVII::VLMUL::LMUL_1; 1414 case 128: 1415 return RISCVII::VLMUL::LMUL_2; 1416 case 256: 1417 return RISCVII::VLMUL::LMUL_4; 1418 case 512: 1419 return RISCVII::VLMUL::LMUL_8; 1420 } 1421 } 1422 1423 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1424 switch (LMul) { 1425 default: 1426 llvm_unreachable("Invalid LMUL."); 1427 case RISCVII::VLMUL::LMUL_F8: 1428 case RISCVII::VLMUL::LMUL_F4: 1429 case RISCVII::VLMUL::LMUL_F2: 1430 case RISCVII::VLMUL::LMUL_1: 1431 return RISCV::VRRegClassID; 1432 case RISCVII::VLMUL::LMUL_2: 1433 return RISCV::VRM2RegClassID; 1434 case RISCVII::VLMUL::LMUL_4: 1435 return RISCV::VRM4RegClassID; 1436 case RISCVII::VLMUL::LMUL_8: 1437 return RISCV::VRM8RegClassID; 1438 } 1439 } 1440 1441 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1442 RISCVII::VLMUL LMUL = getLMUL(VT); 1443 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1444 LMUL == RISCVII::VLMUL::LMUL_F4 || 1445 LMUL == RISCVII::VLMUL::LMUL_F2 || 1446 LMUL == RISCVII::VLMUL::LMUL_1) { 1447 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1448 "Unexpected subreg numbering"); 1449 return RISCV::sub_vrm1_0 + Index; 1450 } 1451 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1452 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1453 "Unexpected subreg numbering"); 1454 return RISCV::sub_vrm2_0 + Index; 1455 } 1456 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1457 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1458 "Unexpected subreg numbering"); 1459 return RISCV::sub_vrm4_0 + Index; 1460 } 1461 llvm_unreachable("Invalid vector type."); 1462 } 1463 1464 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1465 if (VT.getVectorElementType() == MVT::i1) 1466 return RISCV::VRRegClassID; 1467 return getRegClassIDForLMUL(getLMUL(VT)); 1468 } 1469 1470 // Attempt to decompose a subvector insert/extract between VecVT and 1471 // SubVecVT via subregister indices. Returns the subregister index that 1472 // can perform the subvector insert/extract with the given element index, as 1473 // well as the index corresponding to any leftover subvectors that must be 1474 // further inserted/extracted within the register class for SubVecVT. 1475 std::pair<unsigned, unsigned> 1476 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1477 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1478 const RISCVRegisterInfo *TRI) { 1479 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1480 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1481 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1482 "Register classes not ordered"); 1483 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1484 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1485 // Try to compose a subregister index that takes us from the incoming 1486 // LMUL>1 register class down to the outgoing one. At each step we half 1487 // the LMUL: 1488 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1489 // Note that this is not guaranteed to find a subregister index, such as 1490 // when we are extracting from one VR type to another. 1491 unsigned SubRegIdx = RISCV::NoSubRegister; 1492 for (const unsigned RCID : 1493 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1494 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1495 VecVT = VecVT.getHalfNumVectorElementsVT(); 1496 bool IsHi = 1497 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1498 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1499 getSubregIndexByMVT(VecVT, IsHi)); 1500 if (IsHi) 1501 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1502 } 1503 return {SubRegIdx, InsertExtractIdx}; 1504 } 1505 1506 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1507 // stores for those types. 1508 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1509 return !Subtarget.useRVVForFixedLengthVectors() || 1510 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1511 } 1512 1513 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1514 if (ScalarTy->isPointerTy()) 1515 return true; 1516 1517 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1518 ScalarTy->isIntegerTy(32)) 1519 return true; 1520 1521 if (ScalarTy->isIntegerTy(64)) 1522 return Subtarget.hasVInstructionsI64(); 1523 1524 if (ScalarTy->isHalfTy()) 1525 return Subtarget.hasVInstructionsF16(); 1526 if (ScalarTy->isFloatTy()) 1527 return Subtarget.hasVInstructionsF32(); 1528 if (ScalarTy->isDoubleTy()) 1529 return Subtarget.hasVInstructionsF64(); 1530 1531 return false; 1532 } 1533 1534 static SDValue getVLOperand(SDValue Op) { 1535 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1536 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1537 "Unexpected opcode"); 1538 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1539 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1540 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1541 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1542 if (!II) 1543 return SDValue(); 1544 return Op.getOperand(II->VLOperand + 1 + HasChain); 1545 } 1546 1547 static bool useRVVForFixedLengthVectorVT(MVT VT, 1548 const RISCVSubtarget &Subtarget) { 1549 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1550 if (!Subtarget.useRVVForFixedLengthVectors()) 1551 return false; 1552 1553 // We only support a set of vector types with a consistent maximum fixed size 1554 // across all supported vector element types to avoid legalization issues. 1555 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1556 // fixed-length vector type we support is 1024 bytes. 1557 if (VT.getFixedSizeInBits() > 1024 * 8) 1558 return false; 1559 1560 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1561 1562 MVT EltVT = VT.getVectorElementType(); 1563 1564 // Don't use RVV for vectors we cannot scalarize if required. 1565 switch (EltVT.SimpleTy) { 1566 // i1 is supported but has different rules. 1567 default: 1568 return false; 1569 case MVT::i1: 1570 // Masks can only use a single register. 1571 if (VT.getVectorNumElements() > MinVLen) 1572 return false; 1573 MinVLen /= 8; 1574 break; 1575 case MVT::i8: 1576 case MVT::i16: 1577 case MVT::i32: 1578 break; 1579 case MVT::i64: 1580 if (!Subtarget.hasVInstructionsI64()) 1581 return false; 1582 break; 1583 case MVT::f16: 1584 if (!Subtarget.hasVInstructionsF16()) 1585 return false; 1586 break; 1587 case MVT::f32: 1588 if (!Subtarget.hasVInstructionsF32()) 1589 return false; 1590 break; 1591 case MVT::f64: 1592 if (!Subtarget.hasVInstructionsF64()) 1593 return false; 1594 break; 1595 } 1596 1597 // Reject elements larger than ELEN. 1598 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1599 return false; 1600 1601 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1602 // Don't use RVV for types that don't fit. 1603 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1604 return false; 1605 1606 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1607 // the base fixed length RVV support in place. 1608 if (!VT.isPow2VectorType()) 1609 return false; 1610 1611 return true; 1612 } 1613 1614 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1615 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1616 } 1617 1618 // Return the largest legal scalable vector type that matches VT's element type. 1619 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1620 const RISCVSubtarget &Subtarget) { 1621 // This may be called before legal types are setup. 1622 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1623 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1624 "Expected legal fixed length vector!"); 1625 1626 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1627 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1628 1629 MVT EltVT = VT.getVectorElementType(); 1630 switch (EltVT.SimpleTy) { 1631 default: 1632 llvm_unreachable("unexpected element type for RVV container"); 1633 case MVT::i1: 1634 case MVT::i8: 1635 case MVT::i16: 1636 case MVT::i32: 1637 case MVT::i64: 1638 case MVT::f16: 1639 case MVT::f32: 1640 case MVT::f64: { 1641 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1642 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1643 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1644 unsigned NumElts = 1645 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1646 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1647 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1648 return MVT::getScalableVectorVT(EltVT, NumElts); 1649 } 1650 } 1651 } 1652 1653 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1654 const RISCVSubtarget &Subtarget) { 1655 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1656 Subtarget); 1657 } 1658 1659 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1660 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1661 } 1662 1663 // Grow V to consume an entire RVV register. 1664 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1665 const RISCVSubtarget &Subtarget) { 1666 assert(VT.isScalableVector() && 1667 "Expected to convert into a scalable vector!"); 1668 assert(V.getValueType().isFixedLengthVector() && 1669 "Expected a fixed length vector operand!"); 1670 SDLoc DL(V); 1671 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1672 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1673 } 1674 1675 // Shrink V so it's just big enough to maintain a VT's worth of data. 1676 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1677 const RISCVSubtarget &Subtarget) { 1678 assert(VT.isFixedLengthVector() && 1679 "Expected to convert into a fixed length vector!"); 1680 assert(V.getValueType().isScalableVector() && 1681 "Expected a scalable vector operand!"); 1682 SDLoc DL(V); 1683 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1684 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1685 } 1686 1687 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1688 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1689 // the vector type that it is contained in. 1690 static std::pair<SDValue, SDValue> 1691 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1692 const RISCVSubtarget &Subtarget) { 1693 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1694 MVT XLenVT = Subtarget.getXLenVT(); 1695 SDValue VL = VecVT.isFixedLengthVector() 1696 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1697 : DAG.getRegister(RISCV::X0, XLenVT); 1698 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1699 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1700 return {Mask, VL}; 1701 } 1702 1703 // As above but assuming the given type is a scalable vector type. 1704 static std::pair<SDValue, SDValue> 1705 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1706 const RISCVSubtarget &Subtarget) { 1707 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1708 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1709 } 1710 1711 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1712 // of either is (currently) supported. This can get us into an infinite loop 1713 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1714 // as a ..., etc. 1715 // Until either (or both) of these can reliably lower any node, reporting that 1716 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1717 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1718 // which is not desirable. 1719 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1720 EVT VT, unsigned DefinedValues) const { 1721 return false; 1722 } 1723 1724 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1725 const RISCVSubtarget &Subtarget) { 1726 // RISCV FP-to-int conversions saturate to the destination register size, but 1727 // don't produce 0 for nan. We can use a conversion instruction and fix the 1728 // nan case with a compare and a select. 1729 SDValue Src = Op.getOperand(0); 1730 1731 EVT DstVT = Op.getValueType(); 1732 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1733 1734 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1735 unsigned Opc; 1736 if (SatVT == DstVT) 1737 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1738 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1739 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1740 else 1741 return SDValue(); 1742 // FIXME: Support other SatVTs by clamping before or after the conversion. 1743 1744 SDLoc DL(Op); 1745 SDValue FpToInt = DAG.getNode( 1746 Opc, DL, DstVT, Src, 1747 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1748 1749 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1750 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1751 } 1752 1753 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1754 // and back. Taking care to avoid converting values that are nan or already 1755 // correct. 1756 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1757 // have FRM dependencies modeled yet. 1758 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1759 MVT VT = Op.getSimpleValueType(); 1760 assert(VT.isVector() && "Unexpected type"); 1761 1762 SDLoc DL(Op); 1763 1764 // Freeze the source since we are increasing the number of uses. 1765 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1766 1767 // Truncate to integer and convert back to FP. 1768 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1769 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1770 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1771 1772 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1773 1774 if (Op.getOpcode() == ISD::FCEIL) { 1775 // If the truncated value is the greater than or equal to the original 1776 // value, we've computed the ceil. Otherwise, we went the wrong way and 1777 // need to increase by 1. 1778 // FIXME: This should use a masked operation. Handle here or in isel? 1779 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1780 DAG.getConstantFP(1.0, DL, VT)); 1781 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1782 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1783 } else if (Op.getOpcode() == ISD::FFLOOR) { 1784 // If the truncated value is the less than or equal to the original value, 1785 // we've computed the floor. Otherwise, we went the wrong way and need to 1786 // decrease by 1. 1787 // FIXME: This should use a masked operation. Handle here or in isel? 1788 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1789 DAG.getConstantFP(1.0, DL, VT)); 1790 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1791 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1792 } 1793 1794 // Restore the original sign so that -0.0 is preserved. 1795 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1796 1797 // Determine the largest integer that can be represented exactly. This and 1798 // values larger than it don't have any fractional bits so don't need to 1799 // be converted. 1800 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1801 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1802 APFloat MaxVal = APFloat(FltSem); 1803 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1804 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1805 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1806 1807 // If abs(Src) was larger than MaxVal or nan, keep it. 1808 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1809 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1810 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1811 } 1812 1813 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1814 // This mode isn't supported in vector hardware on RISCV. But as long as we 1815 // aren't compiling with trapping math, we can emulate this with 1816 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1817 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1818 // dependencies modeled yet. 1819 // FIXME: Use masked operations to avoid final merge. 1820 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1821 MVT VT = Op.getSimpleValueType(); 1822 assert(VT.isVector() && "Unexpected type"); 1823 1824 SDLoc DL(Op); 1825 1826 // Freeze the source since we are increasing the number of uses. 1827 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1828 1829 // We do the conversion on the absolute value and fix the sign at the end. 1830 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1831 1832 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1833 bool Ignored; 1834 APFloat Point5Pred = APFloat(0.5f); 1835 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1836 Point5Pred.next(/*nextDown*/ true); 1837 1838 // Add the adjustment. 1839 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1840 DAG.getConstantFP(Point5Pred, DL, VT)); 1841 1842 // Truncate to integer and convert back to fp. 1843 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1844 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1845 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1846 1847 // Restore the original sign. 1848 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1849 1850 // Determine the largest integer that can be represented exactly. This and 1851 // values larger than it don't have any fractional bits so don't need to 1852 // be converted. 1853 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1854 APFloat MaxVal = APFloat(FltSem); 1855 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1856 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1857 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1858 1859 // If abs(Src) was larger than MaxVal or nan, keep it. 1860 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1861 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1862 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1863 } 1864 1865 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1866 const RISCVSubtarget &Subtarget) { 1867 MVT VT = Op.getSimpleValueType(); 1868 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1869 1870 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1871 1872 SDLoc DL(Op); 1873 SDValue Mask, VL; 1874 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1875 1876 unsigned Opc = 1877 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1878 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 1879 Op.getOperand(0), VL); 1880 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1881 } 1882 1883 struct VIDSequence { 1884 int64_t StepNumerator; 1885 unsigned StepDenominator; 1886 int64_t Addend; 1887 }; 1888 1889 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1890 // to the (non-zero) step S and start value X. This can be then lowered as the 1891 // RVV sequence (VID * S) + X, for example. 1892 // The step S is represented as an integer numerator divided by a positive 1893 // denominator. Note that the implementation currently only identifies 1894 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1895 // cannot detect 2/3, for example. 1896 // Note that this method will also match potentially unappealing index 1897 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1898 // determine whether this is worth generating code for. 1899 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1900 unsigned NumElts = Op.getNumOperands(); 1901 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1902 if (!Op.getValueType().isInteger()) 1903 return None; 1904 1905 Optional<unsigned> SeqStepDenom; 1906 Optional<int64_t> SeqStepNum, SeqAddend; 1907 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1908 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1909 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1910 // Assume undef elements match the sequence; we just have to be careful 1911 // when interpolating across them. 1912 if (Op.getOperand(Idx).isUndef()) 1913 continue; 1914 // The BUILD_VECTOR must be all constants. 1915 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1916 return None; 1917 1918 uint64_t Val = Op.getConstantOperandVal(Idx) & 1919 maskTrailingOnes<uint64_t>(EltSizeInBits); 1920 1921 if (PrevElt) { 1922 // Calculate the step since the last non-undef element, and ensure 1923 // it's consistent across the entire sequence. 1924 unsigned IdxDiff = Idx - PrevElt->second; 1925 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1926 1927 // A zero-value value difference means that we're somewhere in the middle 1928 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1929 // step change before evaluating the sequence. 1930 if (ValDiff != 0) { 1931 int64_t Remainder = ValDiff % IdxDiff; 1932 // Normalize the step if it's greater than 1. 1933 if (Remainder != ValDiff) { 1934 // The difference must cleanly divide the element span. 1935 if (Remainder != 0) 1936 return None; 1937 ValDiff /= IdxDiff; 1938 IdxDiff = 1; 1939 } 1940 1941 if (!SeqStepNum) 1942 SeqStepNum = ValDiff; 1943 else if (ValDiff != SeqStepNum) 1944 return None; 1945 1946 if (!SeqStepDenom) 1947 SeqStepDenom = IdxDiff; 1948 else if (IdxDiff != *SeqStepDenom) 1949 return None; 1950 } 1951 } 1952 1953 // Record and/or check any addend. 1954 if (SeqStepNum && SeqStepDenom) { 1955 uint64_t ExpectedVal = 1956 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1957 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1958 if (!SeqAddend) 1959 SeqAddend = Addend; 1960 else if (SeqAddend != Addend) 1961 return None; 1962 } 1963 1964 // Record this non-undef element for later. 1965 if (!PrevElt || PrevElt->first != Val) 1966 PrevElt = std::make_pair(Val, Idx); 1967 } 1968 // We need to have logged both a step and an addend for this to count as 1969 // a legal index sequence. 1970 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1971 return None; 1972 1973 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1974 } 1975 1976 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1977 // and lower it as a VRGATHER_VX_VL from the source vector. 1978 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1979 SelectionDAG &DAG, 1980 const RISCVSubtarget &Subtarget) { 1981 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1982 return SDValue(); 1983 SDValue Vec = SplatVal.getOperand(0); 1984 // Only perform this optimization on vectors of the same size for simplicity. 1985 if (Vec.getValueType() != VT) 1986 return SDValue(); 1987 SDValue Idx = SplatVal.getOperand(1); 1988 // The index must be a legal type. 1989 if (Idx.getValueType() != Subtarget.getXLenVT()) 1990 return SDValue(); 1991 1992 MVT ContainerVT = VT; 1993 if (VT.isFixedLengthVector()) { 1994 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1995 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1996 } 1997 1998 SDValue Mask, VL; 1999 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2000 2001 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2002 Idx, Mask, VL); 2003 2004 if (!VT.isFixedLengthVector()) 2005 return Gather; 2006 2007 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2008 } 2009 2010 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2011 const RISCVSubtarget &Subtarget) { 2012 MVT VT = Op.getSimpleValueType(); 2013 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2014 2015 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2016 2017 SDLoc DL(Op); 2018 SDValue Mask, VL; 2019 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2020 2021 MVT XLenVT = Subtarget.getXLenVT(); 2022 unsigned NumElts = Op.getNumOperands(); 2023 2024 if (VT.getVectorElementType() == MVT::i1) { 2025 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2026 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2027 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2028 } 2029 2030 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2031 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2032 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2033 } 2034 2035 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2036 // scalar integer chunks whose bit-width depends on the number of mask 2037 // bits and XLEN. 2038 // First, determine the most appropriate scalar integer type to use. This 2039 // is at most XLenVT, but may be shrunk to a smaller vector element type 2040 // according to the size of the final vector - use i8 chunks rather than 2041 // XLenVT if we're producing a v8i1. This results in more consistent 2042 // codegen across RV32 and RV64. 2043 unsigned NumViaIntegerBits = 2044 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2045 NumViaIntegerBits = std::min(NumViaIntegerBits, 2046 Subtarget.getMaxELENForFixedLengthVectors()); 2047 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2048 // If we have to use more than one INSERT_VECTOR_ELT then this 2049 // optimization is likely to increase code size; avoid peforming it in 2050 // such a case. We can use a load from a constant pool in this case. 2051 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2052 return SDValue(); 2053 // Now we can create our integer vector type. Note that it may be larger 2054 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2055 MVT IntegerViaVecVT = 2056 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2057 divideCeil(NumElts, NumViaIntegerBits)); 2058 2059 uint64_t Bits = 0; 2060 unsigned BitPos = 0, IntegerEltIdx = 0; 2061 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2062 2063 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2064 // Once we accumulate enough bits to fill our scalar type, insert into 2065 // our vector and clear our accumulated data. 2066 if (I != 0 && I % NumViaIntegerBits == 0) { 2067 if (NumViaIntegerBits <= 32) 2068 Bits = SignExtend64(Bits, 32); 2069 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2070 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2071 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2072 Bits = 0; 2073 BitPos = 0; 2074 IntegerEltIdx++; 2075 } 2076 SDValue V = Op.getOperand(I); 2077 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2078 Bits |= ((uint64_t)BitValue << BitPos); 2079 } 2080 2081 // Insert the (remaining) scalar value into position in our integer 2082 // vector type. 2083 if (NumViaIntegerBits <= 32) 2084 Bits = SignExtend64(Bits, 32); 2085 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2086 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2087 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2088 2089 if (NumElts < NumViaIntegerBits) { 2090 // If we're producing a smaller vector than our minimum legal integer 2091 // type, bitcast to the equivalent (known-legal) mask type, and extract 2092 // our final mask. 2093 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2094 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2095 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2096 DAG.getConstant(0, DL, XLenVT)); 2097 } else { 2098 // Else we must have produced an integer type with the same size as the 2099 // mask type; bitcast for the final result. 2100 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2101 Vec = DAG.getBitcast(VT, Vec); 2102 } 2103 2104 return Vec; 2105 } 2106 2107 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2108 // vector type, we have a legal equivalently-sized i8 type, so we can use 2109 // that. 2110 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2111 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2112 2113 SDValue WideVec; 2114 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2115 // For a splat, perform a scalar truncate before creating the wider 2116 // vector. 2117 assert(Splat.getValueType() == XLenVT && 2118 "Unexpected type for i1 splat value"); 2119 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2120 DAG.getConstant(1, DL, XLenVT)); 2121 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2122 } else { 2123 SmallVector<SDValue, 8> Ops(Op->op_values()); 2124 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2125 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2126 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2127 } 2128 2129 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2130 } 2131 2132 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2133 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2134 return Gather; 2135 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2136 : RISCVISD::VMV_V_X_VL; 2137 Splat = 2138 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2139 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2140 } 2141 2142 // Try and match index sequences, which we can lower to the vid instruction 2143 // with optional modifications. An all-undef vector is matched by 2144 // getSplatValue, above. 2145 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2146 int64_t StepNumerator = SimpleVID->StepNumerator; 2147 unsigned StepDenominator = SimpleVID->StepDenominator; 2148 int64_t Addend = SimpleVID->Addend; 2149 2150 assert(StepNumerator != 0 && "Invalid step"); 2151 bool Negate = false; 2152 int64_t SplatStepVal = StepNumerator; 2153 unsigned StepOpcode = ISD::MUL; 2154 if (StepNumerator != 1) { 2155 if (isPowerOf2_64(std::abs(StepNumerator))) { 2156 Negate = StepNumerator < 0; 2157 StepOpcode = ISD::SHL; 2158 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2159 } 2160 } 2161 2162 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2163 // threshold since it's the immediate value many RVV instructions accept. 2164 // There is no vmul.vi instruction so ensure multiply constant can fit in 2165 // a single addi instruction. 2166 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2167 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2168 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2169 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2170 // Convert right out of the scalable type so we can use standard ISD 2171 // nodes for the rest of the computation. If we used scalable types with 2172 // these, we'd lose the fixed-length vector info and generate worse 2173 // vsetvli code. 2174 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2175 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2176 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2177 SDValue SplatStep = DAG.getSplatVector( 2178 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2179 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2180 } 2181 if (StepDenominator != 1) { 2182 SDValue SplatStep = DAG.getSplatVector( 2183 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2184 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2185 } 2186 if (Addend != 0 || Negate) { 2187 SDValue SplatAddend = 2188 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2189 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2190 } 2191 return VID; 2192 } 2193 } 2194 2195 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2196 // when re-interpreted as a vector with a larger element type. For example, 2197 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2198 // could be instead splat as 2199 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2200 // TODO: This optimization could also work on non-constant splats, but it 2201 // would require bit-manipulation instructions to construct the splat value. 2202 SmallVector<SDValue> Sequence; 2203 unsigned EltBitSize = VT.getScalarSizeInBits(); 2204 const auto *BV = cast<BuildVectorSDNode>(Op); 2205 if (VT.isInteger() && EltBitSize < 64 && 2206 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2207 BV->getRepeatedSequence(Sequence) && 2208 (Sequence.size() * EltBitSize) <= 64) { 2209 unsigned SeqLen = Sequence.size(); 2210 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2211 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2212 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2213 ViaIntVT == MVT::i64) && 2214 "Unexpected sequence type"); 2215 2216 unsigned EltIdx = 0; 2217 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2218 uint64_t SplatValue = 0; 2219 // Construct the amalgamated value which can be splatted as this larger 2220 // vector type. 2221 for (const auto &SeqV : Sequence) { 2222 if (!SeqV.isUndef()) 2223 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2224 << (EltIdx * EltBitSize)); 2225 EltIdx++; 2226 } 2227 2228 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2229 // achieve better constant materializion. 2230 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2231 SplatValue = SignExtend64(SplatValue, 32); 2232 2233 // Since we can't introduce illegal i64 types at this stage, we can only 2234 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2235 // way we can use RVV instructions to splat. 2236 assert((ViaIntVT.bitsLE(XLenVT) || 2237 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2238 "Unexpected bitcast sequence"); 2239 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2240 SDValue ViaVL = 2241 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2242 MVT ViaContainerVT = 2243 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2244 SDValue Splat = 2245 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2246 DAG.getUNDEF(ViaContainerVT), 2247 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2248 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2249 return DAG.getBitcast(VT, Splat); 2250 } 2251 } 2252 2253 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2254 // which constitute a large proportion of the elements. In such cases we can 2255 // splat a vector with the dominant element and make up the shortfall with 2256 // INSERT_VECTOR_ELTs. 2257 // Note that this includes vectors of 2 elements by association. The 2258 // upper-most element is the "dominant" one, allowing us to use a splat to 2259 // "insert" the upper element, and an insert of the lower element at position 2260 // 0, which improves codegen. 2261 SDValue DominantValue; 2262 unsigned MostCommonCount = 0; 2263 DenseMap<SDValue, unsigned> ValueCounts; 2264 unsigned NumUndefElts = 2265 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2266 2267 // Track the number of scalar loads we know we'd be inserting, estimated as 2268 // any non-zero floating-point constant. Other kinds of element are either 2269 // already in registers or are materialized on demand. The threshold at which 2270 // a vector load is more desirable than several scalar materializion and 2271 // vector-insertion instructions is not known. 2272 unsigned NumScalarLoads = 0; 2273 2274 for (SDValue V : Op->op_values()) { 2275 if (V.isUndef()) 2276 continue; 2277 2278 ValueCounts.insert(std::make_pair(V, 0)); 2279 unsigned &Count = ValueCounts[V]; 2280 2281 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2282 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2283 2284 // Is this value dominant? In case of a tie, prefer the highest element as 2285 // it's cheaper to insert near the beginning of a vector than it is at the 2286 // end. 2287 if (++Count >= MostCommonCount) { 2288 DominantValue = V; 2289 MostCommonCount = Count; 2290 } 2291 } 2292 2293 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2294 unsigned NumDefElts = NumElts - NumUndefElts; 2295 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2296 2297 // Don't perform this optimization when optimizing for size, since 2298 // materializing elements and inserting them tends to cause code bloat. 2299 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2300 ((MostCommonCount > DominantValueCountThreshold) || 2301 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2302 // Start by splatting the most common element. 2303 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2304 2305 DenseSet<SDValue> Processed{DominantValue}; 2306 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2307 for (const auto &OpIdx : enumerate(Op->ops())) { 2308 const SDValue &V = OpIdx.value(); 2309 if (V.isUndef() || !Processed.insert(V).second) 2310 continue; 2311 if (ValueCounts[V] == 1) { 2312 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2313 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2314 } else { 2315 // Blend in all instances of this value using a VSELECT, using a 2316 // mask where each bit signals whether that element is the one 2317 // we're after. 2318 SmallVector<SDValue> Ops; 2319 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2320 return DAG.getConstant(V == V1, DL, XLenVT); 2321 }); 2322 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2323 DAG.getBuildVector(SelMaskTy, DL, Ops), 2324 DAG.getSplatBuildVector(VT, DL, V), Vec); 2325 } 2326 } 2327 2328 return Vec; 2329 } 2330 2331 return SDValue(); 2332 } 2333 2334 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2335 SDValue Lo, SDValue Hi, SDValue VL, 2336 SelectionDAG &DAG) { 2337 bool HasPassthru = Passthru && !Passthru.isUndef(); 2338 if (!HasPassthru && !Passthru) 2339 Passthru = DAG.getUNDEF(VT); 2340 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2341 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2342 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2343 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2344 // node in order to try and match RVV vector/scalar instructions. 2345 if ((LoC >> 31) == HiC) 2346 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2347 2348 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2349 // vmv.v.x whose EEW = 32 to lower it. 2350 auto *Const = dyn_cast<ConstantSDNode>(VL); 2351 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2352 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2353 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2354 // access the subtarget here now. 2355 auto InterVec = DAG.getNode( 2356 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2357 DAG.getRegister(RISCV::X0, MVT::i32)); 2358 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2359 } 2360 } 2361 2362 // Fall back to a stack store and stride x0 vector load. 2363 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2364 Hi, VL); 2365 } 2366 2367 // Called by type legalization to handle splat of i64 on RV32. 2368 // FIXME: We can optimize this when the type has sign or zero bits in one 2369 // of the halves. 2370 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2371 SDValue Scalar, SDValue VL, 2372 SelectionDAG &DAG) { 2373 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2374 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2375 DAG.getConstant(0, DL, MVT::i32)); 2376 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2377 DAG.getConstant(1, DL, MVT::i32)); 2378 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2379 } 2380 2381 // This function lowers a splat of a scalar operand Splat with the vector 2382 // length VL. It ensures the final sequence is type legal, which is useful when 2383 // lowering a splat after type legalization. 2384 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2385 MVT VT, SDLoc DL, SelectionDAG &DAG, 2386 const RISCVSubtarget &Subtarget) { 2387 bool HasPassthru = Passthru && !Passthru.isUndef(); 2388 if (!HasPassthru && !Passthru) 2389 Passthru = DAG.getUNDEF(VT); 2390 if (VT.isFloatingPoint()) { 2391 // If VL is 1, we could use vfmv.s.f. 2392 if (isOneConstant(VL)) 2393 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2394 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2395 } 2396 2397 MVT XLenVT = Subtarget.getXLenVT(); 2398 2399 // Simplest case is that the operand needs to be promoted to XLenVT. 2400 if (Scalar.getValueType().bitsLE(XLenVT)) { 2401 // If the operand is a constant, sign extend to increase our chances 2402 // of being able to use a .vi instruction. ANY_EXTEND would become a 2403 // a zero extend and the simm5 check in isel would fail. 2404 // FIXME: Should we ignore the upper bits in isel instead? 2405 unsigned ExtOpc = 2406 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2407 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2408 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2409 // If VL is 1 and the scalar value won't benefit from immediate, we could 2410 // use vmv.s.x. 2411 if (isOneConstant(VL) && 2412 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2413 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2414 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2415 } 2416 2417 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2418 "Unexpected scalar for splat lowering!"); 2419 2420 if (isOneConstant(VL) && isNullConstant(Scalar)) 2421 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2422 DAG.getConstant(0, DL, XLenVT), VL); 2423 2424 // Otherwise use the more complicated splatting algorithm. 2425 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2426 } 2427 2428 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2429 const RISCVSubtarget &Subtarget) { 2430 // We need to be able to widen elements to the next larger integer type. 2431 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2432 return false; 2433 2434 int Size = Mask.size(); 2435 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2436 2437 int Srcs[] = {-1, -1}; 2438 for (int i = 0; i != Size; ++i) { 2439 // Ignore undef elements. 2440 if (Mask[i] < 0) 2441 continue; 2442 2443 // Is this an even or odd element. 2444 int Pol = i % 2; 2445 2446 // Ensure we consistently use the same source for this element polarity. 2447 int Src = Mask[i] / Size; 2448 if (Srcs[Pol] < 0) 2449 Srcs[Pol] = Src; 2450 if (Srcs[Pol] != Src) 2451 return false; 2452 2453 // Make sure the element within the source is appropriate for this element 2454 // in the destination. 2455 int Elt = Mask[i] % Size; 2456 if (Elt != i / 2) 2457 return false; 2458 } 2459 2460 // We need to find a source for each polarity and they can't be the same. 2461 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2462 return false; 2463 2464 // Swap the sources if the second source was in the even polarity. 2465 SwapSources = Srcs[0] > Srcs[1]; 2466 2467 return true; 2468 } 2469 2470 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2471 /// and then extract the original number of elements from the rotated result. 2472 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2473 /// returned rotation amount is for a rotate right, where elements move from 2474 /// higher elements to lower elements. \p LoSrc indicates the first source 2475 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2476 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2477 /// 0 or 1 if a rotation is found. 2478 /// 2479 /// NOTE: We talk about rotate to the right which matches how bit shift and 2480 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2481 /// and the table below write vectors with the lowest elements on the left. 2482 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2483 int Size = Mask.size(); 2484 2485 // We need to detect various ways of spelling a rotation: 2486 // [11, 12, 13, 14, 15, 0, 1, 2] 2487 // [-1, 12, 13, 14, -1, -1, 1, -1] 2488 // [-1, -1, -1, -1, -1, -1, 1, 2] 2489 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2490 // [-1, 4, 5, 6, -1, -1, 9, -1] 2491 // [-1, 4, 5, 6, -1, -1, -1, -1] 2492 int Rotation = 0; 2493 LoSrc = -1; 2494 HiSrc = -1; 2495 for (int i = 0; i != Size; ++i) { 2496 int M = Mask[i]; 2497 if (M < 0) 2498 continue; 2499 2500 // Determine where a rotate vector would have started. 2501 int StartIdx = i - (M % Size); 2502 // The identity rotation isn't interesting, stop. 2503 if (StartIdx == 0) 2504 return -1; 2505 2506 // If we found the tail of a vector the rotation must be the missing 2507 // front. If we found the head of a vector, it must be how much of the 2508 // head. 2509 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2510 2511 if (Rotation == 0) 2512 Rotation = CandidateRotation; 2513 else if (Rotation != CandidateRotation) 2514 // The rotations don't match, so we can't match this mask. 2515 return -1; 2516 2517 // Compute which value this mask is pointing at. 2518 int MaskSrc = M < Size ? 0 : 1; 2519 2520 // Compute which of the two target values this index should be assigned to. 2521 // This reflects whether the high elements are remaining or the low elemnts 2522 // are remaining. 2523 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2524 2525 // Either set up this value if we've not encountered it before, or check 2526 // that it remains consistent. 2527 if (TargetSrc < 0) 2528 TargetSrc = MaskSrc; 2529 else if (TargetSrc != MaskSrc) 2530 // This may be a rotation, but it pulls from the inputs in some 2531 // unsupported interleaving. 2532 return -1; 2533 } 2534 2535 // Check that we successfully analyzed the mask, and normalize the results. 2536 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2537 assert((LoSrc >= 0 || HiSrc >= 0) && 2538 "Failed to find a rotated input vector!"); 2539 2540 return Rotation; 2541 } 2542 2543 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2544 const RISCVSubtarget &Subtarget) { 2545 SDValue V1 = Op.getOperand(0); 2546 SDValue V2 = Op.getOperand(1); 2547 SDLoc DL(Op); 2548 MVT XLenVT = Subtarget.getXLenVT(); 2549 MVT VT = Op.getSimpleValueType(); 2550 unsigned NumElts = VT.getVectorNumElements(); 2551 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2552 2553 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2554 2555 SDValue TrueMask, VL; 2556 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2557 2558 if (SVN->isSplat()) { 2559 const int Lane = SVN->getSplatIndex(); 2560 if (Lane >= 0) { 2561 MVT SVT = VT.getVectorElementType(); 2562 2563 // Turn splatted vector load into a strided load with an X0 stride. 2564 SDValue V = V1; 2565 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2566 // with undef. 2567 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2568 int Offset = Lane; 2569 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2570 int OpElements = 2571 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2572 V = V.getOperand(Offset / OpElements); 2573 Offset %= OpElements; 2574 } 2575 2576 // We need to ensure the load isn't atomic or volatile. 2577 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2578 auto *Ld = cast<LoadSDNode>(V); 2579 Offset *= SVT.getStoreSize(); 2580 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2581 TypeSize::Fixed(Offset), DL); 2582 2583 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2584 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2585 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2586 SDValue IntID = 2587 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2588 SDValue Ops[] = {Ld->getChain(), 2589 IntID, 2590 DAG.getUNDEF(ContainerVT), 2591 NewAddr, 2592 DAG.getRegister(RISCV::X0, XLenVT), 2593 VL}; 2594 SDValue NewLoad = DAG.getMemIntrinsicNode( 2595 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2596 DAG.getMachineFunction().getMachineMemOperand( 2597 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2598 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2599 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2600 } 2601 2602 // Otherwise use a scalar load and splat. This will give the best 2603 // opportunity to fold a splat into the operation. ISel can turn it into 2604 // the x0 strided load if we aren't able to fold away the select. 2605 if (SVT.isFloatingPoint()) 2606 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2607 Ld->getPointerInfo().getWithOffset(Offset), 2608 Ld->getOriginalAlign(), 2609 Ld->getMemOperand()->getFlags()); 2610 else 2611 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2612 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2613 Ld->getOriginalAlign(), 2614 Ld->getMemOperand()->getFlags()); 2615 DAG.makeEquivalentMemoryOrdering(Ld, V); 2616 2617 unsigned Opc = 2618 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2619 SDValue Splat = 2620 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2621 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2622 } 2623 2624 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2625 assert(Lane < (int)NumElts && "Unexpected lane!"); 2626 SDValue Gather = 2627 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2628 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2629 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2630 } 2631 } 2632 2633 ArrayRef<int> Mask = SVN->getMask(); 2634 2635 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2636 // be undef which can be handled with a single SLIDEDOWN/UP. 2637 int LoSrc, HiSrc; 2638 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2639 if (Rotation > 0) { 2640 SDValue LoV, HiV; 2641 if (LoSrc >= 0) { 2642 LoV = LoSrc == 0 ? V1 : V2; 2643 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2644 } 2645 if (HiSrc >= 0) { 2646 HiV = HiSrc == 0 ? V1 : V2; 2647 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2648 } 2649 2650 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2651 // to slide LoV up by (NumElts - Rotation). 2652 unsigned InvRotate = NumElts - Rotation; 2653 2654 SDValue Res = DAG.getUNDEF(ContainerVT); 2655 if (HiV) { 2656 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2657 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2658 // causes multiple vsetvlis in some test cases such as lowering 2659 // reduce.mul 2660 SDValue DownVL = VL; 2661 if (LoV) 2662 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2663 Res = 2664 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2665 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2666 } 2667 if (LoV) 2668 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2669 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2670 2671 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2672 } 2673 2674 // Detect an interleave shuffle and lower to 2675 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2676 bool SwapSources; 2677 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2678 // Swap sources if needed. 2679 if (SwapSources) 2680 std::swap(V1, V2); 2681 2682 // Extract the lower half of the vectors. 2683 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2684 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2685 DAG.getConstant(0, DL, XLenVT)); 2686 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2687 DAG.getConstant(0, DL, XLenVT)); 2688 2689 // Double the element width and halve the number of elements in an int type. 2690 unsigned EltBits = VT.getScalarSizeInBits(); 2691 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2692 MVT WideIntVT = 2693 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2694 // Convert this to a scalable vector. We need to base this on the 2695 // destination size to ensure there's always a type with a smaller LMUL. 2696 MVT WideIntContainerVT = 2697 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2698 2699 // Convert sources to scalable vectors with the same element count as the 2700 // larger type. 2701 MVT HalfContainerVT = MVT::getVectorVT( 2702 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2703 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2704 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2705 2706 // Cast sources to integer. 2707 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2708 MVT IntHalfVT = 2709 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2710 V1 = DAG.getBitcast(IntHalfVT, V1); 2711 V2 = DAG.getBitcast(IntHalfVT, V2); 2712 2713 // Freeze V2 since we use it twice and we need to be sure that the add and 2714 // multiply see the same value. 2715 V2 = DAG.getFreeze(V2); 2716 2717 // Recreate TrueMask using the widened type's element count. 2718 MVT MaskVT = 2719 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2720 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2721 2722 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2723 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2724 V2, TrueMask, VL); 2725 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2726 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2727 DAG.getUNDEF(IntHalfVT), 2728 DAG.getAllOnesConstant(DL, XLenVT)); 2729 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2730 V2, Multiplier, TrueMask, VL); 2731 // Add the new copies to our previous addition giving us 2^eltbits copies of 2732 // V2. This is equivalent to shifting V2 left by eltbits. This should 2733 // combine with the vwmulu.vv above to form vwmaccu.vv. 2734 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2735 TrueMask, VL); 2736 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2737 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2738 // vector VT. 2739 ContainerVT = 2740 MVT::getVectorVT(VT.getVectorElementType(), 2741 WideIntContainerVT.getVectorElementCount() * 2); 2742 Add = DAG.getBitcast(ContainerVT, Add); 2743 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2744 } 2745 2746 // Detect shuffles which can be re-expressed as vector selects; these are 2747 // shuffles in which each element in the destination is taken from an element 2748 // at the corresponding index in either source vectors. 2749 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2750 int MaskIndex = MaskIdx.value(); 2751 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2752 }); 2753 2754 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2755 2756 SmallVector<SDValue> MaskVals; 2757 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2758 // merged with a second vrgather. 2759 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2760 2761 // By default we preserve the original operand order, and use a mask to 2762 // select LHS as true and RHS as false. However, since RVV vector selects may 2763 // feature splats but only on the LHS, we may choose to invert our mask and 2764 // instead select between RHS and LHS. 2765 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2766 bool InvertMask = IsSelect == SwapOps; 2767 2768 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2769 // half. 2770 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2771 2772 // Now construct the mask that will be used by the vselect or blended 2773 // vrgather operation. For vrgathers, construct the appropriate indices into 2774 // each vector. 2775 for (int MaskIndex : Mask) { 2776 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2777 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2778 if (!IsSelect) { 2779 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2780 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2781 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2782 : DAG.getUNDEF(XLenVT)); 2783 GatherIndicesRHS.push_back( 2784 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2785 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2786 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2787 ++LHSIndexCounts[MaskIndex]; 2788 if (!IsLHSOrUndefIndex) 2789 ++RHSIndexCounts[MaskIndex - NumElts]; 2790 } 2791 } 2792 2793 if (SwapOps) { 2794 std::swap(V1, V2); 2795 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2796 } 2797 2798 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2799 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2800 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2801 2802 if (IsSelect) 2803 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2804 2805 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2806 // On such a large vector we're unable to use i8 as the index type. 2807 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2808 // may involve vector splitting if we're already at LMUL=8, or our 2809 // user-supplied maximum fixed-length LMUL. 2810 return SDValue(); 2811 } 2812 2813 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2814 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2815 MVT IndexVT = VT.changeTypeToInteger(); 2816 // Since we can't introduce illegal index types at this stage, use i16 and 2817 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2818 // than XLenVT. 2819 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2820 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2821 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2822 } 2823 2824 MVT IndexContainerVT = 2825 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2826 2827 SDValue Gather; 2828 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2829 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2830 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2831 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2832 Subtarget); 2833 } else { 2834 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2835 // If only one index is used, we can use a "splat" vrgather. 2836 // TODO: We can splat the most-common index and fix-up any stragglers, if 2837 // that's beneficial. 2838 if (LHSIndexCounts.size() == 1) { 2839 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2840 Gather = 2841 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2842 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2843 } else { 2844 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2845 LHSIndices = 2846 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2847 2848 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2849 TrueMask, VL); 2850 } 2851 } 2852 2853 // If a second vector operand is used by this shuffle, blend it in with an 2854 // additional vrgather. 2855 if (!V2.isUndef()) { 2856 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2857 // If only one index is used, we can use a "splat" vrgather. 2858 // TODO: We can splat the most-common index and fix-up any stragglers, if 2859 // that's beneficial. 2860 if (RHSIndexCounts.size() == 1) { 2861 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2862 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2863 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2864 } else { 2865 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2866 RHSIndices = 2867 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2868 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2869 VL); 2870 } 2871 2872 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2873 SelectMask = 2874 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2875 2876 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2877 Gather, VL); 2878 } 2879 2880 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2881 } 2882 2883 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2884 // Support splats for any type. These should type legalize well. 2885 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2886 return true; 2887 2888 // Only support legal VTs for other shuffles for now. 2889 if (!isTypeLegal(VT)) 2890 return false; 2891 2892 MVT SVT = VT.getSimpleVT(); 2893 2894 bool SwapSources; 2895 int LoSrc, HiSrc; 2896 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2897 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2898 } 2899 2900 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2901 SDLoc DL, SelectionDAG &DAG, 2902 const RISCVSubtarget &Subtarget) { 2903 if (VT.isScalableVector()) 2904 return DAG.getFPExtendOrRound(Op, DL, VT); 2905 assert(VT.isFixedLengthVector() && 2906 "Unexpected value type for RVV FP extend/round lowering"); 2907 SDValue Mask, VL; 2908 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2909 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2910 ? RISCVISD::FP_EXTEND_VL 2911 : RISCVISD::FP_ROUND_VL; 2912 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2913 } 2914 2915 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2916 // the exponent. 2917 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2918 MVT VT = Op.getSimpleValueType(); 2919 unsigned EltSize = VT.getScalarSizeInBits(); 2920 SDValue Src = Op.getOperand(0); 2921 SDLoc DL(Op); 2922 2923 // We need a FP type that can represent the value. 2924 // TODO: Use f16 for i8 when possible? 2925 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2926 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2927 2928 // Legal types should have been checked in the RISCVTargetLowering 2929 // constructor. 2930 // TODO: Splitting may make sense in some cases. 2931 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2932 "Expected legal float type!"); 2933 2934 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2935 // The trailing zero count is equal to log2 of this single bit value. 2936 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2937 SDValue Neg = 2938 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2939 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2940 } 2941 2942 // We have a legal FP type, convert to it. 2943 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2944 // Bitcast to integer and shift the exponent to the LSB. 2945 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2946 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2947 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2948 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2949 DAG.getConstant(ShiftAmt, DL, IntVT)); 2950 // Truncate back to original type to allow vnsrl. 2951 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2952 // The exponent contains log2 of the value in biased form. 2953 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2954 2955 // For trailing zeros, we just need to subtract the bias. 2956 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2957 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2958 DAG.getConstant(ExponentBias, DL, VT)); 2959 2960 // For leading zeros, we need to remove the bias and convert from log2 to 2961 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2962 unsigned Adjust = ExponentBias + (EltSize - 1); 2963 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2964 } 2965 2966 // While RVV has alignment restrictions, we should always be able to load as a 2967 // legal equivalently-sized byte-typed vector instead. This method is 2968 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2969 // the load is already correctly-aligned, it returns SDValue(). 2970 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2971 SelectionDAG &DAG) const { 2972 auto *Load = cast<LoadSDNode>(Op); 2973 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2974 2975 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2976 Load->getMemoryVT(), 2977 *Load->getMemOperand())) 2978 return SDValue(); 2979 2980 SDLoc DL(Op); 2981 MVT VT = Op.getSimpleValueType(); 2982 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2983 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2984 "Unexpected unaligned RVV load type"); 2985 MVT NewVT = 2986 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2987 assert(NewVT.isValid() && 2988 "Expecting equally-sized RVV vector types to be legal"); 2989 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2990 Load->getPointerInfo(), Load->getOriginalAlign(), 2991 Load->getMemOperand()->getFlags()); 2992 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2993 } 2994 2995 // While RVV has alignment restrictions, we should always be able to store as a 2996 // legal equivalently-sized byte-typed vector instead. This method is 2997 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2998 // returns SDValue() if the store is already correctly aligned. 2999 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3000 SelectionDAG &DAG) const { 3001 auto *Store = cast<StoreSDNode>(Op); 3002 assert(Store && Store->getValue().getValueType().isVector() && 3003 "Expected vector store"); 3004 3005 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3006 Store->getMemoryVT(), 3007 *Store->getMemOperand())) 3008 return SDValue(); 3009 3010 SDLoc DL(Op); 3011 SDValue StoredVal = Store->getValue(); 3012 MVT VT = StoredVal.getSimpleValueType(); 3013 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3014 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3015 "Unexpected unaligned RVV store type"); 3016 MVT NewVT = 3017 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3018 assert(NewVT.isValid() && 3019 "Expecting equally-sized RVV vector types to be legal"); 3020 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3021 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3022 Store->getPointerInfo(), Store->getOriginalAlign(), 3023 Store->getMemOperand()->getFlags()); 3024 } 3025 3026 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3027 SelectionDAG &DAG) const { 3028 switch (Op.getOpcode()) { 3029 default: 3030 report_fatal_error("unimplemented operand"); 3031 case ISD::GlobalAddress: 3032 return lowerGlobalAddress(Op, DAG); 3033 case ISD::BlockAddress: 3034 return lowerBlockAddress(Op, DAG); 3035 case ISD::ConstantPool: 3036 return lowerConstantPool(Op, DAG); 3037 case ISD::JumpTable: 3038 return lowerJumpTable(Op, DAG); 3039 case ISD::GlobalTLSAddress: 3040 return lowerGlobalTLSAddress(Op, DAG); 3041 case ISD::SELECT: 3042 return lowerSELECT(Op, DAG); 3043 case ISD::BRCOND: 3044 return lowerBRCOND(Op, DAG); 3045 case ISD::VASTART: 3046 return lowerVASTART(Op, DAG); 3047 case ISD::FRAMEADDR: 3048 return lowerFRAMEADDR(Op, DAG); 3049 case ISD::RETURNADDR: 3050 return lowerRETURNADDR(Op, DAG); 3051 case ISD::SHL_PARTS: 3052 return lowerShiftLeftParts(Op, DAG); 3053 case ISD::SRA_PARTS: 3054 return lowerShiftRightParts(Op, DAG, true); 3055 case ISD::SRL_PARTS: 3056 return lowerShiftRightParts(Op, DAG, false); 3057 case ISD::BITCAST: { 3058 SDLoc DL(Op); 3059 EVT VT = Op.getValueType(); 3060 SDValue Op0 = Op.getOperand(0); 3061 EVT Op0VT = Op0.getValueType(); 3062 MVT XLenVT = Subtarget.getXLenVT(); 3063 if (VT.isFixedLengthVector()) { 3064 // We can handle fixed length vector bitcasts with a simple replacement 3065 // in isel. 3066 if (Op0VT.isFixedLengthVector()) 3067 return Op; 3068 // When bitcasting from scalar to fixed-length vector, insert the scalar 3069 // into a one-element vector of the result type, and perform a vector 3070 // bitcast. 3071 if (!Op0VT.isVector()) { 3072 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3073 if (!isTypeLegal(BVT)) 3074 return SDValue(); 3075 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3076 DAG.getUNDEF(BVT), Op0, 3077 DAG.getConstant(0, DL, XLenVT))); 3078 } 3079 return SDValue(); 3080 } 3081 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3082 // thus: bitcast the vector to a one-element vector type whose element type 3083 // is the same as the result type, and extract the first element. 3084 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3085 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3086 if (!isTypeLegal(BVT)) 3087 return SDValue(); 3088 SDValue BVec = DAG.getBitcast(BVT, Op0); 3089 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3090 DAG.getConstant(0, DL, XLenVT)); 3091 } 3092 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3093 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3094 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3095 return FPConv; 3096 } 3097 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3098 Subtarget.hasStdExtF()) { 3099 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3100 SDValue FPConv = 3101 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3102 return FPConv; 3103 } 3104 return SDValue(); 3105 } 3106 case ISD::INTRINSIC_WO_CHAIN: 3107 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3108 case ISD::INTRINSIC_W_CHAIN: 3109 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3110 case ISD::INTRINSIC_VOID: 3111 return LowerINTRINSIC_VOID(Op, DAG); 3112 case ISD::BSWAP: 3113 case ISD::BITREVERSE: { 3114 MVT VT = Op.getSimpleValueType(); 3115 SDLoc DL(Op); 3116 if (Subtarget.hasStdExtZbp()) { 3117 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3118 // Start with the maximum immediate value which is the bitwidth - 1. 3119 unsigned Imm = VT.getSizeInBits() - 1; 3120 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3121 if (Op.getOpcode() == ISD::BSWAP) 3122 Imm &= ~0x7U; 3123 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3124 DAG.getConstant(Imm, DL, VT)); 3125 } 3126 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3127 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3128 // Expand bitreverse to a bswap(rev8) followed by brev8. 3129 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3130 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3131 // as brev8 by an isel pattern. 3132 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3133 DAG.getConstant(7, DL, VT)); 3134 } 3135 case ISD::FSHL: 3136 case ISD::FSHR: { 3137 MVT VT = Op.getSimpleValueType(); 3138 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3139 SDLoc DL(Op); 3140 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3141 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3142 // accidentally setting the extra bit. 3143 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3144 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3145 DAG.getConstant(ShAmtWidth, DL, VT)); 3146 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3147 // instruction use different orders. fshl will return its first operand for 3148 // shift of zero, fshr will return its second operand. fsl and fsr both 3149 // return rs1 so the ISD nodes need to have different operand orders. 3150 // Shift amount is in rs2. 3151 SDValue Op0 = Op.getOperand(0); 3152 SDValue Op1 = Op.getOperand(1); 3153 unsigned Opc = RISCVISD::FSL; 3154 if (Op.getOpcode() == ISD::FSHR) { 3155 std::swap(Op0, Op1); 3156 Opc = RISCVISD::FSR; 3157 } 3158 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3159 } 3160 case ISD::TRUNCATE: { 3161 SDLoc DL(Op); 3162 MVT VT = Op.getSimpleValueType(); 3163 // Only custom-lower vector truncates 3164 if (!VT.isVector()) 3165 return Op; 3166 3167 // Truncates to mask types are handled differently 3168 if (VT.getVectorElementType() == MVT::i1) 3169 return lowerVectorMaskTrunc(Op, DAG); 3170 3171 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3172 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3173 // truncate by one power of two at a time. 3174 MVT DstEltVT = VT.getVectorElementType(); 3175 3176 SDValue Src = Op.getOperand(0); 3177 MVT SrcVT = Src.getSimpleValueType(); 3178 MVT SrcEltVT = SrcVT.getVectorElementType(); 3179 3180 assert(DstEltVT.bitsLT(SrcEltVT) && 3181 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3182 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3183 "Unexpected vector truncate lowering"); 3184 3185 MVT ContainerVT = SrcVT; 3186 if (SrcVT.isFixedLengthVector()) { 3187 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3188 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3189 } 3190 3191 SDValue Result = Src; 3192 SDValue Mask, VL; 3193 std::tie(Mask, VL) = 3194 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3195 LLVMContext &Context = *DAG.getContext(); 3196 const ElementCount Count = ContainerVT.getVectorElementCount(); 3197 do { 3198 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3199 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3200 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3201 Mask, VL); 3202 } while (SrcEltVT != DstEltVT); 3203 3204 if (SrcVT.isFixedLengthVector()) 3205 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3206 3207 return Result; 3208 } 3209 case ISD::ANY_EXTEND: 3210 case ISD::ZERO_EXTEND: 3211 if (Op.getOperand(0).getValueType().isVector() && 3212 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3213 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3214 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3215 case ISD::SIGN_EXTEND: 3216 if (Op.getOperand(0).getValueType().isVector() && 3217 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3218 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3219 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3220 case ISD::SPLAT_VECTOR_PARTS: 3221 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3222 case ISD::INSERT_VECTOR_ELT: 3223 return lowerINSERT_VECTOR_ELT(Op, DAG); 3224 case ISD::EXTRACT_VECTOR_ELT: 3225 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3226 case ISD::VSCALE: { 3227 MVT VT = Op.getSimpleValueType(); 3228 SDLoc DL(Op); 3229 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3230 // We define our scalable vector types for lmul=1 to use a 64 bit known 3231 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3232 // vscale as VLENB / 8. 3233 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3234 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3235 report_fatal_error("Support for VLEN==32 is incomplete."); 3236 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3237 // We assume VLENB is a multiple of 8. We manually choose the best shift 3238 // here because SimplifyDemandedBits isn't always able to simplify it. 3239 uint64_t Val = Op.getConstantOperandVal(0); 3240 if (isPowerOf2_64(Val)) { 3241 uint64_t Log2 = Log2_64(Val); 3242 if (Log2 < 3) 3243 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3244 DAG.getConstant(3 - Log2, DL, VT)); 3245 if (Log2 > 3) 3246 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3247 DAG.getConstant(Log2 - 3, DL, VT)); 3248 return VLENB; 3249 } 3250 // If the multiplier is a multiple of 8, scale it down to avoid needing 3251 // to shift the VLENB value. 3252 if ((Val % 8) == 0) 3253 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3254 DAG.getConstant(Val / 8, DL, VT)); 3255 } 3256 3257 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3258 DAG.getConstant(3, DL, VT)); 3259 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3260 } 3261 case ISD::FPOWI: { 3262 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3263 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3264 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3265 Op.getOperand(1).getValueType() == MVT::i32) { 3266 SDLoc DL(Op); 3267 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3268 SDValue Powi = 3269 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3270 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3271 DAG.getIntPtrConstant(0, DL)); 3272 } 3273 return SDValue(); 3274 } 3275 case ISD::FP_EXTEND: { 3276 // RVV can only do fp_extend to types double the size as the source. We 3277 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3278 // via f32. 3279 SDLoc DL(Op); 3280 MVT VT = Op.getSimpleValueType(); 3281 SDValue Src = Op.getOperand(0); 3282 MVT SrcVT = Src.getSimpleValueType(); 3283 3284 // Prepare any fixed-length vector operands. 3285 MVT ContainerVT = VT; 3286 if (SrcVT.isFixedLengthVector()) { 3287 ContainerVT = getContainerForFixedLengthVector(VT); 3288 MVT SrcContainerVT = 3289 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3290 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3291 } 3292 3293 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3294 SrcVT.getVectorElementType() != MVT::f16) { 3295 // For scalable vectors, we only need to close the gap between 3296 // vXf16->vXf64. 3297 if (!VT.isFixedLengthVector()) 3298 return Op; 3299 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3300 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3301 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3302 } 3303 3304 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3305 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3306 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3307 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3308 3309 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3310 DL, DAG, Subtarget); 3311 if (VT.isFixedLengthVector()) 3312 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3313 return Extend; 3314 } 3315 case ISD::FP_ROUND: { 3316 // RVV can only do fp_round to types half the size as the source. We 3317 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3318 // conversion instruction. 3319 SDLoc DL(Op); 3320 MVT VT = Op.getSimpleValueType(); 3321 SDValue Src = Op.getOperand(0); 3322 MVT SrcVT = Src.getSimpleValueType(); 3323 3324 // Prepare any fixed-length vector operands. 3325 MVT ContainerVT = VT; 3326 if (VT.isFixedLengthVector()) { 3327 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3328 ContainerVT = 3329 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3330 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3331 } 3332 3333 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3334 SrcVT.getVectorElementType() != MVT::f64) { 3335 // For scalable vectors, we only need to close the gap between 3336 // vXf64<->vXf16. 3337 if (!VT.isFixedLengthVector()) 3338 return Op; 3339 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3340 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3341 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3342 } 3343 3344 SDValue Mask, VL; 3345 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3346 3347 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3348 SDValue IntermediateRound = 3349 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3350 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3351 DL, DAG, Subtarget); 3352 3353 if (VT.isFixedLengthVector()) 3354 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3355 return Round; 3356 } 3357 case ISD::FP_TO_SINT: 3358 case ISD::FP_TO_UINT: 3359 case ISD::SINT_TO_FP: 3360 case ISD::UINT_TO_FP: { 3361 // RVV can only do fp<->int conversions to types half/double the size as 3362 // the source. We custom-lower any conversions that do two hops into 3363 // sequences. 3364 MVT VT = Op.getSimpleValueType(); 3365 if (!VT.isVector()) 3366 return Op; 3367 SDLoc DL(Op); 3368 SDValue Src = Op.getOperand(0); 3369 MVT EltVT = VT.getVectorElementType(); 3370 MVT SrcVT = Src.getSimpleValueType(); 3371 MVT SrcEltVT = SrcVT.getVectorElementType(); 3372 unsigned EltSize = EltVT.getSizeInBits(); 3373 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3374 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3375 "Unexpected vector element types"); 3376 3377 bool IsInt2FP = SrcEltVT.isInteger(); 3378 // Widening conversions 3379 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3380 if (IsInt2FP) { 3381 // Do a regular integer sign/zero extension then convert to float. 3382 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3383 VT.getVectorElementCount()); 3384 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3385 ? ISD::ZERO_EXTEND 3386 : ISD::SIGN_EXTEND; 3387 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3388 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3389 } 3390 // FP2Int 3391 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3392 // Do one doubling fp_extend then complete the operation by converting 3393 // to int. 3394 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3395 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3396 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3397 } 3398 3399 // Narrowing conversions 3400 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3401 if (IsInt2FP) { 3402 // One narrowing int_to_fp, then an fp_round. 3403 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3404 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3405 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3406 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3407 } 3408 // FP2Int 3409 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3410 // representable by the integer, the result is poison. 3411 MVT IVecVT = 3412 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3413 VT.getVectorElementCount()); 3414 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3415 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3416 } 3417 3418 // Scalable vectors can exit here. Patterns will handle equally-sized 3419 // conversions halving/doubling ones. 3420 if (!VT.isFixedLengthVector()) 3421 return Op; 3422 3423 // For fixed-length vectors we lower to a custom "VL" node. 3424 unsigned RVVOpc = 0; 3425 switch (Op.getOpcode()) { 3426 default: 3427 llvm_unreachable("Impossible opcode"); 3428 case ISD::FP_TO_SINT: 3429 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3430 break; 3431 case ISD::FP_TO_UINT: 3432 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3433 break; 3434 case ISD::SINT_TO_FP: 3435 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3436 break; 3437 case ISD::UINT_TO_FP: 3438 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3439 break; 3440 } 3441 3442 MVT ContainerVT, SrcContainerVT; 3443 // Derive the reference container type from the larger vector type. 3444 if (SrcEltSize > EltSize) { 3445 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3446 ContainerVT = 3447 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3448 } else { 3449 ContainerVT = getContainerForFixedLengthVector(VT); 3450 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3451 } 3452 3453 SDValue Mask, VL; 3454 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3455 3456 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3457 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3458 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3459 } 3460 case ISD::FP_TO_SINT_SAT: 3461 case ISD::FP_TO_UINT_SAT: 3462 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3463 case ISD::FTRUNC: 3464 case ISD::FCEIL: 3465 case ISD::FFLOOR: 3466 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3467 case ISD::FROUND: 3468 return lowerFROUND(Op, DAG); 3469 case ISD::VECREDUCE_ADD: 3470 case ISD::VECREDUCE_UMAX: 3471 case ISD::VECREDUCE_SMAX: 3472 case ISD::VECREDUCE_UMIN: 3473 case ISD::VECREDUCE_SMIN: 3474 return lowerVECREDUCE(Op, DAG); 3475 case ISD::VECREDUCE_AND: 3476 case ISD::VECREDUCE_OR: 3477 case ISD::VECREDUCE_XOR: 3478 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3479 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3480 return lowerVECREDUCE(Op, DAG); 3481 case ISD::VECREDUCE_FADD: 3482 case ISD::VECREDUCE_SEQ_FADD: 3483 case ISD::VECREDUCE_FMIN: 3484 case ISD::VECREDUCE_FMAX: 3485 return lowerFPVECREDUCE(Op, DAG); 3486 case ISD::VP_REDUCE_ADD: 3487 case ISD::VP_REDUCE_UMAX: 3488 case ISD::VP_REDUCE_SMAX: 3489 case ISD::VP_REDUCE_UMIN: 3490 case ISD::VP_REDUCE_SMIN: 3491 case ISD::VP_REDUCE_FADD: 3492 case ISD::VP_REDUCE_SEQ_FADD: 3493 case ISD::VP_REDUCE_FMIN: 3494 case ISD::VP_REDUCE_FMAX: 3495 return lowerVPREDUCE(Op, DAG); 3496 case ISD::VP_REDUCE_AND: 3497 case ISD::VP_REDUCE_OR: 3498 case ISD::VP_REDUCE_XOR: 3499 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3500 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3501 return lowerVPREDUCE(Op, DAG); 3502 case ISD::INSERT_SUBVECTOR: 3503 return lowerINSERT_SUBVECTOR(Op, DAG); 3504 case ISD::EXTRACT_SUBVECTOR: 3505 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3506 case ISD::STEP_VECTOR: 3507 return lowerSTEP_VECTOR(Op, DAG); 3508 case ISD::VECTOR_REVERSE: 3509 return lowerVECTOR_REVERSE(Op, DAG); 3510 case ISD::BUILD_VECTOR: 3511 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3512 case ISD::SPLAT_VECTOR: 3513 if (Op.getValueType().getVectorElementType() == MVT::i1) 3514 return lowerVectorMaskSplat(Op, DAG); 3515 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3516 case ISD::VECTOR_SHUFFLE: 3517 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3518 case ISD::CONCAT_VECTORS: { 3519 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3520 // better than going through the stack, as the default expansion does. 3521 SDLoc DL(Op); 3522 MVT VT = Op.getSimpleValueType(); 3523 unsigned NumOpElts = 3524 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3525 SDValue Vec = DAG.getUNDEF(VT); 3526 for (const auto &OpIdx : enumerate(Op->ops())) { 3527 SDValue SubVec = OpIdx.value(); 3528 // Don't insert undef subvectors. 3529 if (SubVec.isUndef()) 3530 continue; 3531 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3532 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3533 } 3534 return Vec; 3535 } 3536 case ISD::LOAD: 3537 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3538 return V; 3539 if (Op.getValueType().isFixedLengthVector()) 3540 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3541 return Op; 3542 case ISD::STORE: 3543 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3544 return V; 3545 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3546 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3547 return Op; 3548 case ISD::MLOAD: 3549 case ISD::VP_LOAD: 3550 return lowerMaskedLoad(Op, DAG); 3551 case ISD::MSTORE: 3552 case ISD::VP_STORE: 3553 return lowerMaskedStore(Op, DAG); 3554 case ISD::SETCC: 3555 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3556 case ISD::ADD: 3557 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3558 case ISD::SUB: 3559 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3560 case ISD::MUL: 3561 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3562 case ISD::MULHS: 3563 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3564 case ISD::MULHU: 3565 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3566 case ISD::AND: 3567 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3568 RISCVISD::AND_VL); 3569 case ISD::OR: 3570 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3571 RISCVISD::OR_VL); 3572 case ISD::XOR: 3573 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3574 RISCVISD::XOR_VL); 3575 case ISD::SDIV: 3576 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3577 case ISD::SREM: 3578 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3579 case ISD::UDIV: 3580 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3581 case ISD::UREM: 3582 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3583 case ISD::SHL: 3584 case ISD::SRA: 3585 case ISD::SRL: 3586 if (Op.getSimpleValueType().isFixedLengthVector()) 3587 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3588 // This can be called for an i32 shift amount that needs to be promoted. 3589 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3590 "Unexpected custom legalisation"); 3591 return SDValue(); 3592 case ISD::SADDSAT: 3593 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3594 case ISD::UADDSAT: 3595 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3596 case ISD::SSUBSAT: 3597 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3598 case ISD::USUBSAT: 3599 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3600 case ISD::FADD: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3602 case ISD::FSUB: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3604 case ISD::FMUL: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3606 case ISD::FDIV: 3607 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3608 case ISD::FNEG: 3609 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3610 case ISD::FABS: 3611 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3612 case ISD::FSQRT: 3613 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3614 case ISD::FMA: 3615 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3616 case ISD::SMIN: 3617 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3618 case ISD::SMAX: 3619 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3620 case ISD::UMIN: 3621 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3622 case ISD::UMAX: 3623 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3624 case ISD::FMINNUM: 3625 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3626 case ISD::FMAXNUM: 3627 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3628 case ISD::ABS: 3629 return lowerABS(Op, DAG); 3630 case ISD::CTLZ_ZERO_UNDEF: 3631 case ISD::CTTZ_ZERO_UNDEF: 3632 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3633 case ISD::VSELECT: 3634 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3635 case ISD::FCOPYSIGN: 3636 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3637 case ISD::MGATHER: 3638 case ISD::VP_GATHER: 3639 return lowerMaskedGather(Op, DAG); 3640 case ISD::MSCATTER: 3641 case ISD::VP_SCATTER: 3642 return lowerMaskedScatter(Op, DAG); 3643 case ISD::FLT_ROUNDS_: 3644 return lowerGET_ROUNDING(Op, DAG); 3645 case ISD::SET_ROUNDING: 3646 return lowerSET_ROUNDING(Op, DAG); 3647 case ISD::VP_SELECT: 3648 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3649 case ISD::VP_MERGE: 3650 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3651 case ISD::VP_ADD: 3652 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3653 case ISD::VP_SUB: 3654 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3655 case ISD::VP_MUL: 3656 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3657 case ISD::VP_SDIV: 3658 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3659 case ISD::VP_UDIV: 3660 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3661 case ISD::VP_SREM: 3662 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3663 case ISD::VP_UREM: 3664 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3665 case ISD::VP_AND: 3666 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3667 case ISD::VP_OR: 3668 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3669 case ISD::VP_XOR: 3670 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3671 case ISD::VP_ASHR: 3672 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3673 case ISD::VP_LSHR: 3674 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3675 case ISD::VP_SHL: 3676 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3677 case ISD::VP_FADD: 3678 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3679 case ISD::VP_FSUB: 3680 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3681 case ISD::VP_FMUL: 3682 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3683 case ISD::VP_FDIV: 3684 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3685 case ISD::VP_FNEG: 3686 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3687 case ISD::VP_FMA: 3688 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3689 } 3690 } 3691 3692 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3693 SelectionDAG &DAG, unsigned Flags) { 3694 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3695 } 3696 3697 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3698 SelectionDAG &DAG, unsigned Flags) { 3699 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3700 Flags); 3701 } 3702 3703 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3704 SelectionDAG &DAG, unsigned Flags) { 3705 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3706 N->getOffset(), Flags); 3707 } 3708 3709 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3710 SelectionDAG &DAG, unsigned Flags) { 3711 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3712 } 3713 3714 template <class NodeTy> 3715 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3716 bool IsLocal) const { 3717 SDLoc DL(N); 3718 EVT Ty = getPointerTy(DAG.getDataLayout()); 3719 3720 if (isPositionIndependent()) { 3721 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3722 if (IsLocal) 3723 // Use PC-relative addressing to access the symbol. This generates the 3724 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3725 // %pcrel_lo(auipc)). 3726 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3727 3728 // Use PC-relative addressing to access the GOT for this symbol, then load 3729 // the address from the GOT. This generates the pattern (PseudoLA sym), 3730 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3731 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3732 } 3733 3734 switch (getTargetMachine().getCodeModel()) { 3735 default: 3736 report_fatal_error("Unsupported code model for lowering"); 3737 case CodeModel::Small: { 3738 // Generate a sequence for accessing addresses within the first 2 GiB of 3739 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3740 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3741 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3742 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3743 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3744 } 3745 case CodeModel::Medium: { 3746 // Generate a sequence for accessing addresses within any 2GiB range within 3747 // the address space. This generates the pattern (PseudoLLA sym), which 3748 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3749 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3750 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3751 } 3752 } 3753 } 3754 3755 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3756 SelectionDAG &DAG) const { 3757 SDLoc DL(Op); 3758 EVT Ty = Op.getValueType(); 3759 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3760 int64_t Offset = N->getOffset(); 3761 MVT XLenVT = Subtarget.getXLenVT(); 3762 3763 const GlobalValue *GV = N->getGlobal(); 3764 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3765 SDValue Addr = getAddr(N, DAG, IsLocal); 3766 3767 // In order to maximise the opportunity for common subexpression elimination, 3768 // emit a separate ADD node for the global address offset instead of folding 3769 // it in the global address node. Later peephole optimisations may choose to 3770 // fold it back in when profitable. 3771 if (Offset != 0) 3772 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3773 DAG.getConstant(Offset, DL, XLenVT)); 3774 return Addr; 3775 } 3776 3777 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3778 SelectionDAG &DAG) const { 3779 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3780 3781 return getAddr(N, DAG); 3782 } 3783 3784 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3785 SelectionDAG &DAG) const { 3786 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3787 3788 return getAddr(N, DAG); 3789 } 3790 3791 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3792 SelectionDAG &DAG) const { 3793 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3794 3795 return getAddr(N, DAG); 3796 } 3797 3798 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3799 SelectionDAG &DAG, 3800 bool UseGOT) const { 3801 SDLoc DL(N); 3802 EVT Ty = getPointerTy(DAG.getDataLayout()); 3803 const GlobalValue *GV = N->getGlobal(); 3804 MVT XLenVT = Subtarget.getXLenVT(); 3805 3806 if (UseGOT) { 3807 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3808 // load the address from the GOT and add the thread pointer. This generates 3809 // the pattern (PseudoLA_TLS_IE sym), which expands to 3810 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3811 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3812 SDValue Load = 3813 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3814 3815 // Add the thread pointer. 3816 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3817 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3818 } 3819 3820 // Generate a sequence for accessing the address relative to the thread 3821 // pointer, with the appropriate adjustment for the thread pointer offset. 3822 // This generates the pattern 3823 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3824 SDValue AddrHi = 3825 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3826 SDValue AddrAdd = 3827 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3828 SDValue AddrLo = 3829 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3830 3831 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3832 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3833 SDValue MNAdd = SDValue( 3834 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3835 0); 3836 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3837 } 3838 3839 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3840 SelectionDAG &DAG) const { 3841 SDLoc DL(N); 3842 EVT Ty = getPointerTy(DAG.getDataLayout()); 3843 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3844 const GlobalValue *GV = N->getGlobal(); 3845 3846 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3847 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3848 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3849 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3850 SDValue Load = 3851 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3852 3853 // Prepare argument list to generate call. 3854 ArgListTy Args; 3855 ArgListEntry Entry; 3856 Entry.Node = Load; 3857 Entry.Ty = CallTy; 3858 Args.push_back(Entry); 3859 3860 // Setup call to __tls_get_addr. 3861 TargetLowering::CallLoweringInfo CLI(DAG); 3862 CLI.setDebugLoc(DL) 3863 .setChain(DAG.getEntryNode()) 3864 .setLibCallee(CallingConv::C, CallTy, 3865 DAG.getExternalSymbol("__tls_get_addr", Ty), 3866 std::move(Args)); 3867 3868 return LowerCallTo(CLI).first; 3869 } 3870 3871 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3872 SelectionDAG &DAG) const { 3873 SDLoc DL(Op); 3874 EVT Ty = Op.getValueType(); 3875 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3876 int64_t Offset = N->getOffset(); 3877 MVT XLenVT = Subtarget.getXLenVT(); 3878 3879 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3880 3881 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3882 CallingConv::GHC) 3883 report_fatal_error("In GHC calling convention TLS is not supported"); 3884 3885 SDValue Addr; 3886 switch (Model) { 3887 case TLSModel::LocalExec: 3888 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3889 break; 3890 case TLSModel::InitialExec: 3891 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3892 break; 3893 case TLSModel::LocalDynamic: 3894 case TLSModel::GeneralDynamic: 3895 Addr = getDynamicTLSAddr(N, DAG); 3896 break; 3897 } 3898 3899 // In order to maximise the opportunity for common subexpression elimination, 3900 // emit a separate ADD node for the global address offset instead of folding 3901 // it in the global address node. Later peephole optimisations may choose to 3902 // fold it back in when profitable. 3903 if (Offset != 0) 3904 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3905 DAG.getConstant(Offset, DL, XLenVT)); 3906 return Addr; 3907 } 3908 3909 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3910 SDValue CondV = Op.getOperand(0); 3911 SDValue TrueV = Op.getOperand(1); 3912 SDValue FalseV = Op.getOperand(2); 3913 SDLoc DL(Op); 3914 MVT VT = Op.getSimpleValueType(); 3915 MVT XLenVT = Subtarget.getXLenVT(); 3916 3917 // Lower vector SELECTs to VSELECTs by splatting the condition. 3918 if (VT.isVector()) { 3919 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3920 SDValue CondSplat = VT.isScalableVector() 3921 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3922 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3923 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3924 } 3925 3926 // If the result type is XLenVT and CondV is the output of a SETCC node 3927 // which also operated on XLenVT inputs, then merge the SETCC node into the 3928 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3929 // compare+branch instructions. i.e.: 3930 // (select (setcc lhs, rhs, cc), truev, falsev) 3931 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3932 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3933 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3934 SDValue LHS = CondV.getOperand(0); 3935 SDValue RHS = CondV.getOperand(1); 3936 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3937 ISD::CondCode CCVal = CC->get(); 3938 3939 // Special case for a select of 2 constants that have a diffence of 1. 3940 // Normally this is done by DAGCombine, but if the select is introduced by 3941 // type legalization or op legalization, we miss it. Restricting to SETLT 3942 // case for now because that is what signed saturating add/sub need. 3943 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3944 // but we would probably want to swap the true/false values if the condition 3945 // is SETGE/SETLE to avoid an XORI. 3946 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3947 CCVal == ISD::SETLT) { 3948 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3949 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3950 if (TrueVal - 1 == FalseVal) 3951 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3952 if (TrueVal + 1 == FalseVal) 3953 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3954 } 3955 3956 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3957 3958 SDValue TargetCC = DAG.getCondCode(CCVal); 3959 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3960 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3961 } 3962 3963 // Otherwise: 3964 // (select condv, truev, falsev) 3965 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3966 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3967 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3968 3969 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3970 3971 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3972 } 3973 3974 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3975 SDValue CondV = Op.getOperand(1); 3976 SDLoc DL(Op); 3977 MVT XLenVT = Subtarget.getXLenVT(); 3978 3979 if (CondV.getOpcode() == ISD::SETCC && 3980 CondV.getOperand(0).getValueType() == XLenVT) { 3981 SDValue LHS = CondV.getOperand(0); 3982 SDValue RHS = CondV.getOperand(1); 3983 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3984 3985 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3986 3987 SDValue TargetCC = DAG.getCondCode(CCVal); 3988 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3989 LHS, RHS, TargetCC, Op.getOperand(2)); 3990 } 3991 3992 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3993 CondV, DAG.getConstant(0, DL, XLenVT), 3994 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3995 } 3996 3997 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3998 MachineFunction &MF = DAG.getMachineFunction(); 3999 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4000 4001 SDLoc DL(Op); 4002 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4003 getPointerTy(MF.getDataLayout())); 4004 4005 // vastart just stores the address of the VarArgsFrameIndex slot into the 4006 // memory location argument. 4007 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4008 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4009 MachinePointerInfo(SV)); 4010 } 4011 4012 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4013 SelectionDAG &DAG) const { 4014 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4015 MachineFunction &MF = DAG.getMachineFunction(); 4016 MachineFrameInfo &MFI = MF.getFrameInfo(); 4017 MFI.setFrameAddressIsTaken(true); 4018 Register FrameReg = RI.getFrameRegister(MF); 4019 int XLenInBytes = Subtarget.getXLen() / 8; 4020 4021 EVT VT = Op.getValueType(); 4022 SDLoc DL(Op); 4023 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4024 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4025 while (Depth--) { 4026 int Offset = -(XLenInBytes * 2); 4027 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4028 DAG.getIntPtrConstant(Offset, DL)); 4029 FrameAddr = 4030 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4031 } 4032 return FrameAddr; 4033 } 4034 4035 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4036 SelectionDAG &DAG) const { 4037 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4038 MachineFunction &MF = DAG.getMachineFunction(); 4039 MachineFrameInfo &MFI = MF.getFrameInfo(); 4040 MFI.setReturnAddressIsTaken(true); 4041 MVT XLenVT = Subtarget.getXLenVT(); 4042 int XLenInBytes = Subtarget.getXLen() / 8; 4043 4044 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4045 return SDValue(); 4046 4047 EVT VT = Op.getValueType(); 4048 SDLoc DL(Op); 4049 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4050 if (Depth) { 4051 int Off = -XLenInBytes; 4052 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4053 SDValue Offset = DAG.getConstant(Off, DL, VT); 4054 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4055 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4056 MachinePointerInfo()); 4057 } 4058 4059 // Return the value of the return address register, marking it an implicit 4060 // live-in. 4061 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4062 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4063 } 4064 4065 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4066 SelectionDAG &DAG) const { 4067 SDLoc DL(Op); 4068 SDValue Lo = Op.getOperand(0); 4069 SDValue Hi = Op.getOperand(1); 4070 SDValue Shamt = Op.getOperand(2); 4071 EVT VT = Lo.getValueType(); 4072 4073 // if Shamt-XLEN < 0: // Shamt < XLEN 4074 // Lo = Lo << Shamt 4075 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4076 // else: 4077 // Lo = 0 4078 // Hi = Lo << (Shamt-XLEN) 4079 4080 SDValue Zero = DAG.getConstant(0, DL, VT); 4081 SDValue One = DAG.getConstant(1, DL, VT); 4082 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4083 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4084 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4085 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4086 4087 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4088 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4089 SDValue ShiftRightLo = 4090 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4091 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4092 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4093 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4094 4095 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4096 4097 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4098 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4099 4100 SDValue Parts[2] = {Lo, Hi}; 4101 return DAG.getMergeValues(Parts, DL); 4102 } 4103 4104 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4105 bool IsSRA) const { 4106 SDLoc DL(Op); 4107 SDValue Lo = Op.getOperand(0); 4108 SDValue Hi = Op.getOperand(1); 4109 SDValue Shamt = Op.getOperand(2); 4110 EVT VT = Lo.getValueType(); 4111 4112 // SRA expansion: 4113 // if Shamt-XLEN < 0: // Shamt < XLEN 4114 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4115 // Hi = Hi >>s Shamt 4116 // else: 4117 // Lo = Hi >>s (Shamt-XLEN); 4118 // Hi = Hi >>s (XLEN-1) 4119 // 4120 // SRL expansion: 4121 // if Shamt-XLEN < 0: // Shamt < XLEN 4122 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4123 // Hi = Hi >>u Shamt 4124 // else: 4125 // Lo = Hi >>u (Shamt-XLEN); 4126 // Hi = 0; 4127 4128 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4129 4130 SDValue Zero = DAG.getConstant(0, DL, VT); 4131 SDValue One = DAG.getConstant(1, DL, VT); 4132 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4133 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4134 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4135 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4136 4137 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4138 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4139 SDValue ShiftLeftHi = 4140 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4141 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4142 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4143 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4144 SDValue HiFalse = 4145 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4146 4147 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4148 4149 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4150 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4151 4152 SDValue Parts[2] = {Lo, Hi}; 4153 return DAG.getMergeValues(Parts, DL); 4154 } 4155 4156 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4157 // legal equivalently-sized i8 type, so we can use that as a go-between. 4158 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4159 SelectionDAG &DAG) const { 4160 SDLoc DL(Op); 4161 MVT VT = Op.getSimpleValueType(); 4162 SDValue SplatVal = Op.getOperand(0); 4163 // All-zeros or all-ones splats are handled specially. 4164 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4165 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4166 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4167 } 4168 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4169 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4170 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4171 } 4172 MVT XLenVT = Subtarget.getXLenVT(); 4173 assert(SplatVal.getValueType() == XLenVT && 4174 "Unexpected type for i1 splat value"); 4175 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4176 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4177 DAG.getConstant(1, DL, XLenVT)); 4178 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4179 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4180 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4181 } 4182 4183 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4184 // illegal (currently only vXi64 RV32). 4185 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4186 // them to VMV_V_X_VL. 4187 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4188 SelectionDAG &DAG) const { 4189 SDLoc DL(Op); 4190 MVT VecVT = Op.getSimpleValueType(); 4191 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4192 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4193 4194 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4195 SDValue Lo = Op.getOperand(0); 4196 SDValue Hi = Op.getOperand(1); 4197 4198 if (VecVT.isFixedLengthVector()) { 4199 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4200 SDLoc DL(Op); 4201 SDValue Mask, VL; 4202 std::tie(Mask, VL) = 4203 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4204 4205 SDValue Res = 4206 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4207 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4208 } 4209 4210 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4211 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4212 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4213 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4214 // node in order to try and match RVV vector/scalar instructions. 4215 if ((LoC >> 31) == HiC) 4216 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4217 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4218 } 4219 4220 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4221 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4222 isa<ConstantSDNode>(Hi.getOperand(1)) && 4223 Hi.getConstantOperandVal(1) == 31) 4224 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4225 DAG.getRegister(RISCV::X0, MVT::i32)); 4226 4227 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4228 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4229 DAG.getUNDEF(VecVT), Lo, Hi, 4230 DAG.getRegister(RISCV::X0, MVT::i32)); 4231 } 4232 4233 // Custom-lower extensions from mask vectors by using a vselect either with 1 4234 // for zero/any-extension or -1 for sign-extension: 4235 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4236 // Note that any-extension is lowered identically to zero-extension. 4237 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4238 int64_t ExtTrueVal) const { 4239 SDLoc DL(Op); 4240 MVT VecVT = Op.getSimpleValueType(); 4241 SDValue Src = Op.getOperand(0); 4242 // Only custom-lower extensions from mask types 4243 assert(Src.getValueType().isVector() && 4244 Src.getValueType().getVectorElementType() == MVT::i1); 4245 4246 MVT XLenVT = Subtarget.getXLenVT(); 4247 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4248 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4249 4250 if (VecVT.isScalableVector()) { 4251 // Be careful not to introduce illegal scalar types at this stage, and be 4252 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4253 // illegal and must be expanded. Since we know that the constants are 4254 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4255 bool IsRV32E64 = 4256 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4257 4258 if (!IsRV32E64) { 4259 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4260 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4261 } else { 4262 SplatZero = 4263 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4264 SplatZero, DAG.getRegister(RISCV::X0, XLenVT)); 4265 SplatTrueVal = 4266 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4267 SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT)); 4268 } 4269 4270 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4271 } 4272 4273 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4274 MVT I1ContainerVT = 4275 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4276 4277 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4278 4279 SDValue Mask, VL; 4280 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4281 4282 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4283 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4284 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4285 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4286 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4287 SplatTrueVal, SplatZero, VL); 4288 4289 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4290 } 4291 4292 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4293 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4294 MVT ExtVT = Op.getSimpleValueType(); 4295 // Only custom-lower extensions from fixed-length vector types. 4296 if (!ExtVT.isFixedLengthVector()) 4297 return Op; 4298 MVT VT = Op.getOperand(0).getSimpleValueType(); 4299 // Grab the canonical container type for the extended type. Infer the smaller 4300 // type from that to ensure the same number of vector elements, as we know 4301 // the LMUL will be sufficient to hold the smaller type. 4302 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4303 // Get the extended container type manually to ensure the same number of 4304 // vector elements between source and dest. 4305 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4306 ContainerExtVT.getVectorElementCount()); 4307 4308 SDValue Op1 = 4309 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4310 4311 SDLoc DL(Op); 4312 SDValue Mask, VL; 4313 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4314 4315 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4316 4317 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4318 } 4319 4320 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4321 // setcc operation: 4322 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4323 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4324 SelectionDAG &DAG) const { 4325 SDLoc DL(Op); 4326 EVT MaskVT = Op.getValueType(); 4327 // Only expect to custom-lower truncations to mask types 4328 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4329 "Unexpected type for vector mask lowering"); 4330 SDValue Src = Op.getOperand(0); 4331 MVT VecVT = Src.getSimpleValueType(); 4332 4333 // If this is a fixed vector, we need to convert it to a scalable vector. 4334 MVT ContainerVT = VecVT; 4335 if (VecVT.isFixedLengthVector()) { 4336 ContainerVT = getContainerForFixedLengthVector(VecVT); 4337 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4338 } 4339 4340 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4341 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4342 4343 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4344 DAG.getUNDEF(ContainerVT), SplatOne); 4345 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4346 DAG.getUNDEF(ContainerVT), SplatZero); 4347 4348 if (VecVT.isScalableVector()) { 4349 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4350 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4351 } 4352 4353 SDValue Mask, VL; 4354 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4355 4356 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4357 SDValue Trunc = 4358 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4359 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4360 DAG.getCondCode(ISD::SETNE), Mask, VL); 4361 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4362 } 4363 4364 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4365 // first position of a vector, and that vector is slid up to the insert index. 4366 // By limiting the active vector length to index+1 and merging with the 4367 // original vector (with an undisturbed tail policy for elements >= VL), we 4368 // achieve the desired result of leaving all elements untouched except the one 4369 // at VL-1, which is replaced with the desired value. 4370 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4371 SelectionDAG &DAG) const { 4372 SDLoc DL(Op); 4373 MVT VecVT = Op.getSimpleValueType(); 4374 SDValue Vec = Op.getOperand(0); 4375 SDValue Val = Op.getOperand(1); 4376 SDValue Idx = Op.getOperand(2); 4377 4378 if (VecVT.getVectorElementType() == MVT::i1) { 4379 // FIXME: For now we just promote to an i8 vector and insert into that, 4380 // but this is probably not optimal. 4381 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4382 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4383 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4384 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4385 } 4386 4387 MVT ContainerVT = VecVT; 4388 // If the operand is a fixed-length vector, convert to a scalable one. 4389 if (VecVT.isFixedLengthVector()) { 4390 ContainerVT = getContainerForFixedLengthVector(VecVT); 4391 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4392 } 4393 4394 MVT XLenVT = Subtarget.getXLenVT(); 4395 4396 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4397 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4398 // Even i64-element vectors on RV32 can be lowered without scalar 4399 // legalization if the most-significant 32 bits of the value are not affected 4400 // by the sign-extension of the lower 32 bits. 4401 // TODO: We could also catch sign extensions of a 32-bit value. 4402 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4403 const auto *CVal = cast<ConstantSDNode>(Val); 4404 if (isInt<32>(CVal->getSExtValue())) { 4405 IsLegalInsert = true; 4406 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4407 } 4408 } 4409 4410 SDValue Mask, VL; 4411 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4412 4413 SDValue ValInVec; 4414 4415 if (IsLegalInsert) { 4416 unsigned Opc = 4417 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4418 if (isNullConstant(Idx)) { 4419 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4420 if (!VecVT.isFixedLengthVector()) 4421 return Vec; 4422 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4423 } 4424 ValInVec = 4425 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4426 } else { 4427 // On RV32, i64-element vectors must be specially handled to place the 4428 // value at element 0, by using two vslide1up instructions in sequence on 4429 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4430 // this. 4431 SDValue One = DAG.getConstant(1, DL, XLenVT); 4432 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4433 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4434 MVT I32ContainerVT = 4435 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4436 SDValue I32Mask = 4437 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4438 // Limit the active VL to two. 4439 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4440 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4441 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4442 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4443 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4444 // First slide in the hi value, then the lo in underneath it. 4445 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4446 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4447 I32Mask, InsertI64VL); 4448 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4449 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4450 I32Mask, InsertI64VL); 4451 // Bitcast back to the right container type. 4452 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4453 } 4454 4455 // Now that the value is in a vector, slide it into position. 4456 SDValue InsertVL = 4457 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4458 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4459 ValInVec, Idx, Mask, InsertVL); 4460 if (!VecVT.isFixedLengthVector()) 4461 return Slideup; 4462 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4463 } 4464 4465 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4466 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4467 // types this is done using VMV_X_S to allow us to glean information about the 4468 // sign bits of the result. 4469 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4470 SelectionDAG &DAG) const { 4471 SDLoc DL(Op); 4472 SDValue Idx = Op.getOperand(1); 4473 SDValue Vec = Op.getOperand(0); 4474 EVT EltVT = Op.getValueType(); 4475 MVT VecVT = Vec.getSimpleValueType(); 4476 MVT XLenVT = Subtarget.getXLenVT(); 4477 4478 if (VecVT.getVectorElementType() == MVT::i1) { 4479 if (VecVT.isFixedLengthVector()) { 4480 unsigned NumElts = VecVT.getVectorNumElements(); 4481 if (NumElts >= 8) { 4482 MVT WideEltVT; 4483 unsigned WidenVecLen; 4484 SDValue ExtractElementIdx; 4485 SDValue ExtractBitIdx; 4486 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4487 MVT LargestEltVT = MVT::getIntegerVT( 4488 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4489 if (NumElts <= LargestEltVT.getSizeInBits()) { 4490 assert(isPowerOf2_32(NumElts) && 4491 "the number of elements should be power of 2"); 4492 WideEltVT = MVT::getIntegerVT(NumElts); 4493 WidenVecLen = 1; 4494 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4495 ExtractBitIdx = Idx; 4496 } else { 4497 WideEltVT = LargestEltVT; 4498 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4499 // extract element index = index / element width 4500 ExtractElementIdx = DAG.getNode( 4501 ISD::SRL, DL, XLenVT, Idx, 4502 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4503 // mask bit index = index % element width 4504 ExtractBitIdx = DAG.getNode( 4505 ISD::AND, DL, XLenVT, Idx, 4506 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4507 } 4508 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4509 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4510 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4511 Vec, ExtractElementIdx); 4512 // Extract the bit from GPR. 4513 SDValue ShiftRight = 4514 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4515 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4516 DAG.getConstant(1, DL, XLenVT)); 4517 } 4518 } 4519 // Otherwise, promote to an i8 vector and extract from that. 4520 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4521 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4522 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4523 } 4524 4525 // If this is a fixed vector, we need to convert it to a scalable vector. 4526 MVT ContainerVT = VecVT; 4527 if (VecVT.isFixedLengthVector()) { 4528 ContainerVT = getContainerForFixedLengthVector(VecVT); 4529 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4530 } 4531 4532 // If the index is 0, the vector is already in the right position. 4533 if (!isNullConstant(Idx)) { 4534 // Use a VL of 1 to avoid processing more elements than we need. 4535 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4536 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4537 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4538 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4539 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4540 } 4541 4542 if (!EltVT.isInteger()) { 4543 // Floating-point extracts are handled in TableGen. 4544 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4545 DAG.getConstant(0, DL, XLenVT)); 4546 } 4547 4548 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4549 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4550 } 4551 4552 // Some RVV intrinsics may claim that they want an integer operand to be 4553 // promoted or expanded. 4554 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4555 const RISCVSubtarget &Subtarget) { 4556 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4557 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4558 "Unexpected opcode"); 4559 4560 if (!Subtarget.hasVInstructions()) 4561 return SDValue(); 4562 4563 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4564 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4565 SDLoc DL(Op); 4566 4567 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4568 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4569 if (!II || !II->hasSplatOperand()) 4570 return SDValue(); 4571 4572 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4573 assert(SplatOp < Op.getNumOperands()); 4574 4575 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4576 SDValue &ScalarOp = Operands[SplatOp]; 4577 MVT OpVT = ScalarOp.getSimpleValueType(); 4578 MVT XLenVT = Subtarget.getXLenVT(); 4579 4580 // If this isn't a scalar, or its type is XLenVT we're done. 4581 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4582 return SDValue(); 4583 4584 // Simplest case is that the operand needs to be promoted to XLenVT. 4585 if (OpVT.bitsLT(XLenVT)) { 4586 // If the operand is a constant, sign extend to increase our chances 4587 // of being able to use a .vi instruction. ANY_EXTEND would become a 4588 // a zero extend and the simm5 check in isel would fail. 4589 // FIXME: Should we ignore the upper bits in isel instead? 4590 unsigned ExtOpc = 4591 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4592 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4593 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4594 } 4595 4596 // Use the previous operand to get the vXi64 VT. The result might be a mask 4597 // VT for compares. Using the previous operand assumes that the previous 4598 // operand will never have a smaller element size than a scalar operand and 4599 // that a widening operation never uses SEW=64. 4600 // NOTE: If this fails the below assert, we can probably just find the 4601 // element count from any operand or result and use it to construct the VT. 4602 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4603 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4604 4605 // The more complex case is when the scalar is larger than XLenVT. 4606 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4607 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4608 4609 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4610 // on the instruction to sign-extend since SEW>XLEN. 4611 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4612 if (isInt<32>(CVal->getSExtValue())) { 4613 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4614 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4615 } 4616 } 4617 4618 // We need to convert the scalar to a splat vector. 4619 // FIXME: Can we implicitly truncate the scalar if it is known to 4620 // be sign extended? 4621 SDValue VL = getVLOperand(Op); 4622 assert(VL.getValueType() == XLenVT); 4623 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4624 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4625 } 4626 4627 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4628 SelectionDAG &DAG) const { 4629 unsigned IntNo = Op.getConstantOperandVal(0); 4630 SDLoc DL(Op); 4631 MVT XLenVT = Subtarget.getXLenVT(); 4632 4633 switch (IntNo) { 4634 default: 4635 break; // Don't custom lower most intrinsics. 4636 case Intrinsic::thread_pointer: { 4637 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4638 return DAG.getRegister(RISCV::X4, PtrVT); 4639 } 4640 case Intrinsic::riscv_orc_b: 4641 case Intrinsic::riscv_brev8: { 4642 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4643 unsigned Opc = 4644 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4645 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4646 DAG.getConstant(7, DL, XLenVT)); 4647 } 4648 case Intrinsic::riscv_grev: 4649 case Intrinsic::riscv_gorc: { 4650 unsigned Opc = 4651 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4652 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4653 } 4654 case Intrinsic::riscv_zip: 4655 case Intrinsic::riscv_unzip: { 4656 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4657 // For i32 the immdiate is 15. For i64 the immediate is 31. 4658 unsigned Opc = 4659 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4660 unsigned BitWidth = Op.getValueSizeInBits(); 4661 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4662 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4663 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4664 } 4665 case Intrinsic::riscv_shfl: 4666 case Intrinsic::riscv_unshfl: { 4667 unsigned Opc = 4668 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4669 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4670 } 4671 case Intrinsic::riscv_bcompress: 4672 case Intrinsic::riscv_bdecompress: { 4673 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4674 : RISCVISD::BDECOMPRESS; 4675 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4676 } 4677 case Intrinsic::riscv_bfp: 4678 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4679 Op.getOperand(2)); 4680 case Intrinsic::riscv_fsl: 4681 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4682 Op.getOperand(2), Op.getOperand(3)); 4683 case Intrinsic::riscv_fsr: 4684 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4685 Op.getOperand(2), Op.getOperand(3)); 4686 case Intrinsic::riscv_vmv_x_s: 4687 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4688 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4689 Op.getOperand(1)); 4690 case Intrinsic::riscv_vmv_v_x: 4691 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4692 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4693 Subtarget); 4694 case Intrinsic::riscv_vfmv_v_f: 4695 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4696 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4697 case Intrinsic::riscv_vmv_s_x: { 4698 SDValue Scalar = Op.getOperand(2); 4699 4700 if (Scalar.getValueType().bitsLE(XLenVT)) { 4701 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4702 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4703 Op.getOperand(1), Scalar, Op.getOperand(3)); 4704 } 4705 4706 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4707 4708 // This is an i64 value that lives in two scalar registers. We have to 4709 // insert this in a convoluted way. First we build vXi64 splat containing 4710 // the/ two values that we assemble using some bit math. Next we'll use 4711 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4712 // to merge element 0 from our splat into the source vector. 4713 // FIXME: This is probably not the best way to do this, but it is 4714 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4715 // point. 4716 // sw lo, (a0) 4717 // sw hi, 4(a0) 4718 // vlse vX, (a0) 4719 // 4720 // vid.v vVid 4721 // vmseq.vx mMask, vVid, 0 4722 // vmerge.vvm vDest, vSrc, vVal, mMask 4723 MVT VT = Op.getSimpleValueType(); 4724 SDValue Vec = Op.getOperand(1); 4725 SDValue VL = getVLOperand(Op); 4726 4727 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4728 if (Op.getOperand(1).isUndef()) 4729 return SplattedVal; 4730 SDValue SplattedIdx = 4731 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4732 DAG.getConstant(0, DL, MVT::i32), VL); 4733 4734 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4735 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4736 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4737 SDValue SelectCond = 4738 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4739 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4740 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4741 Vec, VL); 4742 } 4743 case Intrinsic::riscv_vslide1up: 4744 case Intrinsic::riscv_vslide1down: 4745 case Intrinsic::riscv_vslide1up_mask: 4746 case Intrinsic::riscv_vslide1down_mask: { 4747 // We need to special case these when the scalar is larger than XLen. 4748 unsigned NumOps = Op.getNumOperands(); 4749 bool IsMasked = NumOps == 7; 4750 SDValue Scalar = Op.getOperand(3); 4751 if (Scalar.getValueType().bitsLE(XLenVT)) 4752 break; 4753 4754 // Splatting a sign extended constant is fine. 4755 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4756 if (isInt<32>(CVal->getSExtValue())) 4757 break; 4758 4759 MVT VT = Op.getSimpleValueType(); 4760 assert(VT.getVectorElementType() == MVT::i64 && 4761 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4762 4763 // Convert the vector source to the equivalent nxvXi32 vector. 4764 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4765 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2)); 4766 4767 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4768 DAG.getConstant(0, DL, XLenVT)); 4769 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4770 DAG.getConstant(1, DL, XLenVT)); 4771 4772 // Double the VL since we halved SEW. 4773 SDValue VL = getVLOperand(Op); 4774 SDValue I32VL = 4775 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4776 4777 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4778 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4779 4780 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4781 // instructions. 4782 SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1)); 4783 if (!IsMasked) { 4784 if (IntNo == Intrinsic::riscv_vslide1up) { 4785 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4786 ScalarHi, I32Mask, I32VL); 4787 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4788 ScalarLo, I32Mask, I32VL); 4789 } else { 4790 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4791 ScalarLo, I32Mask, I32VL); 4792 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4793 ScalarHi, I32Mask, I32VL); 4794 } 4795 } else { 4796 // TODO Those VSLIDE1 could be TAMA because we use vmerge to select 4797 // maskedoff 4798 SDValue Undef = DAG.getUNDEF(I32VT); 4799 if (IntNo == Intrinsic::riscv_vslide1up_mask) { 4800 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4801 ScalarHi, I32Mask, I32VL); 4802 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4803 ScalarLo, I32Mask, I32VL); 4804 } else { 4805 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4806 ScalarLo, I32Mask, I32VL); 4807 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4808 ScalarHi, I32Mask, I32VL); 4809 } 4810 } 4811 4812 // Convert back to nxvXi64. 4813 Vec = DAG.getBitcast(VT, Vec); 4814 4815 if (!IsMasked) 4816 return Vec; 4817 // Apply mask after the operation. 4818 SDValue Mask = Op.getOperand(NumOps - 3); 4819 SDValue MaskedOff = Op.getOperand(1); 4820 // Assume Policy operand is the last operand. 4821 uint64_t Policy = Op.getConstantOperandVal(NumOps - 1); 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 VL); 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, VL); 4832 } 4833 } 4834 4835 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4836 } 4837 4838 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4839 SelectionDAG &DAG) const { 4840 unsigned IntNo = Op.getConstantOperandVal(1); 4841 switch (IntNo) { 4842 default: 4843 break; 4844 case Intrinsic::riscv_masked_strided_load: { 4845 SDLoc DL(Op); 4846 MVT XLenVT = Subtarget.getXLenVT(); 4847 4848 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4849 // the selection of the masked intrinsics doesn't do this for us. 4850 SDValue Mask = Op.getOperand(5); 4851 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4852 4853 MVT VT = Op->getSimpleValueType(0); 4854 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4855 4856 SDValue PassThru = Op.getOperand(2); 4857 if (!IsUnmasked) { 4858 MVT MaskVT = 4859 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4860 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4861 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4862 } 4863 4864 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4865 4866 SDValue IntID = DAG.getTargetConstant( 4867 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4868 XLenVT); 4869 4870 auto *Load = cast<MemIntrinsicSDNode>(Op); 4871 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4872 if (IsUnmasked) 4873 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4874 else 4875 Ops.push_back(PassThru); 4876 Ops.push_back(Op.getOperand(3)); // Ptr 4877 Ops.push_back(Op.getOperand(4)); // Stride 4878 if (!IsUnmasked) 4879 Ops.push_back(Mask); 4880 Ops.push_back(VL); 4881 if (!IsUnmasked) { 4882 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4883 Ops.push_back(Policy); 4884 } 4885 4886 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4887 SDValue Result = 4888 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4889 Load->getMemoryVT(), Load->getMemOperand()); 4890 SDValue Chain = Result.getValue(1); 4891 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4892 return DAG.getMergeValues({Result, Chain}, DL); 4893 } 4894 } 4895 4896 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4897 } 4898 4899 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4900 SelectionDAG &DAG) const { 4901 unsigned IntNo = Op.getConstantOperandVal(1); 4902 switch (IntNo) { 4903 default: 4904 break; 4905 case Intrinsic::riscv_masked_strided_store: { 4906 SDLoc DL(Op); 4907 MVT XLenVT = Subtarget.getXLenVT(); 4908 4909 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4910 // the selection of the masked intrinsics doesn't do this for us. 4911 SDValue Mask = Op.getOperand(5); 4912 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4913 4914 SDValue Val = Op.getOperand(2); 4915 MVT VT = Val.getSimpleValueType(); 4916 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4917 4918 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4919 if (!IsUnmasked) { 4920 MVT MaskVT = 4921 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4922 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4923 } 4924 4925 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4926 4927 SDValue IntID = DAG.getTargetConstant( 4928 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4929 XLenVT); 4930 4931 auto *Store = cast<MemIntrinsicSDNode>(Op); 4932 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4933 Ops.push_back(Val); 4934 Ops.push_back(Op.getOperand(3)); // Ptr 4935 Ops.push_back(Op.getOperand(4)); // Stride 4936 if (!IsUnmasked) 4937 Ops.push_back(Mask); 4938 Ops.push_back(VL); 4939 4940 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4941 Ops, Store->getMemoryVT(), 4942 Store->getMemOperand()); 4943 } 4944 } 4945 4946 return SDValue(); 4947 } 4948 4949 static MVT getLMUL1VT(MVT VT) { 4950 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4951 "Unexpected vector MVT"); 4952 return MVT::getScalableVectorVT( 4953 VT.getVectorElementType(), 4954 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4955 } 4956 4957 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4958 switch (ISDOpcode) { 4959 default: 4960 llvm_unreachable("Unhandled reduction"); 4961 case ISD::VECREDUCE_ADD: 4962 return RISCVISD::VECREDUCE_ADD_VL; 4963 case ISD::VECREDUCE_UMAX: 4964 return RISCVISD::VECREDUCE_UMAX_VL; 4965 case ISD::VECREDUCE_SMAX: 4966 return RISCVISD::VECREDUCE_SMAX_VL; 4967 case ISD::VECREDUCE_UMIN: 4968 return RISCVISD::VECREDUCE_UMIN_VL; 4969 case ISD::VECREDUCE_SMIN: 4970 return RISCVISD::VECREDUCE_SMIN_VL; 4971 case ISD::VECREDUCE_AND: 4972 return RISCVISD::VECREDUCE_AND_VL; 4973 case ISD::VECREDUCE_OR: 4974 return RISCVISD::VECREDUCE_OR_VL; 4975 case ISD::VECREDUCE_XOR: 4976 return RISCVISD::VECREDUCE_XOR_VL; 4977 } 4978 } 4979 4980 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4981 SelectionDAG &DAG, 4982 bool IsVP) const { 4983 SDLoc DL(Op); 4984 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4985 MVT VecVT = Vec.getSimpleValueType(); 4986 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4987 Op.getOpcode() == ISD::VECREDUCE_OR || 4988 Op.getOpcode() == ISD::VECREDUCE_XOR || 4989 Op.getOpcode() == ISD::VP_REDUCE_AND || 4990 Op.getOpcode() == ISD::VP_REDUCE_OR || 4991 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4992 "Unexpected reduction lowering"); 4993 4994 MVT XLenVT = Subtarget.getXLenVT(); 4995 assert(Op.getValueType() == XLenVT && 4996 "Expected reduction output to be legalized to XLenVT"); 4997 4998 MVT ContainerVT = VecVT; 4999 if (VecVT.isFixedLengthVector()) { 5000 ContainerVT = getContainerForFixedLengthVector(VecVT); 5001 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5002 } 5003 5004 SDValue Mask, VL; 5005 if (IsVP) { 5006 Mask = Op.getOperand(2); 5007 VL = Op.getOperand(3); 5008 } else { 5009 std::tie(Mask, VL) = 5010 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5011 } 5012 5013 unsigned BaseOpc; 5014 ISD::CondCode CC; 5015 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5016 5017 switch (Op.getOpcode()) { 5018 default: 5019 llvm_unreachable("Unhandled reduction"); 5020 case ISD::VECREDUCE_AND: 5021 case ISD::VP_REDUCE_AND: { 5022 // vcpop ~x == 0 5023 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5024 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5025 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5026 CC = ISD::SETEQ; 5027 BaseOpc = ISD::AND; 5028 break; 5029 } 5030 case ISD::VECREDUCE_OR: 5031 case ISD::VP_REDUCE_OR: 5032 // vcpop x != 0 5033 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5034 CC = ISD::SETNE; 5035 BaseOpc = ISD::OR; 5036 break; 5037 case ISD::VECREDUCE_XOR: 5038 case ISD::VP_REDUCE_XOR: { 5039 // ((vcpop x) & 1) != 0 5040 SDValue One = DAG.getConstant(1, DL, XLenVT); 5041 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5042 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5043 CC = ISD::SETNE; 5044 BaseOpc = ISD::XOR; 5045 break; 5046 } 5047 } 5048 5049 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5050 5051 if (!IsVP) 5052 return SetCC; 5053 5054 // Now include the start value in the operation. 5055 // Note that we must return the start value when no elements are operated 5056 // upon. The vcpop instructions we've emitted in each case above will return 5057 // 0 for an inactive vector, and so we've already received the neutral value: 5058 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5059 // can simply include the start value. 5060 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5061 } 5062 5063 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5064 SelectionDAG &DAG) const { 5065 SDLoc DL(Op); 5066 SDValue Vec = Op.getOperand(0); 5067 EVT VecEVT = Vec.getValueType(); 5068 5069 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5070 5071 // Due to ordering in legalize types we may have a vector type that needs to 5072 // be split. Do that manually so we can get down to a legal type. 5073 while (getTypeAction(*DAG.getContext(), VecEVT) == 5074 TargetLowering::TypeSplitVector) { 5075 SDValue Lo, Hi; 5076 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5077 VecEVT = Lo.getValueType(); 5078 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5079 } 5080 5081 // TODO: The type may need to be widened rather than split. Or widened before 5082 // it can be split. 5083 if (!isTypeLegal(VecEVT)) 5084 return SDValue(); 5085 5086 MVT VecVT = VecEVT.getSimpleVT(); 5087 MVT VecEltVT = VecVT.getVectorElementType(); 5088 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5089 5090 MVT ContainerVT = VecVT; 5091 if (VecVT.isFixedLengthVector()) { 5092 ContainerVT = getContainerForFixedLengthVector(VecVT); 5093 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5094 } 5095 5096 MVT M1VT = getLMUL1VT(ContainerVT); 5097 MVT XLenVT = Subtarget.getXLenVT(); 5098 5099 SDValue Mask, VL; 5100 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5101 5102 SDValue NeutralElem = 5103 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5104 SDValue IdentitySplat = 5105 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5106 M1VT, DL, DAG, Subtarget); 5107 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5108 IdentitySplat, Mask, VL); 5109 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5110 DAG.getConstant(0, DL, XLenVT)); 5111 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5112 } 5113 5114 // Given a reduction op, this function returns the matching reduction opcode, 5115 // the vector SDValue and the scalar SDValue required to lower this to a 5116 // RISCVISD node. 5117 static std::tuple<unsigned, SDValue, SDValue> 5118 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5119 SDLoc DL(Op); 5120 auto Flags = Op->getFlags(); 5121 unsigned Opcode = Op.getOpcode(); 5122 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5123 switch (Opcode) { 5124 default: 5125 llvm_unreachable("Unhandled reduction"); 5126 case ISD::VECREDUCE_FADD: { 5127 // Use positive zero if we can. It is cheaper to materialize. 5128 SDValue Zero = 5129 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5130 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5131 } 5132 case ISD::VECREDUCE_SEQ_FADD: 5133 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5134 Op.getOperand(0)); 5135 case ISD::VECREDUCE_FMIN: 5136 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5137 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5138 case ISD::VECREDUCE_FMAX: 5139 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5140 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5141 } 5142 } 5143 5144 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5145 SelectionDAG &DAG) const { 5146 SDLoc DL(Op); 5147 MVT VecEltVT = Op.getSimpleValueType(); 5148 5149 unsigned RVVOpcode; 5150 SDValue VectorVal, ScalarVal; 5151 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5152 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5153 MVT VecVT = VectorVal.getSimpleValueType(); 5154 5155 MVT ContainerVT = VecVT; 5156 if (VecVT.isFixedLengthVector()) { 5157 ContainerVT = getContainerForFixedLengthVector(VecVT); 5158 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5159 } 5160 5161 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5162 MVT XLenVT = Subtarget.getXLenVT(); 5163 5164 SDValue Mask, VL; 5165 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5166 5167 SDValue ScalarSplat = 5168 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5169 M1VT, DL, DAG, Subtarget); 5170 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5171 VectorVal, ScalarSplat, Mask, VL); 5172 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5173 DAG.getConstant(0, DL, XLenVT)); 5174 } 5175 5176 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5177 switch (ISDOpcode) { 5178 default: 5179 llvm_unreachable("Unhandled reduction"); 5180 case ISD::VP_REDUCE_ADD: 5181 return RISCVISD::VECREDUCE_ADD_VL; 5182 case ISD::VP_REDUCE_UMAX: 5183 return RISCVISD::VECREDUCE_UMAX_VL; 5184 case ISD::VP_REDUCE_SMAX: 5185 return RISCVISD::VECREDUCE_SMAX_VL; 5186 case ISD::VP_REDUCE_UMIN: 5187 return RISCVISD::VECREDUCE_UMIN_VL; 5188 case ISD::VP_REDUCE_SMIN: 5189 return RISCVISD::VECREDUCE_SMIN_VL; 5190 case ISD::VP_REDUCE_AND: 5191 return RISCVISD::VECREDUCE_AND_VL; 5192 case ISD::VP_REDUCE_OR: 5193 return RISCVISD::VECREDUCE_OR_VL; 5194 case ISD::VP_REDUCE_XOR: 5195 return RISCVISD::VECREDUCE_XOR_VL; 5196 case ISD::VP_REDUCE_FADD: 5197 return RISCVISD::VECREDUCE_FADD_VL; 5198 case ISD::VP_REDUCE_SEQ_FADD: 5199 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5200 case ISD::VP_REDUCE_FMAX: 5201 return RISCVISD::VECREDUCE_FMAX_VL; 5202 case ISD::VP_REDUCE_FMIN: 5203 return RISCVISD::VECREDUCE_FMIN_VL; 5204 } 5205 } 5206 5207 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5208 SelectionDAG &DAG) const { 5209 SDLoc DL(Op); 5210 SDValue Vec = Op.getOperand(1); 5211 EVT VecEVT = Vec.getValueType(); 5212 5213 // TODO: The type may need to be widened rather than split. Or widened before 5214 // it can be split. 5215 if (!isTypeLegal(VecEVT)) 5216 return SDValue(); 5217 5218 MVT VecVT = VecEVT.getSimpleVT(); 5219 MVT VecEltVT = VecVT.getVectorElementType(); 5220 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5221 5222 MVT ContainerVT = VecVT; 5223 if (VecVT.isFixedLengthVector()) { 5224 ContainerVT = getContainerForFixedLengthVector(VecVT); 5225 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5226 } 5227 5228 SDValue VL = Op.getOperand(3); 5229 SDValue Mask = Op.getOperand(2); 5230 5231 MVT M1VT = getLMUL1VT(ContainerVT); 5232 MVT XLenVT = Subtarget.getXLenVT(); 5233 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5234 5235 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5236 DAG.getConstant(1, DL, XLenVT), M1VT, 5237 DL, DAG, Subtarget); 5238 SDValue Reduction = 5239 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5240 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5241 DAG.getConstant(0, DL, XLenVT)); 5242 if (!VecVT.isInteger()) 5243 return Elt0; 5244 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5245 } 5246 5247 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5248 SelectionDAG &DAG) const { 5249 SDValue Vec = Op.getOperand(0); 5250 SDValue SubVec = Op.getOperand(1); 5251 MVT VecVT = Vec.getSimpleValueType(); 5252 MVT SubVecVT = SubVec.getSimpleValueType(); 5253 5254 SDLoc DL(Op); 5255 MVT XLenVT = Subtarget.getXLenVT(); 5256 unsigned OrigIdx = Op.getConstantOperandVal(2); 5257 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5258 5259 // We don't have the ability to slide mask vectors up indexed by their i1 5260 // elements; the smallest we can do is i8. Often we are able to bitcast to 5261 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5262 // into a scalable one, we might not necessarily have enough scalable 5263 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5264 if (SubVecVT.getVectorElementType() == MVT::i1 && 5265 (OrigIdx != 0 || !Vec.isUndef())) { 5266 if (VecVT.getVectorMinNumElements() >= 8 && 5267 SubVecVT.getVectorMinNumElements() >= 8) { 5268 assert(OrigIdx % 8 == 0 && "Invalid index"); 5269 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5270 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5271 "Unexpected mask vector lowering"); 5272 OrigIdx /= 8; 5273 SubVecVT = 5274 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5275 SubVecVT.isScalableVector()); 5276 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5277 VecVT.isScalableVector()); 5278 Vec = DAG.getBitcast(VecVT, Vec); 5279 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5280 } else { 5281 // We can't slide this mask vector up indexed by its i1 elements. 5282 // This poses a problem when we wish to insert a scalable vector which 5283 // can't be re-expressed as a larger type. Just choose the slow path and 5284 // extend to a larger type, then truncate back down. 5285 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5286 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5287 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5288 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5289 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5290 Op.getOperand(2)); 5291 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5292 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5293 } 5294 } 5295 5296 // If the subvector vector is a fixed-length type, we cannot use subregister 5297 // manipulation to simplify the codegen; we don't know which register of a 5298 // LMUL group contains the specific subvector as we only know the minimum 5299 // register size. Therefore we must slide the vector group up the full 5300 // amount. 5301 if (SubVecVT.isFixedLengthVector()) { 5302 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5303 return Op; 5304 MVT ContainerVT = VecVT; 5305 if (VecVT.isFixedLengthVector()) { 5306 ContainerVT = getContainerForFixedLengthVector(VecVT); 5307 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5308 } 5309 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5310 DAG.getUNDEF(ContainerVT), SubVec, 5311 DAG.getConstant(0, DL, XLenVT)); 5312 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5313 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5314 return DAG.getBitcast(Op.getValueType(), SubVec); 5315 } 5316 SDValue Mask = 5317 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5318 // Set the vector length to only the number of elements we care about. Note 5319 // that for slideup this includes the offset. 5320 SDValue VL = 5321 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5322 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5323 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5324 SubVec, SlideupAmt, Mask, VL); 5325 if (VecVT.isFixedLengthVector()) 5326 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5327 return DAG.getBitcast(Op.getValueType(), Slideup); 5328 } 5329 5330 unsigned SubRegIdx, RemIdx; 5331 std::tie(SubRegIdx, RemIdx) = 5332 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5333 VecVT, SubVecVT, OrigIdx, TRI); 5334 5335 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5336 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5337 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5338 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5339 5340 // 1. If the Idx has been completely eliminated and this subvector's size is 5341 // a vector register or a multiple thereof, or the surrounding elements are 5342 // undef, then this is a subvector insert which naturally aligns to a vector 5343 // register. These can easily be handled using subregister manipulation. 5344 // 2. If the subvector is smaller than a vector register, then the insertion 5345 // must preserve the undisturbed elements of the register. We do this by 5346 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5347 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5348 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5349 // LMUL=1 type back into the larger vector (resolving to another subregister 5350 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5351 // to avoid allocating a large register group to hold our subvector. 5352 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5353 return Op; 5354 5355 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5356 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5357 // (in our case undisturbed). This means we can set up a subvector insertion 5358 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5359 // size of the subvector. 5360 MVT InterSubVT = VecVT; 5361 SDValue AlignedExtract = Vec; 5362 unsigned AlignedIdx = OrigIdx - RemIdx; 5363 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5364 InterSubVT = getLMUL1VT(VecVT); 5365 // Extract a subvector equal to the nearest full vector register type. This 5366 // should resolve to a EXTRACT_SUBREG instruction. 5367 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5368 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5369 } 5370 5371 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5372 // For scalable vectors this must be further multiplied by vscale. 5373 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5374 5375 SDValue Mask, VL; 5376 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5377 5378 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5379 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5380 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5381 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5382 5383 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5384 DAG.getUNDEF(InterSubVT), SubVec, 5385 DAG.getConstant(0, DL, XLenVT)); 5386 5387 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5388 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5389 5390 // If required, insert this subvector back into the correct vector register. 5391 // This should resolve to an INSERT_SUBREG instruction. 5392 if (VecVT.bitsGT(InterSubVT)) 5393 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5394 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5395 5396 // We might have bitcast from a mask type: cast back to the original type if 5397 // required. 5398 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5399 } 5400 5401 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5402 SelectionDAG &DAG) const { 5403 SDValue Vec = Op.getOperand(0); 5404 MVT SubVecVT = Op.getSimpleValueType(); 5405 MVT VecVT = Vec.getSimpleValueType(); 5406 5407 SDLoc DL(Op); 5408 MVT XLenVT = Subtarget.getXLenVT(); 5409 unsigned OrigIdx = Op.getConstantOperandVal(1); 5410 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5411 5412 // We don't have the ability to slide mask vectors down indexed by their i1 5413 // elements; the smallest we can do is i8. Often we are able to bitcast to 5414 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5415 // from a scalable one, we might not necessarily have enough scalable 5416 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5417 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5418 if (VecVT.getVectorMinNumElements() >= 8 && 5419 SubVecVT.getVectorMinNumElements() >= 8) { 5420 assert(OrigIdx % 8 == 0 && "Invalid index"); 5421 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5422 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5423 "Unexpected mask vector lowering"); 5424 OrigIdx /= 8; 5425 SubVecVT = 5426 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5427 SubVecVT.isScalableVector()); 5428 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5429 VecVT.isScalableVector()); 5430 Vec = DAG.getBitcast(VecVT, Vec); 5431 } else { 5432 // We can't slide this mask vector down, indexed by its i1 elements. 5433 // This poses a problem when we wish to extract a scalable vector which 5434 // can't be re-expressed as a larger type. Just choose the slow path and 5435 // extend to a larger type, then truncate back down. 5436 // TODO: We could probably improve this when extracting certain fixed 5437 // from fixed, where we can extract as i8 and shift the correct element 5438 // right to reach the desired subvector? 5439 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5440 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5441 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5442 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5443 Op.getOperand(1)); 5444 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5445 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5446 } 5447 } 5448 5449 // If the subvector vector is a fixed-length type, we cannot use subregister 5450 // manipulation to simplify the codegen; we don't know which register of a 5451 // LMUL group contains the specific subvector as we only know the minimum 5452 // register size. Therefore we must slide the vector group down the full 5453 // amount. 5454 if (SubVecVT.isFixedLengthVector()) { 5455 // With an index of 0 this is a cast-like subvector, which can be performed 5456 // with subregister operations. 5457 if (OrigIdx == 0) 5458 return Op; 5459 MVT ContainerVT = VecVT; 5460 if (VecVT.isFixedLengthVector()) { 5461 ContainerVT = getContainerForFixedLengthVector(VecVT); 5462 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5463 } 5464 SDValue Mask = 5465 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5466 // Set the vector length to only the number of elements we care about. This 5467 // avoids sliding down elements we're going to discard straight away. 5468 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5469 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5470 SDValue Slidedown = 5471 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5472 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5473 // Now we can use a cast-like subvector extract to get the result. 5474 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5475 DAG.getConstant(0, DL, XLenVT)); 5476 return DAG.getBitcast(Op.getValueType(), Slidedown); 5477 } 5478 5479 unsigned SubRegIdx, RemIdx; 5480 std::tie(SubRegIdx, RemIdx) = 5481 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5482 VecVT, SubVecVT, OrigIdx, TRI); 5483 5484 // If the Idx has been completely eliminated then this is a subvector extract 5485 // which naturally aligns to a vector register. These can easily be handled 5486 // using subregister manipulation. 5487 if (RemIdx == 0) 5488 return Op; 5489 5490 // Else we must shift our vector register directly to extract the subvector. 5491 // Do this using VSLIDEDOWN. 5492 5493 // If the vector type is an LMUL-group type, extract a subvector equal to the 5494 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5495 // instruction. 5496 MVT InterSubVT = VecVT; 5497 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5498 InterSubVT = getLMUL1VT(VecVT); 5499 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5500 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5501 } 5502 5503 // Slide this vector register down by the desired number of elements in order 5504 // to place the desired subvector starting at element 0. 5505 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5506 // For scalable vectors this must be further multiplied by vscale. 5507 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5508 5509 SDValue Mask, VL; 5510 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5511 SDValue Slidedown = 5512 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5513 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5514 5515 // Now the vector is in the right position, extract our final subvector. This 5516 // should resolve to a COPY. 5517 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5518 DAG.getConstant(0, DL, XLenVT)); 5519 5520 // We might have bitcast from a mask type: cast back to the original type if 5521 // required. 5522 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5523 } 5524 5525 // Lower step_vector to the vid instruction. Any non-identity step value must 5526 // be accounted for my manual expansion. 5527 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5528 SelectionDAG &DAG) const { 5529 SDLoc DL(Op); 5530 MVT VT = Op.getSimpleValueType(); 5531 MVT XLenVT = Subtarget.getXLenVT(); 5532 SDValue Mask, VL; 5533 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5534 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5535 uint64_t StepValImm = Op.getConstantOperandVal(0); 5536 if (StepValImm != 1) { 5537 if (isPowerOf2_64(StepValImm)) { 5538 SDValue StepVal = 5539 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5540 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5541 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5542 } else { 5543 SDValue StepVal = lowerScalarSplat( 5544 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5545 VL, VT, DL, DAG, Subtarget); 5546 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5547 } 5548 } 5549 return StepVec; 5550 } 5551 5552 // Implement vector_reverse using vrgather.vv with indices determined by 5553 // subtracting the id of each element from (VLMAX-1). This will convert 5554 // the indices like so: 5555 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5556 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5557 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5558 SelectionDAG &DAG) const { 5559 SDLoc DL(Op); 5560 MVT VecVT = Op.getSimpleValueType(); 5561 unsigned EltSize = VecVT.getScalarSizeInBits(); 5562 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5563 5564 unsigned MaxVLMAX = 0; 5565 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5566 if (VectorBitsMax != 0) 5567 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5568 5569 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5570 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5571 5572 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5573 // to use vrgatherei16.vv. 5574 // TODO: It's also possible to use vrgatherei16.vv for other types to 5575 // decrease register width for the index calculation. 5576 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5577 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5578 // Reverse each half, then reassemble them in reverse order. 5579 // NOTE: It's also possible that after splitting that VLMAX no longer 5580 // requires vrgatherei16.vv. 5581 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5582 SDValue Lo, Hi; 5583 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5584 EVT LoVT, HiVT; 5585 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5586 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5587 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5588 // Reassemble the low and high pieces reversed. 5589 // FIXME: This is a CONCAT_VECTORS. 5590 SDValue Res = 5591 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5592 DAG.getIntPtrConstant(0, DL)); 5593 return DAG.getNode( 5594 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5595 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5596 } 5597 5598 // Just promote the int type to i16 which will double the LMUL. 5599 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5600 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5601 } 5602 5603 MVT XLenVT = Subtarget.getXLenVT(); 5604 SDValue Mask, VL; 5605 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5606 5607 // Calculate VLMAX-1 for the desired SEW. 5608 unsigned MinElts = VecVT.getVectorMinNumElements(); 5609 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5610 DAG.getConstant(MinElts, DL, XLenVT)); 5611 SDValue VLMinus1 = 5612 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5613 5614 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5615 bool IsRV32E64 = 5616 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5617 SDValue SplatVL; 5618 if (!IsRV32E64) 5619 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5620 else 5621 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5622 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5623 5624 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5625 SDValue Indices = 5626 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5627 5628 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5629 } 5630 5631 SDValue 5632 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5633 SelectionDAG &DAG) const { 5634 SDLoc DL(Op); 5635 auto *Load = cast<LoadSDNode>(Op); 5636 5637 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5638 Load->getMemoryVT(), 5639 *Load->getMemOperand()) && 5640 "Expecting a correctly-aligned load"); 5641 5642 MVT VT = Op.getSimpleValueType(); 5643 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5644 5645 SDValue VL = 5646 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5647 5648 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5649 SDValue NewLoad = DAG.getMemIntrinsicNode( 5650 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5651 Load->getMemoryVT(), Load->getMemOperand()); 5652 5653 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5654 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5655 } 5656 5657 SDValue 5658 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5659 SelectionDAG &DAG) const { 5660 SDLoc DL(Op); 5661 auto *Store = cast<StoreSDNode>(Op); 5662 5663 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5664 Store->getMemoryVT(), 5665 *Store->getMemOperand()) && 5666 "Expecting a correctly-aligned store"); 5667 5668 SDValue StoreVal = Store->getValue(); 5669 MVT VT = StoreVal.getSimpleValueType(); 5670 5671 // If the size less than a byte, we need to pad with zeros to make a byte. 5672 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5673 VT = MVT::v8i1; 5674 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5675 DAG.getConstant(0, DL, VT), StoreVal, 5676 DAG.getIntPtrConstant(0, DL)); 5677 } 5678 5679 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5680 5681 SDValue VL = 5682 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5683 5684 SDValue NewValue = 5685 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5686 return DAG.getMemIntrinsicNode( 5687 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5688 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5689 Store->getMemoryVT(), Store->getMemOperand()); 5690 } 5691 5692 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5693 SelectionDAG &DAG) const { 5694 SDLoc DL(Op); 5695 MVT VT = Op.getSimpleValueType(); 5696 5697 const auto *MemSD = cast<MemSDNode>(Op); 5698 EVT MemVT = MemSD->getMemoryVT(); 5699 MachineMemOperand *MMO = MemSD->getMemOperand(); 5700 SDValue Chain = MemSD->getChain(); 5701 SDValue BasePtr = MemSD->getBasePtr(); 5702 5703 SDValue Mask, PassThru, VL; 5704 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5705 Mask = VPLoad->getMask(); 5706 PassThru = DAG.getUNDEF(VT); 5707 VL = VPLoad->getVectorLength(); 5708 } else { 5709 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5710 Mask = MLoad->getMask(); 5711 PassThru = MLoad->getPassThru(); 5712 } 5713 5714 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5715 5716 MVT XLenVT = Subtarget.getXLenVT(); 5717 5718 MVT ContainerVT = VT; 5719 if (VT.isFixedLengthVector()) { 5720 ContainerVT = getContainerForFixedLengthVector(VT); 5721 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5722 if (!IsUnmasked) { 5723 MVT MaskVT = 5724 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5725 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5726 } 5727 } 5728 5729 if (!VL) 5730 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5731 5732 unsigned IntID = 5733 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5734 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5735 if (IsUnmasked) 5736 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5737 else 5738 Ops.push_back(PassThru); 5739 Ops.push_back(BasePtr); 5740 if (!IsUnmasked) 5741 Ops.push_back(Mask); 5742 Ops.push_back(VL); 5743 if (!IsUnmasked) 5744 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5745 5746 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5747 5748 SDValue Result = 5749 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5750 Chain = Result.getValue(1); 5751 5752 if (VT.isFixedLengthVector()) 5753 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5754 5755 return DAG.getMergeValues({Result, Chain}, DL); 5756 } 5757 5758 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5759 SelectionDAG &DAG) const { 5760 SDLoc DL(Op); 5761 5762 const auto *MemSD = cast<MemSDNode>(Op); 5763 EVT MemVT = MemSD->getMemoryVT(); 5764 MachineMemOperand *MMO = MemSD->getMemOperand(); 5765 SDValue Chain = MemSD->getChain(); 5766 SDValue BasePtr = MemSD->getBasePtr(); 5767 SDValue Val, Mask, VL; 5768 5769 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5770 Val = VPStore->getValue(); 5771 Mask = VPStore->getMask(); 5772 VL = VPStore->getVectorLength(); 5773 } else { 5774 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5775 Val = MStore->getValue(); 5776 Mask = MStore->getMask(); 5777 } 5778 5779 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5780 5781 MVT VT = Val.getSimpleValueType(); 5782 MVT XLenVT = Subtarget.getXLenVT(); 5783 5784 MVT ContainerVT = VT; 5785 if (VT.isFixedLengthVector()) { 5786 ContainerVT = getContainerForFixedLengthVector(VT); 5787 5788 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5789 if (!IsUnmasked) { 5790 MVT MaskVT = 5791 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5792 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5793 } 5794 } 5795 5796 if (!VL) 5797 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5798 5799 unsigned IntID = 5800 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5801 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5802 Ops.push_back(Val); 5803 Ops.push_back(BasePtr); 5804 if (!IsUnmasked) 5805 Ops.push_back(Mask); 5806 Ops.push_back(VL); 5807 5808 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5809 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5810 } 5811 5812 SDValue 5813 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5814 SelectionDAG &DAG) const { 5815 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5816 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5817 5818 MVT VT = Op.getSimpleValueType(); 5819 5820 SDValue Op1 = 5821 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5822 SDValue Op2 = 5823 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5824 5825 SDLoc DL(Op); 5826 SDValue VL = 5827 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5828 5829 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5830 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5831 5832 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5833 Op.getOperand(2), Mask, VL); 5834 5835 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5836 } 5837 5838 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5839 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5840 MVT VT = Op.getSimpleValueType(); 5841 5842 if (VT.getVectorElementType() == MVT::i1) 5843 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5844 5845 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5846 } 5847 5848 SDValue 5849 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5850 SelectionDAG &DAG) const { 5851 unsigned Opc; 5852 switch (Op.getOpcode()) { 5853 default: llvm_unreachable("Unexpected opcode!"); 5854 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5855 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5856 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5857 } 5858 5859 return lowerToScalableOp(Op, DAG, Opc); 5860 } 5861 5862 // Lower vector ABS to smax(X, sub(0, X)). 5863 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5864 SDLoc DL(Op); 5865 MVT VT = Op.getSimpleValueType(); 5866 SDValue X = Op.getOperand(0); 5867 5868 assert(VT.isFixedLengthVector() && "Unexpected type"); 5869 5870 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5871 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5872 5873 SDValue Mask, VL; 5874 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5875 5876 SDValue SplatZero = DAG.getNode( 5877 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5878 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5879 SDValue NegX = 5880 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5881 SDValue Max = 5882 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5883 5884 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5885 } 5886 5887 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5888 SDValue Op, SelectionDAG &DAG) const { 5889 SDLoc DL(Op); 5890 MVT VT = Op.getSimpleValueType(); 5891 SDValue Mag = Op.getOperand(0); 5892 SDValue Sign = Op.getOperand(1); 5893 assert(Mag.getValueType() == Sign.getValueType() && 5894 "Can only handle COPYSIGN with matching types."); 5895 5896 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5897 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5898 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5899 5900 SDValue Mask, VL; 5901 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5902 5903 SDValue CopySign = 5904 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5905 5906 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5907 } 5908 5909 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5910 SDValue Op, SelectionDAG &DAG) const { 5911 MVT VT = Op.getSimpleValueType(); 5912 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5913 5914 MVT I1ContainerVT = 5915 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5916 5917 SDValue CC = 5918 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5919 SDValue Op1 = 5920 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5921 SDValue Op2 = 5922 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5923 5924 SDLoc DL(Op); 5925 SDValue Mask, VL; 5926 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5927 5928 SDValue Select = 5929 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5930 5931 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5932 } 5933 5934 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5935 unsigned NewOpc, 5936 bool HasMask) const { 5937 MVT VT = Op.getSimpleValueType(); 5938 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5939 5940 // Create list of operands by converting existing ones to scalable types. 5941 SmallVector<SDValue, 6> Ops; 5942 for (const SDValue &V : Op->op_values()) { 5943 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5944 5945 // Pass through non-vector operands. 5946 if (!V.getValueType().isVector()) { 5947 Ops.push_back(V); 5948 continue; 5949 } 5950 5951 // "cast" fixed length vector to a scalable vector. 5952 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5953 "Only fixed length vectors are supported!"); 5954 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5955 } 5956 5957 SDLoc DL(Op); 5958 SDValue Mask, VL; 5959 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5960 if (HasMask) 5961 Ops.push_back(Mask); 5962 Ops.push_back(VL); 5963 5964 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5965 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5966 } 5967 5968 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5969 // * Operands of each node are assumed to be in the same order. 5970 // * The EVL operand is promoted from i32 to i64 on RV64. 5971 // * Fixed-length vectors are converted to their scalable-vector container 5972 // types. 5973 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5974 unsigned RISCVISDOpc) const { 5975 SDLoc DL(Op); 5976 MVT VT = Op.getSimpleValueType(); 5977 SmallVector<SDValue, 4> Ops; 5978 5979 for (const auto &OpIdx : enumerate(Op->ops())) { 5980 SDValue V = OpIdx.value(); 5981 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5982 // Pass through operands which aren't fixed-length vectors. 5983 if (!V.getValueType().isFixedLengthVector()) { 5984 Ops.push_back(V); 5985 continue; 5986 } 5987 // "cast" fixed length vector to a scalable vector. 5988 MVT OpVT = V.getSimpleValueType(); 5989 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5990 assert(useRVVForFixedLengthVectorVT(OpVT) && 5991 "Only fixed length vectors are supported!"); 5992 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5993 } 5994 5995 if (!VT.isFixedLengthVector()) 5996 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5997 5998 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5999 6000 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6001 6002 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6003 } 6004 6005 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6006 unsigned MaskOpc, 6007 unsigned VecOpc) const { 6008 MVT VT = Op.getSimpleValueType(); 6009 if (VT.getVectorElementType() != MVT::i1) 6010 return lowerVPOp(Op, DAG, VecOpc); 6011 6012 // It is safe to drop mask parameter as masked-off elements are undef. 6013 SDValue Op1 = Op->getOperand(0); 6014 SDValue Op2 = Op->getOperand(1); 6015 SDValue VL = Op->getOperand(3); 6016 6017 MVT ContainerVT = VT; 6018 const bool IsFixed = VT.isFixedLengthVector(); 6019 if (IsFixed) { 6020 ContainerVT = getContainerForFixedLengthVector(VT); 6021 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6022 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6023 } 6024 6025 SDLoc DL(Op); 6026 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6027 if (!IsFixed) 6028 return Val; 6029 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6030 } 6031 6032 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6033 // matched to a RVV indexed load. The RVV indexed load instructions only 6034 // support the "unsigned unscaled" addressing mode; indices are implicitly 6035 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6036 // signed or scaled indexing is extended to the XLEN value type and scaled 6037 // accordingly. 6038 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6039 SelectionDAG &DAG) const { 6040 SDLoc DL(Op); 6041 MVT VT = Op.getSimpleValueType(); 6042 6043 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6044 EVT MemVT = MemSD->getMemoryVT(); 6045 MachineMemOperand *MMO = MemSD->getMemOperand(); 6046 SDValue Chain = MemSD->getChain(); 6047 SDValue BasePtr = MemSD->getBasePtr(); 6048 6049 ISD::LoadExtType LoadExtType; 6050 SDValue Index, Mask, PassThru, VL; 6051 6052 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6053 Index = VPGN->getIndex(); 6054 Mask = VPGN->getMask(); 6055 PassThru = DAG.getUNDEF(VT); 6056 VL = VPGN->getVectorLength(); 6057 // VP doesn't support extending loads. 6058 LoadExtType = ISD::NON_EXTLOAD; 6059 } else { 6060 // Else it must be a MGATHER. 6061 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6062 Index = MGN->getIndex(); 6063 Mask = MGN->getMask(); 6064 PassThru = MGN->getPassThru(); 6065 LoadExtType = MGN->getExtensionType(); 6066 } 6067 6068 MVT IndexVT = Index.getSimpleValueType(); 6069 MVT XLenVT = Subtarget.getXLenVT(); 6070 6071 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6072 "Unexpected VTs!"); 6073 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6074 // Targets have to explicitly opt-in for extending vector loads. 6075 assert(LoadExtType == ISD::NON_EXTLOAD && 6076 "Unexpected extending MGATHER/VP_GATHER"); 6077 (void)LoadExtType; 6078 6079 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6080 // the selection of the masked intrinsics doesn't do this for us. 6081 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6082 6083 MVT ContainerVT = VT; 6084 if (VT.isFixedLengthVector()) { 6085 // We need to use the larger of the result and index type to determine the 6086 // scalable type to use so we don't increase LMUL for any operand/result. 6087 if (VT.bitsGE(IndexVT)) { 6088 ContainerVT = getContainerForFixedLengthVector(VT); 6089 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6090 ContainerVT.getVectorElementCount()); 6091 } else { 6092 IndexVT = getContainerForFixedLengthVector(IndexVT); 6093 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6094 IndexVT.getVectorElementCount()); 6095 } 6096 6097 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6098 6099 if (!IsUnmasked) { 6100 MVT MaskVT = 6101 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6102 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6103 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6104 } 6105 } 6106 6107 if (!VL) 6108 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6109 6110 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6111 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6112 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6113 VL); 6114 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6115 TrueMask, VL); 6116 } 6117 6118 unsigned IntID = 6119 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6120 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6121 if (IsUnmasked) 6122 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6123 else 6124 Ops.push_back(PassThru); 6125 Ops.push_back(BasePtr); 6126 Ops.push_back(Index); 6127 if (!IsUnmasked) 6128 Ops.push_back(Mask); 6129 Ops.push_back(VL); 6130 if (!IsUnmasked) 6131 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6132 6133 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6134 SDValue Result = 6135 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6136 Chain = Result.getValue(1); 6137 6138 if (VT.isFixedLengthVector()) 6139 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6140 6141 return DAG.getMergeValues({Result, Chain}, DL); 6142 } 6143 6144 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6145 // matched to a RVV indexed store. The RVV indexed store instructions only 6146 // support the "unsigned unscaled" addressing mode; indices are implicitly 6147 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6148 // signed or scaled indexing is extended to the XLEN value type and scaled 6149 // accordingly. 6150 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6151 SelectionDAG &DAG) const { 6152 SDLoc DL(Op); 6153 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6154 EVT MemVT = MemSD->getMemoryVT(); 6155 MachineMemOperand *MMO = MemSD->getMemOperand(); 6156 SDValue Chain = MemSD->getChain(); 6157 SDValue BasePtr = MemSD->getBasePtr(); 6158 6159 bool IsTruncatingStore = false; 6160 SDValue Index, Mask, Val, VL; 6161 6162 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6163 Index = VPSN->getIndex(); 6164 Mask = VPSN->getMask(); 6165 Val = VPSN->getValue(); 6166 VL = VPSN->getVectorLength(); 6167 // VP doesn't support truncating stores. 6168 IsTruncatingStore = false; 6169 } else { 6170 // Else it must be a MSCATTER. 6171 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6172 Index = MSN->getIndex(); 6173 Mask = MSN->getMask(); 6174 Val = MSN->getValue(); 6175 IsTruncatingStore = MSN->isTruncatingStore(); 6176 } 6177 6178 MVT VT = Val.getSimpleValueType(); 6179 MVT IndexVT = Index.getSimpleValueType(); 6180 MVT XLenVT = Subtarget.getXLenVT(); 6181 6182 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6183 "Unexpected VTs!"); 6184 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6185 // Targets have to explicitly opt-in for extending vector loads and 6186 // truncating vector stores. 6187 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6188 (void)IsTruncatingStore; 6189 6190 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6191 // the selection of the masked intrinsics doesn't do this for us. 6192 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6193 6194 MVT ContainerVT = VT; 6195 if (VT.isFixedLengthVector()) { 6196 // We need to use the larger of the value and index type to determine the 6197 // scalable type to use so we don't increase LMUL for any operand/result. 6198 if (VT.bitsGE(IndexVT)) { 6199 ContainerVT = getContainerForFixedLengthVector(VT); 6200 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6201 ContainerVT.getVectorElementCount()); 6202 } else { 6203 IndexVT = getContainerForFixedLengthVector(IndexVT); 6204 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6205 IndexVT.getVectorElementCount()); 6206 } 6207 6208 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6209 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6210 6211 if (!IsUnmasked) { 6212 MVT MaskVT = 6213 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6214 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6215 } 6216 } 6217 6218 if (!VL) 6219 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6220 6221 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6222 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6223 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6224 VL); 6225 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6226 TrueMask, VL); 6227 } 6228 6229 unsigned IntID = 6230 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6231 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6232 Ops.push_back(Val); 6233 Ops.push_back(BasePtr); 6234 Ops.push_back(Index); 6235 if (!IsUnmasked) 6236 Ops.push_back(Mask); 6237 Ops.push_back(VL); 6238 6239 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6240 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6241 } 6242 6243 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6244 SelectionDAG &DAG) const { 6245 const MVT XLenVT = Subtarget.getXLenVT(); 6246 SDLoc DL(Op); 6247 SDValue Chain = Op->getOperand(0); 6248 SDValue SysRegNo = DAG.getTargetConstant( 6249 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6250 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6251 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6252 6253 // Encoding used for rounding mode in RISCV differs from that used in 6254 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6255 // table, which consists of a sequence of 4-bit fields, each representing 6256 // corresponding FLT_ROUNDS mode. 6257 static const int Table = 6258 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6259 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6260 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6261 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6262 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6263 6264 SDValue Shift = 6265 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6266 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6267 DAG.getConstant(Table, DL, XLenVT), Shift); 6268 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6269 DAG.getConstant(7, DL, XLenVT)); 6270 6271 return DAG.getMergeValues({Masked, Chain}, DL); 6272 } 6273 6274 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6275 SelectionDAG &DAG) const { 6276 const MVT XLenVT = Subtarget.getXLenVT(); 6277 SDLoc DL(Op); 6278 SDValue Chain = Op->getOperand(0); 6279 SDValue RMValue = Op->getOperand(1); 6280 SDValue SysRegNo = DAG.getTargetConstant( 6281 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6282 6283 // Encoding used for rounding mode in RISCV differs from that used in 6284 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6285 // a table, which consists of a sequence of 4-bit fields, each representing 6286 // corresponding RISCV mode. 6287 static const unsigned Table = 6288 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6289 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6290 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6291 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6292 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6293 6294 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6295 DAG.getConstant(2, DL, XLenVT)); 6296 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6297 DAG.getConstant(Table, DL, XLenVT), Shift); 6298 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6299 DAG.getConstant(0x7, DL, XLenVT)); 6300 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6301 RMValue); 6302 } 6303 6304 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6305 switch (IntNo) { 6306 default: 6307 llvm_unreachable("Unexpected Intrinsic"); 6308 case Intrinsic::riscv_grev: 6309 return RISCVISD::GREVW; 6310 case Intrinsic::riscv_gorc: 6311 return RISCVISD::GORCW; 6312 case Intrinsic::riscv_bcompress: 6313 return RISCVISD::BCOMPRESSW; 6314 case Intrinsic::riscv_bdecompress: 6315 return RISCVISD::BDECOMPRESSW; 6316 case Intrinsic::riscv_bfp: 6317 return RISCVISD::BFPW; 6318 case Intrinsic::riscv_fsl: 6319 return RISCVISD::FSLW; 6320 case Intrinsic::riscv_fsr: 6321 return RISCVISD::FSRW; 6322 } 6323 } 6324 6325 // Converts the given intrinsic to a i64 operation with any extension. 6326 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6327 unsigned IntNo) { 6328 SDLoc DL(N); 6329 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6330 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6331 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6332 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6333 // ReplaceNodeResults requires we maintain the same type for the return value. 6334 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6335 } 6336 6337 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6338 // form of the given Opcode. 6339 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6340 switch (Opcode) { 6341 default: 6342 llvm_unreachable("Unexpected opcode"); 6343 case ISD::SHL: 6344 return RISCVISD::SLLW; 6345 case ISD::SRA: 6346 return RISCVISD::SRAW; 6347 case ISD::SRL: 6348 return RISCVISD::SRLW; 6349 case ISD::SDIV: 6350 return RISCVISD::DIVW; 6351 case ISD::UDIV: 6352 return RISCVISD::DIVUW; 6353 case ISD::UREM: 6354 return RISCVISD::REMUW; 6355 case ISD::ROTL: 6356 return RISCVISD::ROLW; 6357 case ISD::ROTR: 6358 return RISCVISD::RORW; 6359 case RISCVISD::GREV: 6360 return RISCVISD::GREVW; 6361 case RISCVISD::GORC: 6362 return RISCVISD::GORCW; 6363 } 6364 } 6365 6366 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6367 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6368 // otherwise be promoted to i64, making it difficult to select the 6369 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6370 // type i8/i16/i32 is lost. 6371 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6372 unsigned ExtOpc = ISD::ANY_EXTEND) { 6373 SDLoc DL(N); 6374 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6375 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6376 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6377 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6378 // ReplaceNodeResults requires we maintain the same type for the return value. 6379 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6380 } 6381 6382 // Converts the given 32-bit operation to a i64 operation with signed extension 6383 // semantic to reduce the signed extension instructions. 6384 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6385 SDLoc DL(N); 6386 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6387 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6388 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6389 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6390 DAG.getValueType(MVT::i32)); 6391 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6392 } 6393 6394 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6395 SmallVectorImpl<SDValue> &Results, 6396 SelectionDAG &DAG) const { 6397 SDLoc DL(N); 6398 switch (N->getOpcode()) { 6399 default: 6400 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6401 case ISD::STRICT_FP_TO_SINT: 6402 case ISD::STRICT_FP_TO_UINT: 6403 case ISD::FP_TO_SINT: 6404 case ISD::FP_TO_UINT: { 6405 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6406 "Unexpected custom legalisation"); 6407 bool IsStrict = N->isStrictFPOpcode(); 6408 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6409 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6410 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6411 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6412 TargetLowering::TypeSoftenFloat) { 6413 if (!isTypeLegal(Op0.getValueType())) 6414 return; 6415 if (IsStrict) { 6416 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6417 : RISCVISD::STRICT_FCVT_WU_RV64; 6418 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6419 SDValue Res = DAG.getNode( 6420 Opc, DL, VTs, N->getOperand(0), Op0, 6421 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6422 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6423 Results.push_back(Res.getValue(1)); 6424 return; 6425 } 6426 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6427 SDValue Res = 6428 DAG.getNode(Opc, DL, MVT::i64, Op0, 6429 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6430 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6431 return; 6432 } 6433 // If the FP type needs to be softened, emit a library call using the 'si' 6434 // version. If we left it to default legalization we'd end up with 'di'. If 6435 // the FP type doesn't need to be softened just let generic type 6436 // legalization promote the result type. 6437 RTLIB::Libcall LC; 6438 if (IsSigned) 6439 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6440 else 6441 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6442 MakeLibCallOptions CallOptions; 6443 EVT OpVT = Op0.getValueType(); 6444 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6445 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6446 SDValue Result; 6447 std::tie(Result, Chain) = 6448 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6449 Results.push_back(Result); 6450 if (IsStrict) 6451 Results.push_back(Chain); 6452 break; 6453 } 6454 case ISD::READCYCLECOUNTER: { 6455 assert(!Subtarget.is64Bit() && 6456 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6457 6458 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6459 SDValue RCW = 6460 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6461 6462 Results.push_back( 6463 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6464 Results.push_back(RCW.getValue(2)); 6465 break; 6466 } 6467 case ISD::MUL: { 6468 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6469 unsigned XLen = Subtarget.getXLen(); 6470 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6471 if (Size > XLen) { 6472 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6473 SDValue LHS = N->getOperand(0); 6474 SDValue RHS = N->getOperand(1); 6475 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6476 6477 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6478 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6479 // We need exactly one side to be unsigned. 6480 if (LHSIsU == RHSIsU) 6481 return; 6482 6483 auto MakeMULPair = [&](SDValue S, SDValue U) { 6484 MVT XLenVT = Subtarget.getXLenVT(); 6485 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6486 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6487 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6488 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6489 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6490 }; 6491 6492 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6493 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6494 6495 // The other operand should be signed, but still prefer MULH when 6496 // possible. 6497 if (RHSIsU && LHSIsS && !RHSIsS) 6498 Results.push_back(MakeMULPair(LHS, RHS)); 6499 else if (LHSIsU && RHSIsS && !LHSIsS) 6500 Results.push_back(MakeMULPair(RHS, LHS)); 6501 6502 return; 6503 } 6504 LLVM_FALLTHROUGH; 6505 } 6506 case ISD::ADD: 6507 case ISD::SUB: 6508 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6509 "Unexpected custom legalisation"); 6510 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6511 break; 6512 case ISD::SHL: 6513 case ISD::SRA: 6514 case ISD::SRL: 6515 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6516 "Unexpected custom legalisation"); 6517 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6518 Results.push_back(customLegalizeToWOp(N, DAG)); 6519 break; 6520 } 6521 6522 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6523 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6524 // shift amount. 6525 if (N->getOpcode() == ISD::SHL) { 6526 SDLoc DL(N); 6527 SDValue NewOp0 = 6528 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6529 SDValue NewOp1 = 6530 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6531 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6532 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6533 DAG.getValueType(MVT::i32)); 6534 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6535 } 6536 6537 break; 6538 case ISD::ROTL: 6539 case ISD::ROTR: 6540 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6541 "Unexpected custom legalisation"); 6542 Results.push_back(customLegalizeToWOp(N, DAG)); 6543 break; 6544 case ISD::CTTZ: 6545 case ISD::CTTZ_ZERO_UNDEF: 6546 case ISD::CTLZ: 6547 case ISD::CTLZ_ZERO_UNDEF: { 6548 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6549 "Unexpected custom legalisation"); 6550 6551 SDValue NewOp0 = 6552 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6553 bool IsCTZ = 6554 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6555 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6556 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6557 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6558 return; 6559 } 6560 case ISD::SDIV: 6561 case ISD::UDIV: 6562 case ISD::UREM: { 6563 MVT VT = N->getSimpleValueType(0); 6564 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6565 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6566 "Unexpected custom legalisation"); 6567 // Don't promote division/remainder by constant since we should expand those 6568 // to multiply by magic constant. 6569 // FIXME: What if the expansion is disabled for minsize. 6570 if (N->getOperand(1).getOpcode() == ISD::Constant) 6571 return; 6572 6573 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6574 // the upper 32 bits. For other types we need to sign or zero extend 6575 // based on the opcode. 6576 unsigned ExtOpc = ISD::ANY_EXTEND; 6577 if (VT != MVT::i32) 6578 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6579 : ISD::ZERO_EXTEND; 6580 6581 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6582 break; 6583 } 6584 case ISD::UADDO: 6585 case ISD::USUBO: { 6586 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6587 "Unexpected custom legalisation"); 6588 bool IsAdd = N->getOpcode() == ISD::UADDO; 6589 // Create an ADDW or SUBW. 6590 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6591 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6592 SDValue Res = 6593 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6594 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6595 DAG.getValueType(MVT::i32)); 6596 6597 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6598 // Since the inputs are sign extended from i32, this is equivalent to 6599 // comparing the lower 32 bits. 6600 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6601 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6602 IsAdd ? ISD::SETULT : ISD::SETUGT); 6603 6604 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6605 Results.push_back(Overflow); 6606 return; 6607 } 6608 case ISD::UADDSAT: 6609 case ISD::USUBSAT: { 6610 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6611 "Unexpected custom legalisation"); 6612 if (Subtarget.hasStdExtZbb()) { 6613 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6614 // sign extend allows overflow of the lower 32 bits to be detected on 6615 // the promoted size. 6616 SDValue LHS = 6617 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6618 SDValue RHS = 6619 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6620 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6621 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6622 return; 6623 } 6624 6625 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6626 // promotion for UADDO/USUBO. 6627 Results.push_back(expandAddSubSat(N, DAG)); 6628 return; 6629 } 6630 case ISD::ABS: { 6631 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6632 "Unexpected custom legalisation"); 6633 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6634 6635 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6636 6637 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6638 6639 // Freeze the source so we can increase it's use count. 6640 Src = DAG.getFreeze(Src); 6641 6642 // Copy sign bit to all bits using the sraiw pattern. 6643 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6644 DAG.getValueType(MVT::i32)); 6645 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6646 DAG.getConstant(31, DL, MVT::i64)); 6647 6648 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6649 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6650 6651 // NOTE: The result is only required to be anyextended, but sext is 6652 // consistent with type legalization of sub. 6653 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6654 DAG.getValueType(MVT::i32)); 6655 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6656 return; 6657 } 6658 case ISD::BITCAST: { 6659 EVT VT = N->getValueType(0); 6660 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6661 SDValue Op0 = N->getOperand(0); 6662 EVT Op0VT = Op0.getValueType(); 6663 MVT XLenVT = Subtarget.getXLenVT(); 6664 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6665 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6666 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6667 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6668 Subtarget.hasStdExtF()) { 6669 SDValue FPConv = 6670 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6671 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6672 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6673 isTypeLegal(Op0VT)) { 6674 // Custom-legalize bitcasts from fixed-length vector types to illegal 6675 // scalar types in order to improve codegen. Bitcast the vector to a 6676 // one-element vector type whose element type is the same as the result 6677 // type, and extract the first element. 6678 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6679 if (isTypeLegal(BVT)) { 6680 SDValue BVec = DAG.getBitcast(BVT, Op0); 6681 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6682 DAG.getConstant(0, DL, XLenVT))); 6683 } 6684 } 6685 break; 6686 } 6687 case RISCVISD::GREV: 6688 case RISCVISD::GORC: { 6689 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6690 "Unexpected custom legalisation"); 6691 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6692 // This is similar to customLegalizeToWOp, except that we pass the second 6693 // operand (a TargetConstant) straight through: it is already of type 6694 // XLenVT. 6695 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6696 SDValue NewOp0 = 6697 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6698 SDValue NewOp1 = 6699 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6700 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6701 // ReplaceNodeResults requires we maintain the same type for the return 6702 // value. 6703 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6704 break; 6705 } 6706 case RISCVISD::SHFL: { 6707 // There is no SHFLIW instruction, but we can just promote the operation. 6708 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6709 "Unexpected custom legalisation"); 6710 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6711 SDValue NewOp0 = 6712 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6713 SDValue NewOp1 = 6714 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6715 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6716 // ReplaceNodeResults requires we maintain the same type for the return 6717 // value. 6718 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6719 break; 6720 } 6721 case ISD::BSWAP: 6722 case ISD::BITREVERSE: { 6723 MVT VT = N->getSimpleValueType(0); 6724 MVT XLenVT = Subtarget.getXLenVT(); 6725 assert((VT == MVT::i8 || VT == MVT::i16 || 6726 (VT == MVT::i32 && Subtarget.is64Bit())) && 6727 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6728 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6729 unsigned Imm = VT.getSizeInBits() - 1; 6730 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6731 if (N->getOpcode() == ISD::BSWAP) 6732 Imm &= ~0x7U; 6733 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6734 SDValue GREVI = 6735 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6736 // ReplaceNodeResults requires we maintain the same type for the return 6737 // value. 6738 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6739 break; 6740 } 6741 case ISD::FSHL: 6742 case ISD::FSHR: { 6743 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6744 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6745 SDValue NewOp0 = 6746 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6747 SDValue NewOp1 = 6748 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6749 SDValue NewShAmt = 6750 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6751 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6752 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6753 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6754 DAG.getConstant(0x1f, DL, MVT::i64)); 6755 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6756 // instruction use different orders. fshl will return its first operand for 6757 // shift of zero, fshr will return its second operand. fsl and fsr both 6758 // return rs1 so the ISD nodes need to have different operand orders. 6759 // Shift amount is in rs2. 6760 unsigned Opc = RISCVISD::FSLW; 6761 if (N->getOpcode() == ISD::FSHR) { 6762 std::swap(NewOp0, NewOp1); 6763 Opc = RISCVISD::FSRW; 6764 } 6765 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6766 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6767 break; 6768 } 6769 case ISD::EXTRACT_VECTOR_ELT: { 6770 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6771 // type is illegal (currently only vXi64 RV32). 6772 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6773 // transferred to the destination register. We issue two of these from the 6774 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6775 // first element. 6776 SDValue Vec = N->getOperand(0); 6777 SDValue Idx = N->getOperand(1); 6778 6779 // The vector type hasn't been legalized yet so we can't issue target 6780 // specific nodes if it needs legalization. 6781 // FIXME: We would manually legalize if it's important. 6782 if (!isTypeLegal(Vec.getValueType())) 6783 return; 6784 6785 MVT VecVT = Vec.getSimpleValueType(); 6786 6787 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6788 VecVT.getVectorElementType() == MVT::i64 && 6789 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6790 6791 // If this is a fixed vector, we need to convert it to a scalable vector. 6792 MVT ContainerVT = VecVT; 6793 if (VecVT.isFixedLengthVector()) { 6794 ContainerVT = getContainerForFixedLengthVector(VecVT); 6795 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6796 } 6797 6798 MVT XLenVT = Subtarget.getXLenVT(); 6799 6800 // Use a VL of 1 to avoid processing more elements than we need. 6801 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6802 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6803 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6804 6805 // Unless the index is known to be 0, we must slide the vector down to get 6806 // the desired element into index 0. 6807 if (!isNullConstant(Idx)) { 6808 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6809 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6810 } 6811 6812 // Extract the lower XLEN bits of the correct vector element. 6813 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6814 6815 // To extract the upper XLEN bits of the vector element, shift the first 6816 // element right by 32 bits and re-extract the lower XLEN bits. 6817 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6818 DAG.getUNDEF(ContainerVT), 6819 DAG.getConstant(32, DL, XLenVT), VL); 6820 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6821 ThirtyTwoV, Mask, VL); 6822 6823 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6824 6825 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6826 break; 6827 } 6828 case ISD::INTRINSIC_WO_CHAIN: { 6829 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6830 switch (IntNo) { 6831 default: 6832 llvm_unreachable( 6833 "Don't know how to custom type legalize this intrinsic!"); 6834 case Intrinsic::riscv_grev: 6835 case Intrinsic::riscv_gorc: 6836 case Intrinsic::riscv_bcompress: 6837 case Intrinsic::riscv_bdecompress: 6838 case Intrinsic::riscv_bfp: { 6839 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6840 "Unexpected custom legalisation"); 6841 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6842 break; 6843 } 6844 case Intrinsic::riscv_fsl: 6845 case Intrinsic::riscv_fsr: { 6846 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6847 "Unexpected custom legalisation"); 6848 SDValue NewOp1 = 6849 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6850 SDValue NewOp2 = 6851 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6852 SDValue NewOp3 = 6853 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6854 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6855 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6856 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6857 break; 6858 } 6859 case Intrinsic::riscv_orc_b: { 6860 // Lower to the GORCI encoding for orc.b with the operand extended. 6861 SDValue NewOp = 6862 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6863 // If Zbp is enabled, use GORCIW which will sign extend the result. 6864 unsigned Opc = 6865 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6866 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6867 DAG.getConstant(7, DL, MVT::i64)); 6868 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6869 return; 6870 } 6871 case Intrinsic::riscv_shfl: 6872 case Intrinsic::riscv_unshfl: { 6873 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6874 "Unexpected custom legalisation"); 6875 SDValue NewOp1 = 6876 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6877 SDValue NewOp2 = 6878 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6879 unsigned Opc = 6880 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6881 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6882 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6883 // will be shuffled the same way as the lower 32 bit half, but the two 6884 // halves won't cross. 6885 if (isa<ConstantSDNode>(NewOp2)) { 6886 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6887 DAG.getConstant(0xf, DL, MVT::i64)); 6888 Opc = 6889 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6890 } 6891 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6892 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6893 break; 6894 } 6895 case Intrinsic::riscv_vmv_x_s: { 6896 EVT VT = N->getValueType(0); 6897 MVT XLenVT = Subtarget.getXLenVT(); 6898 if (VT.bitsLT(XLenVT)) { 6899 // Simple case just extract using vmv.x.s and truncate. 6900 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6901 Subtarget.getXLenVT(), N->getOperand(1)); 6902 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6903 return; 6904 } 6905 6906 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6907 "Unexpected custom legalization"); 6908 6909 // We need to do the move in two steps. 6910 SDValue Vec = N->getOperand(1); 6911 MVT VecVT = Vec.getSimpleValueType(); 6912 6913 // First extract the lower XLEN bits of the element. 6914 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6915 6916 // To extract the upper XLEN bits of the vector element, shift the first 6917 // element right by 32 bits and re-extract the lower XLEN bits. 6918 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6919 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6920 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6921 SDValue ThirtyTwoV = 6922 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 6923 DAG.getConstant(32, DL, XLenVT), VL); 6924 SDValue LShr32 = 6925 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6926 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6927 6928 Results.push_back( 6929 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6930 break; 6931 } 6932 } 6933 break; 6934 } 6935 case ISD::VECREDUCE_ADD: 6936 case ISD::VECREDUCE_AND: 6937 case ISD::VECREDUCE_OR: 6938 case ISD::VECREDUCE_XOR: 6939 case ISD::VECREDUCE_SMAX: 6940 case ISD::VECREDUCE_UMAX: 6941 case ISD::VECREDUCE_SMIN: 6942 case ISD::VECREDUCE_UMIN: 6943 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6944 Results.push_back(V); 6945 break; 6946 case ISD::VP_REDUCE_ADD: 6947 case ISD::VP_REDUCE_AND: 6948 case ISD::VP_REDUCE_OR: 6949 case ISD::VP_REDUCE_XOR: 6950 case ISD::VP_REDUCE_SMAX: 6951 case ISD::VP_REDUCE_UMAX: 6952 case ISD::VP_REDUCE_SMIN: 6953 case ISD::VP_REDUCE_UMIN: 6954 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6955 Results.push_back(V); 6956 break; 6957 case ISD::FLT_ROUNDS_: { 6958 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6959 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6960 Results.push_back(Res.getValue(0)); 6961 Results.push_back(Res.getValue(1)); 6962 break; 6963 } 6964 } 6965 } 6966 6967 // A structure to hold one of the bit-manipulation patterns below. Together, a 6968 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6969 // (or (and (shl x, 1), 0xAAAAAAAA), 6970 // (and (srl x, 1), 0x55555555)) 6971 struct RISCVBitmanipPat { 6972 SDValue Op; 6973 unsigned ShAmt; 6974 bool IsSHL; 6975 6976 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6977 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6978 } 6979 }; 6980 6981 // Matches patterns of the form 6982 // (and (shl x, C2), (C1 << C2)) 6983 // (and (srl x, C2), C1) 6984 // (shl (and x, C1), C2) 6985 // (srl (and x, (C1 << C2)), C2) 6986 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6987 // The expected masks for each shift amount are specified in BitmanipMasks where 6988 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6989 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6990 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6991 // XLen is 64. 6992 static Optional<RISCVBitmanipPat> 6993 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6994 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6995 "Unexpected number of masks"); 6996 Optional<uint64_t> Mask; 6997 // Optionally consume a mask around the shift operation. 6998 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6999 Mask = Op.getConstantOperandVal(1); 7000 Op = Op.getOperand(0); 7001 } 7002 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7003 return None; 7004 bool IsSHL = Op.getOpcode() == ISD::SHL; 7005 7006 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7007 return None; 7008 uint64_t ShAmt = Op.getConstantOperandVal(1); 7009 7010 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7011 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7012 return None; 7013 // If we don't have enough masks for 64 bit, then we must be trying to 7014 // match SHFL so we're only allowed to shift 1/4 of the width. 7015 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7016 return None; 7017 7018 SDValue Src = Op.getOperand(0); 7019 7020 // The expected mask is shifted left when the AND is found around SHL 7021 // patterns. 7022 // ((x >> 1) & 0x55555555) 7023 // ((x << 1) & 0xAAAAAAAA) 7024 bool SHLExpMask = IsSHL; 7025 7026 if (!Mask) { 7027 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7028 // the mask is all ones: consume that now. 7029 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7030 Mask = Src.getConstantOperandVal(1); 7031 Src = Src.getOperand(0); 7032 // The expected mask is now in fact shifted left for SRL, so reverse the 7033 // decision. 7034 // ((x & 0xAAAAAAAA) >> 1) 7035 // ((x & 0x55555555) << 1) 7036 SHLExpMask = !SHLExpMask; 7037 } else { 7038 // Use a default shifted mask of all-ones if there's no AND, truncated 7039 // down to the expected width. This simplifies the logic later on. 7040 Mask = maskTrailingOnes<uint64_t>(Width); 7041 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7042 } 7043 } 7044 7045 unsigned MaskIdx = Log2_32(ShAmt); 7046 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7047 7048 if (SHLExpMask) 7049 ExpMask <<= ShAmt; 7050 7051 if (Mask != ExpMask) 7052 return None; 7053 7054 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7055 } 7056 7057 // Matches any of the following bit-manipulation patterns: 7058 // (and (shl x, 1), (0x55555555 << 1)) 7059 // (and (srl x, 1), 0x55555555) 7060 // (shl (and x, 0x55555555), 1) 7061 // (srl (and x, (0x55555555 << 1)), 1) 7062 // where the shift amount and mask may vary thus: 7063 // [1] = 0x55555555 / 0xAAAAAAAA 7064 // [2] = 0x33333333 / 0xCCCCCCCC 7065 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7066 // [8] = 0x00FF00FF / 0xFF00FF00 7067 // [16] = 0x0000FFFF / 0xFFFFFFFF 7068 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7069 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7070 // These are the unshifted masks which we use to match bit-manipulation 7071 // patterns. They may be shifted left in certain circumstances. 7072 static const uint64_t BitmanipMasks[] = { 7073 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7074 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7075 7076 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7077 } 7078 7079 // Match the following pattern as a GREVI(W) operation 7080 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7081 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7082 const RISCVSubtarget &Subtarget) { 7083 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7084 EVT VT = Op.getValueType(); 7085 7086 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7087 auto LHS = matchGREVIPat(Op.getOperand(0)); 7088 auto RHS = matchGREVIPat(Op.getOperand(1)); 7089 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7090 SDLoc DL(Op); 7091 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7092 DAG.getConstant(LHS->ShAmt, DL, VT)); 7093 } 7094 } 7095 return SDValue(); 7096 } 7097 7098 // Matches any the following pattern as a GORCI(W) operation 7099 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7100 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7101 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7102 // Note that with the variant of 3., 7103 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7104 // the inner pattern will first be matched as GREVI and then the outer 7105 // pattern will be matched to GORC via the first rule above. 7106 // 4. (or (rotl/rotr x, bitwidth/2), x) 7107 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7108 const RISCVSubtarget &Subtarget) { 7109 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7110 EVT VT = Op.getValueType(); 7111 7112 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7113 SDLoc DL(Op); 7114 SDValue Op0 = Op.getOperand(0); 7115 SDValue Op1 = Op.getOperand(1); 7116 7117 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7118 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7119 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7120 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7121 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7122 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7123 if ((Reverse.getOpcode() == ISD::ROTL || 7124 Reverse.getOpcode() == ISD::ROTR) && 7125 Reverse.getOperand(0) == X && 7126 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7127 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7128 if (RotAmt == (VT.getSizeInBits() / 2)) 7129 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7130 DAG.getConstant(RotAmt, DL, VT)); 7131 } 7132 return SDValue(); 7133 }; 7134 7135 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7136 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7137 return V; 7138 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7139 return V; 7140 7141 // OR is commutable so canonicalize its OR operand to the left 7142 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7143 std::swap(Op0, Op1); 7144 if (Op0.getOpcode() != ISD::OR) 7145 return SDValue(); 7146 SDValue OrOp0 = Op0.getOperand(0); 7147 SDValue OrOp1 = Op0.getOperand(1); 7148 auto LHS = matchGREVIPat(OrOp0); 7149 // OR is commutable so swap the operands and try again: x might have been 7150 // on the left 7151 if (!LHS) { 7152 std::swap(OrOp0, OrOp1); 7153 LHS = matchGREVIPat(OrOp0); 7154 } 7155 auto RHS = matchGREVIPat(Op1); 7156 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7157 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7158 DAG.getConstant(LHS->ShAmt, DL, VT)); 7159 } 7160 } 7161 return SDValue(); 7162 } 7163 7164 // Matches any of the following bit-manipulation patterns: 7165 // (and (shl x, 1), (0x22222222 << 1)) 7166 // (and (srl x, 1), 0x22222222) 7167 // (shl (and x, 0x22222222), 1) 7168 // (srl (and x, (0x22222222 << 1)), 1) 7169 // where the shift amount and mask may vary thus: 7170 // [1] = 0x22222222 / 0x44444444 7171 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7172 // [4] = 0x00F000F0 / 0x0F000F00 7173 // [8] = 0x0000FF00 / 0x00FF0000 7174 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7175 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7176 // These are the unshifted masks which we use to match bit-manipulation 7177 // patterns. They may be shifted left in certain circumstances. 7178 static const uint64_t BitmanipMasks[] = { 7179 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7180 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7181 7182 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7183 } 7184 7185 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7186 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7187 const RISCVSubtarget &Subtarget) { 7188 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7189 EVT VT = Op.getValueType(); 7190 7191 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7192 return SDValue(); 7193 7194 SDValue Op0 = Op.getOperand(0); 7195 SDValue Op1 = Op.getOperand(1); 7196 7197 // Or is commutable so canonicalize the second OR to the LHS. 7198 if (Op0.getOpcode() != ISD::OR) 7199 std::swap(Op0, Op1); 7200 if (Op0.getOpcode() != ISD::OR) 7201 return SDValue(); 7202 7203 // We found an inner OR, so our operands are the operands of the inner OR 7204 // and the other operand of the outer OR. 7205 SDValue A = Op0.getOperand(0); 7206 SDValue B = Op0.getOperand(1); 7207 SDValue C = Op1; 7208 7209 auto Match1 = matchSHFLPat(A); 7210 auto Match2 = matchSHFLPat(B); 7211 7212 // If neither matched, we failed. 7213 if (!Match1 && !Match2) 7214 return SDValue(); 7215 7216 // We had at least one match. if one failed, try the remaining C operand. 7217 if (!Match1) { 7218 std::swap(A, C); 7219 Match1 = matchSHFLPat(A); 7220 if (!Match1) 7221 return SDValue(); 7222 } else if (!Match2) { 7223 std::swap(B, C); 7224 Match2 = matchSHFLPat(B); 7225 if (!Match2) 7226 return SDValue(); 7227 } 7228 assert(Match1 && Match2); 7229 7230 // Make sure our matches pair up. 7231 if (!Match1->formsPairWith(*Match2)) 7232 return SDValue(); 7233 7234 // All the remains is to make sure C is an AND with the same input, that masks 7235 // out the bits that are being shuffled. 7236 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7237 C.getOperand(0) != Match1->Op) 7238 return SDValue(); 7239 7240 uint64_t Mask = C.getConstantOperandVal(1); 7241 7242 static const uint64_t BitmanipMasks[] = { 7243 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7244 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7245 }; 7246 7247 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7248 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7249 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7250 7251 if (Mask != ExpMask) 7252 return SDValue(); 7253 7254 SDLoc DL(Op); 7255 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7256 DAG.getConstant(Match1->ShAmt, DL, VT)); 7257 } 7258 7259 // Optimize (add (shl x, c0), (shl y, c1)) -> 7260 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7261 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7262 const RISCVSubtarget &Subtarget) { 7263 // Perform this optimization only in the zba extension. 7264 if (!Subtarget.hasStdExtZba()) 7265 return SDValue(); 7266 7267 // Skip for vector types and larger types. 7268 EVT VT = N->getValueType(0); 7269 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7270 return SDValue(); 7271 7272 // The two operand nodes must be SHL and have no other use. 7273 SDValue N0 = N->getOperand(0); 7274 SDValue N1 = N->getOperand(1); 7275 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7276 !N0->hasOneUse() || !N1->hasOneUse()) 7277 return SDValue(); 7278 7279 // Check c0 and c1. 7280 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7281 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7282 if (!N0C || !N1C) 7283 return SDValue(); 7284 int64_t C0 = N0C->getSExtValue(); 7285 int64_t C1 = N1C->getSExtValue(); 7286 if (C0 <= 0 || C1 <= 0) 7287 return SDValue(); 7288 7289 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7290 int64_t Bits = std::min(C0, C1); 7291 int64_t Diff = std::abs(C0 - C1); 7292 if (Diff != 1 && Diff != 2 && Diff != 3) 7293 return SDValue(); 7294 7295 // Build nodes. 7296 SDLoc DL(N); 7297 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7298 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7299 SDValue NA0 = 7300 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7301 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7302 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7303 } 7304 7305 // Combine 7306 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) 7307 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) 7308 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7309 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) 7310 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7311 const RISCVSubtarget &Subtarget) { 7312 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7313 N->getOpcode() == RISCVISD::RORW || 7314 N->getOpcode() == RISCVISD::ROLW) && 7315 "Unexpected opcode!"); 7316 SDValue Src = N->getOperand(0); 7317 SDLoc DL(N); 7318 unsigned Opc; 7319 7320 if (!Subtarget.hasStdExtZbp()) 7321 return SDValue(); 7322 7323 if ((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL) && 7324 Src.getOpcode() == RISCVISD::GREV) 7325 Opc = RISCVISD::GREV; 7326 else if ((N->getOpcode() == RISCVISD::RORW || 7327 N->getOpcode() == RISCVISD::ROLW) && 7328 Src.getOpcode() == RISCVISD::GREVW) 7329 Opc = RISCVISD::GREVW; 7330 else 7331 return SDValue(); 7332 7333 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7334 !isa<ConstantSDNode>(Src.getOperand(1))) 7335 return SDValue(); 7336 7337 unsigned ShAmt1 = N->getConstantOperandVal(1); 7338 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7339 if (ShAmt1 != 16 && ShAmt2 != 24) 7340 return SDValue(); 7341 7342 Src = Src.getOperand(0); 7343 return DAG.getNode(Opc, DL, N->getValueType(0), Src, 7344 DAG.getConstant(8, DL, N->getOperand(1).getValueType())); 7345 } 7346 7347 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7348 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7349 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7350 // not undo itself, but they are redundant. 7351 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7352 SDValue Src = N->getOperand(0); 7353 7354 if (Src.getOpcode() != N->getOpcode()) 7355 return SDValue(); 7356 7357 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7358 !isa<ConstantSDNode>(Src.getOperand(1))) 7359 return SDValue(); 7360 7361 unsigned ShAmt1 = N->getConstantOperandVal(1); 7362 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7363 Src = Src.getOperand(0); 7364 7365 unsigned CombinedShAmt; 7366 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7367 CombinedShAmt = ShAmt1 | ShAmt2; 7368 else 7369 CombinedShAmt = ShAmt1 ^ ShAmt2; 7370 7371 if (CombinedShAmt == 0) 7372 return Src; 7373 7374 SDLoc DL(N); 7375 return DAG.getNode( 7376 N->getOpcode(), DL, N->getValueType(0), Src, 7377 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7378 } 7379 7380 // Combine a constant select operand into its use: 7381 // 7382 // (and (select cond, -1, c), x) 7383 // -> (select cond, x, (and x, c)) [AllOnes=1] 7384 // (or (select cond, 0, c), x) 7385 // -> (select cond, x, (or x, c)) [AllOnes=0] 7386 // (xor (select cond, 0, c), x) 7387 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7388 // (add (select cond, 0, c), x) 7389 // -> (select cond, x, (add x, c)) [AllOnes=0] 7390 // (sub x, (select cond, 0, c)) 7391 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7392 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7393 SelectionDAG &DAG, bool AllOnes) { 7394 EVT VT = N->getValueType(0); 7395 7396 // Skip vectors. 7397 if (VT.isVector()) 7398 return SDValue(); 7399 7400 if ((Slct.getOpcode() != ISD::SELECT && 7401 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7402 !Slct.hasOneUse()) 7403 return SDValue(); 7404 7405 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7406 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7407 }; 7408 7409 bool SwapSelectOps; 7410 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7411 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7412 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7413 SDValue NonConstantVal; 7414 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7415 SwapSelectOps = false; 7416 NonConstantVal = FalseVal; 7417 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7418 SwapSelectOps = true; 7419 NonConstantVal = TrueVal; 7420 } else 7421 return SDValue(); 7422 7423 // Slct is now know to be the desired identity constant when CC is true. 7424 TrueVal = OtherOp; 7425 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7426 // Unless SwapSelectOps says the condition should be false. 7427 if (SwapSelectOps) 7428 std::swap(TrueVal, FalseVal); 7429 7430 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7431 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7432 {Slct.getOperand(0), Slct.getOperand(1), 7433 Slct.getOperand(2), TrueVal, FalseVal}); 7434 7435 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7436 {Slct.getOperand(0), TrueVal, FalseVal}); 7437 } 7438 7439 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7440 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7441 bool AllOnes) { 7442 SDValue N0 = N->getOperand(0); 7443 SDValue N1 = N->getOperand(1); 7444 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7445 return Result; 7446 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7447 return Result; 7448 return SDValue(); 7449 } 7450 7451 // Transform (add (mul x, c0), c1) -> 7452 // (add (mul (add x, c1/c0), c0), c1%c0). 7453 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7454 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7455 // to an infinite loop in DAGCombine if transformed. 7456 // Or transform (add (mul x, c0), c1) -> 7457 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7458 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7459 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7460 // lead to an infinite loop in DAGCombine if transformed. 7461 // Or transform (add (mul x, c0), c1) -> 7462 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7463 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7464 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7465 // lead to an infinite loop in DAGCombine if transformed. 7466 // Or transform (add (mul x, c0), c1) -> 7467 // (mul (add x, c1/c0), c0). 7468 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7469 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7470 const RISCVSubtarget &Subtarget) { 7471 // Skip for vector types and larger types. 7472 EVT VT = N->getValueType(0); 7473 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7474 return SDValue(); 7475 // The first operand node must be a MUL and has no other use. 7476 SDValue N0 = N->getOperand(0); 7477 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7478 return SDValue(); 7479 // Check if c0 and c1 match above conditions. 7480 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7481 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7482 if (!N0C || !N1C) 7483 return SDValue(); 7484 // If N0C has multiple uses it's possible one of the cases in 7485 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7486 // in an infinite loop. 7487 if (!N0C->hasOneUse()) 7488 return SDValue(); 7489 int64_t C0 = N0C->getSExtValue(); 7490 int64_t C1 = N1C->getSExtValue(); 7491 int64_t CA, CB; 7492 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7493 return SDValue(); 7494 // Search for proper CA (non-zero) and CB that both are simm12. 7495 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7496 !isInt<12>(C0 * (C1 / C0))) { 7497 CA = C1 / C0; 7498 CB = C1 % C0; 7499 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7500 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7501 CA = C1 / C0 + 1; 7502 CB = C1 % C0 - C0; 7503 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7504 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7505 CA = C1 / C0 - 1; 7506 CB = C1 % C0 + C0; 7507 } else 7508 return SDValue(); 7509 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7510 SDLoc DL(N); 7511 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7512 DAG.getConstant(CA, DL, VT)); 7513 SDValue New1 = 7514 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7515 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7516 } 7517 7518 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7519 const RISCVSubtarget &Subtarget) { 7520 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7521 return V; 7522 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7523 return V; 7524 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7525 // (select lhs, rhs, cc, x, (add x, y)) 7526 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7527 } 7528 7529 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7530 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7531 // (select lhs, rhs, cc, x, (sub x, y)) 7532 SDValue N0 = N->getOperand(0); 7533 SDValue N1 = N->getOperand(1); 7534 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7535 } 7536 7537 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7538 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7539 // (select lhs, rhs, cc, x, (and x, y)) 7540 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7541 } 7542 7543 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7544 const RISCVSubtarget &Subtarget) { 7545 if (Subtarget.hasStdExtZbp()) { 7546 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7547 return GREV; 7548 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7549 return GORC; 7550 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7551 return SHFL; 7552 } 7553 7554 // fold (or (select cond, 0, y), x) -> 7555 // (select cond, x, (or x, y)) 7556 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7557 } 7558 7559 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7560 // fold (xor (select cond, 0, y), x) -> 7561 // (select cond, x, (xor x, y)) 7562 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7563 } 7564 7565 static SDValue performSIGN_EXTEND_INREG(SDNode *N, SelectionDAG &DAG) { 7566 SDValue Src = N->getOperand(0); 7567 7568 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7569 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7570 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7571 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), N->getValueType(0), 7572 Src.getOperand(0)); 7573 7574 return SDValue(); 7575 } 7576 7577 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7578 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7579 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7580 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7581 // ADDW/SUBW/MULW. 7582 static SDValue performANY_EXTENDCombine(SDNode *N, 7583 TargetLowering::DAGCombinerInfo &DCI, 7584 const RISCVSubtarget &Subtarget) { 7585 if (!Subtarget.is64Bit()) 7586 return SDValue(); 7587 7588 SelectionDAG &DAG = DCI.DAG; 7589 7590 SDValue Src = N->getOperand(0); 7591 EVT VT = N->getValueType(0); 7592 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7593 return SDValue(); 7594 7595 // The opcode must be one that can implicitly sign_extend. 7596 // FIXME: Additional opcodes. 7597 switch (Src.getOpcode()) { 7598 default: 7599 return SDValue(); 7600 case ISD::MUL: 7601 if (!Subtarget.hasStdExtM()) 7602 return SDValue(); 7603 LLVM_FALLTHROUGH; 7604 case ISD::ADD: 7605 case ISD::SUB: 7606 break; 7607 } 7608 7609 // Only handle cases where the result is used by a CopyToReg. That likely 7610 // means the value is a liveout of the basic block. This helps prevent 7611 // infinite combine loops like PR51206. 7612 if (none_of(N->uses(), 7613 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7614 return SDValue(); 7615 7616 SmallVector<SDNode *, 4> SetCCs; 7617 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7618 UE = Src.getNode()->use_end(); 7619 UI != UE; ++UI) { 7620 SDNode *User = *UI; 7621 if (User == N) 7622 continue; 7623 if (UI.getUse().getResNo() != Src.getResNo()) 7624 continue; 7625 // All i32 setccs are legalized by sign extending operands. 7626 if (User->getOpcode() == ISD::SETCC) { 7627 SetCCs.push_back(User); 7628 continue; 7629 } 7630 // We don't know if we can extend this user. 7631 break; 7632 } 7633 7634 // If we don't have any SetCCs, this isn't worthwhile. 7635 if (SetCCs.empty()) 7636 return SDValue(); 7637 7638 SDLoc DL(N); 7639 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7640 DCI.CombineTo(N, SExt); 7641 7642 // Promote all the setccs. 7643 for (SDNode *SetCC : SetCCs) { 7644 SmallVector<SDValue, 4> Ops; 7645 7646 for (unsigned j = 0; j != 2; ++j) { 7647 SDValue SOp = SetCC->getOperand(j); 7648 if (SOp == Src) 7649 Ops.push_back(SExt); 7650 else 7651 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7652 } 7653 7654 Ops.push_back(SetCC->getOperand(2)); 7655 DCI.CombineTo(SetCC, 7656 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7657 } 7658 return SDValue(N, 0); 7659 } 7660 7661 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7662 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7663 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7664 bool Commute = false) { 7665 assert((N->getOpcode() == RISCVISD::ADD_VL || 7666 N->getOpcode() == RISCVISD::SUB_VL) && 7667 "Unexpected opcode"); 7668 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7669 SDValue Op0 = N->getOperand(0); 7670 SDValue Op1 = N->getOperand(1); 7671 if (Commute) 7672 std::swap(Op0, Op1); 7673 7674 MVT VT = N->getSimpleValueType(0); 7675 7676 // Determine the narrow size for a widening add/sub. 7677 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7678 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7679 VT.getVectorElementCount()); 7680 7681 SDValue Mask = N->getOperand(2); 7682 SDValue VL = N->getOperand(3); 7683 7684 SDLoc DL(N); 7685 7686 // If the RHS is a sext or zext, we can form a widening op. 7687 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7688 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7689 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7690 unsigned ExtOpc = Op1.getOpcode(); 7691 Op1 = Op1.getOperand(0); 7692 // Re-introduce narrower extends if needed. 7693 if (Op1.getValueType() != NarrowVT) 7694 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7695 7696 unsigned WOpc; 7697 if (ExtOpc == RISCVISD::VSEXT_VL) 7698 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7699 else 7700 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7701 7702 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7703 } 7704 7705 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7706 // sext/zext? 7707 7708 return SDValue(); 7709 } 7710 7711 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7712 // vwsub(u).vv/vx. 7713 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7714 SDValue Op0 = N->getOperand(0); 7715 SDValue Op1 = N->getOperand(1); 7716 SDValue Mask = N->getOperand(2); 7717 SDValue VL = N->getOperand(3); 7718 7719 MVT VT = N->getSimpleValueType(0); 7720 MVT NarrowVT = Op1.getSimpleValueType(); 7721 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7722 7723 unsigned VOpc; 7724 switch (N->getOpcode()) { 7725 default: llvm_unreachable("Unexpected opcode"); 7726 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7727 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7728 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7729 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7730 } 7731 7732 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7733 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7734 7735 SDLoc DL(N); 7736 7737 // If the LHS is a sext or zext, we can narrow this op to the same size as 7738 // the RHS. 7739 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7740 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7741 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7742 unsigned ExtOpc = Op0.getOpcode(); 7743 Op0 = Op0.getOperand(0); 7744 // Re-introduce narrower extends if needed. 7745 if (Op0.getValueType() != NarrowVT) 7746 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7747 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7748 } 7749 7750 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7751 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7752 7753 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7754 // to commute and use a vwadd(u).vx instead. 7755 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7756 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7757 Op0 = Op0.getOperand(1); 7758 7759 // See if have enough sign bits or zero bits in the scalar to use a 7760 // widening add/sub by splatting to smaller element size. 7761 unsigned EltBits = VT.getScalarSizeInBits(); 7762 unsigned ScalarBits = Op0.getValueSizeInBits(); 7763 // Make sure we're getting all element bits from the scalar register. 7764 // FIXME: Support implicit sign extension of vmv.v.x? 7765 if (ScalarBits < EltBits) 7766 return SDValue(); 7767 7768 if (IsSigned) { 7769 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7770 return SDValue(); 7771 } else { 7772 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7773 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7774 return SDValue(); 7775 } 7776 7777 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7778 DAG.getUNDEF(NarrowVT), Op0, VL); 7779 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7780 } 7781 7782 return SDValue(); 7783 } 7784 7785 // Try to form VWMUL, VWMULU or VWMULSU. 7786 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7787 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7788 bool Commute) { 7789 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7790 SDValue Op0 = N->getOperand(0); 7791 SDValue Op1 = N->getOperand(1); 7792 if (Commute) 7793 std::swap(Op0, Op1); 7794 7795 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7796 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7797 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7798 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7799 return SDValue(); 7800 7801 SDValue Mask = N->getOperand(2); 7802 SDValue VL = N->getOperand(3); 7803 7804 // Make sure the mask and VL match. 7805 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7806 return SDValue(); 7807 7808 MVT VT = N->getSimpleValueType(0); 7809 7810 // Determine the narrow size for a widening multiply. 7811 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7812 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7813 VT.getVectorElementCount()); 7814 7815 SDLoc DL(N); 7816 7817 // See if the other operand is the same opcode. 7818 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7819 if (!Op1.hasOneUse()) 7820 return SDValue(); 7821 7822 // Make sure the mask and VL match. 7823 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7824 return SDValue(); 7825 7826 Op1 = Op1.getOperand(0); 7827 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7828 // The operand is a splat of a scalar. 7829 7830 // The pasthru must be undef for tail agnostic 7831 if (!Op1.getOperand(0).isUndef()) 7832 return SDValue(); 7833 // The VL must be the same. 7834 if (Op1.getOperand(2) != VL) 7835 return SDValue(); 7836 7837 // Get the scalar value. 7838 Op1 = Op1.getOperand(1); 7839 7840 // See if have enough sign bits or zero bits in the scalar to use a 7841 // widening multiply by splatting to smaller element size. 7842 unsigned EltBits = VT.getScalarSizeInBits(); 7843 unsigned ScalarBits = Op1.getValueSizeInBits(); 7844 // Make sure we're getting all element bits from the scalar register. 7845 // FIXME: Support implicit sign extension of vmv.v.x? 7846 if (ScalarBits < EltBits) 7847 return SDValue(); 7848 7849 // If the LHS is a sign extend, try to use vwmul. 7850 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7851 // Can use vwmul. 7852 } else { 7853 // Otherwise try to use vwmulu or vwmulsu. 7854 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7855 if (DAG.MaskedValueIsZero(Op1, Mask)) 7856 IsVWMULSU = IsSignExt; 7857 else 7858 return SDValue(); 7859 } 7860 7861 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7862 DAG.getUNDEF(NarrowVT), Op1, VL); 7863 } else 7864 return SDValue(); 7865 7866 Op0 = Op0.getOperand(0); 7867 7868 // Re-introduce narrower extends if needed. 7869 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7870 if (Op0.getValueType() != NarrowVT) 7871 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7872 // vwmulsu requires second operand to be zero extended. 7873 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7874 if (Op1.getValueType() != NarrowVT) 7875 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7876 7877 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7878 if (!IsVWMULSU) 7879 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7880 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7881 } 7882 7883 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7884 switch (Op.getOpcode()) { 7885 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7886 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7887 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7888 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7889 case ISD::FROUND: return RISCVFPRndMode::RMM; 7890 } 7891 7892 return RISCVFPRndMode::Invalid; 7893 } 7894 7895 // Fold 7896 // (fp_to_int (froundeven X)) -> fcvt X, rne 7897 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7898 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7899 // (fp_to_int (fceil X)) -> fcvt X, rup 7900 // (fp_to_int (fround X)) -> fcvt X, rmm 7901 static SDValue performFP_TO_INTCombine(SDNode *N, 7902 TargetLowering::DAGCombinerInfo &DCI, 7903 const RISCVSubtarget &Subtarget) { 7904 SelectionDAG &DAG = DCI.DAG; 7905 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7906 MVT XLenVT = Subtarget.getXLenVT(); 7907 7908 // Only handle XLen or i32 types. Other types narrower than XLen will 7909 // eventually be legalized to XLenVT. 7910 EVT VT = N->getValueType(0); 7911 if (VT != MVT::i32 && VT != XLenVT) 7912 return SDValue(); 7913 7914 SDValue Src = N->getOperand(0); 7915 7916 // Ensure the FP type is also legal. 7917 if (!TLI.isTypeLegal(Src.getValueType())) 7918 return SDValue(); 7919 7920 // Don't do this for f16 with Zfhmin and not Zfh. 7921 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7922 return SDValue(); 7923 7924 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7925 if (FRM == RISCVFPRndMode::Invalid) 7926 return SDValue(); 7927 7928 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7929 7930 unsigned Opc; 7931 if (VT == XLenVT) 7932 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7933 else 7934 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7935 7936 SDLoc DL(N); 7937 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7938 DAG.getTargetConstant(FRM, DL, XLenVT)); 7939 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7940 } 7941 7942 // Fold 7943 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7944 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7945 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7946 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7947 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7948 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7949 TargetLowering::DAGCombinerInfo &DCI, 7950 const RISCVSubtarget &Subtarget) { 7951 SelectionDAG &DAG = DCI.DAG; 7952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7953 MVT XLenVT = Subtarget.getXLenVT(); 7954 7955 // Only handle XLen types. Other types narrower than XLen will eventually be 7956 // legalized to XLenVT. 7957 EVT DstVT = N->getValueType(0); 7958 if (DstVT != XLenVT) 7959 return SDValue(); 7960 7961 SDValue Src = N->getOperand(0); 7962 7963 // Ensure the FP type is also legal. 7964 if (!TLI.isTypeLegal(Src.getValueType())) 7965 return SDValue(); 7966 7967 // Don't do this for f16 with Zfhmin and not Zfh. 7968 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7969 return SDValue(); 7970 7971 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7972 7973 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7974 if (FRM == RISCVFPRndMode::Invalid) 7975 return SDValue(); 7976 7977 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7978 7979 unsigned Opc; 7980 if (SatVT == DstVT) 7981 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7982 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7983 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7984 else 7985 return SDValue(); 7986 // FIXME: Support other SatVTs by clamping before or after the conversion. 7987 7988 Src = Src.getOperand(0); 7989 7990 SDLoc DL(N); 7991 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7992 DAG.getTargetConstant(FRM, DL, XLenVT)); 7993 7994 // RISCV FP-to-int conversions saturate to the destination register size, but 7995 // don't produce 0 for nan. 7996 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7997 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7998 } 7999 8000 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8001 DAGCombinerInfo &DCI) const { 8002 SelectionDAG &DAG = DCI.DAG; 8003 8004 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8005 // bits are demanded. N will be added to the Worklist if it was not deleted. 8006 // Caller should return SDValue(N, 0) if this returns true. 8007 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8008 SDValue Op = N->getOperand(OpNo); 8009 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8010 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8011 return false; 8012 8013 if (N->getOpcode() != ISD::DELETED_NODE) 8014 DCI.AddToWorklist(N); 8015 return true; 8016 }; 8017 8018 switch (N->getOpcode()) { 8019 default: 8020 break; 8021 case RISCVISD::SplitF64: { 8022 SDValue Op0 = N->getOperand(0); 8023 // If the input to SplitF64 is just BuildPairF64 then the operation is 8024 // redundant. Instead, use BuildPairF64's operands directly. 8025 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8026 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8027 8028 if (Op0->isUndef()) { 8029 SDValue Lo = DAG.getUNDEF(MVT::i32); 8030 SDValue Hi = DAG.getUNDEF(MVT::i32); 8031 return DCI.CombineTo(N, Lo, Hi); 8032 } 8033 8034 SDLoc DL(N); 8035 8036 // It's cheaper to materialise two 32-bit integers than to load a double 8037 // from the constant pool and transfer it to integer registers through the 8038 // stack. 8039 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8040 APInt V = C->getValueAPF().bitcastToAPInt(); 8041 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8042 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8043 return DCI.CombineTo(N, Lo, Hi); 8044 } 8045 8046 // This is a target-specific version of a DAGCombine performed in 8047 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8048 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8049 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8050 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8051 !Op0.getNode()->hasOneUse()) 8052 break; 8053 SDValue NewSplitF64 = 8054 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8055 Op0.getOperand(0)); 8056 SDValue Lo = NewSplitF64.getValue(0); 8057 SDValue Hi = NewSplitF64.getValue(1); 8058 APInt SignBit = APInt::getSignMask(32); 8059 if (Op0.getOpcode() == ISD::FNEG) { 8060 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8061 DAG.getConstant(SignBit, DL, MVT::i32)); 8062 return DCI.CombineTo(N, Lo, NewHi); 8063 } 8064 assert(Op0.getOpcode() == ISD::FABS); 8065 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8066 DAG.getConstant(~SignBit, DL, MVT::i32)); 8067 return DCI.CombineTo(N, Lo, NewHi); 8068 } 8069 case RISCVISD::SLLW: 8070 case RISCVISD::SRAW: 8071 case RISCVISD::SRLW: { 8072 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8073 if (SimplifyDemandedLowBitsHelper(0, 32) || 8074 SimplifyDemandedLowBitsHelper(1, 5)) 8075 return SDValue(N, 0); 8076 8077 break; 8078 } 8079 case ISD::ROTR: 8080 case ISD::ROTL: 8081 case RISCVISD::RORW: 8082 case RISCVISD::ROLW: { 8083 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8084 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8085 if (SimplifyDemandedLowBitsHelper(0, 32) || 8086 SimplifyDemandedLowBitsHelper(1, 5)) 8087 return SDValue(N, 0); 8088 } 8089 8090 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8091 } 8092 case RISCVISD::CLZW: 8093 case RISCVISD::CTZW: { 8094 // Only the lower 32 bits of the first operand are read 8095 if (SimplifyDemandedLowBitsHelper(0, 32)) 8096 return SDValue(N, 0); 8097 break; 8098 } 8099 case RISCVISD::GREV: 8100 case RISCVISD::GORC: { 8101 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8102 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8103 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8104 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8105 return SDValue(N, 0); 8106 8107 return combineGREVI_GORCI(N, DAG); 8108 } 8109 case RISCVISD::GREVW: 8110 case RISCVISD::GORCW: { 8111 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8112 if (SimplifyDemandedLowBitsHelper(0, 32) || 8113 SimplifyDemandedLowBitsHelper(1, 5)) 8114 return SDValue(N, 0); 8115 8116 return combineGREVI_GORCI(N, DAG); 8117 } 8118 case RISCVISD::SHFL: 8119 case RISCVISD::UNSHFL: { 8120 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8121 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8122 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8123 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8124 return SDValue(N, 0); 8125 8126 break; 8127 } 8128 case RISCVISD::SHFLW: 8129 case RISCVISD::UNSHFLW: { 8130 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8131 if (SimplifyDemandedLowBitsHelper(0, 32) || 8132 SimplifyDemandedLowBitsHelper(1, 4)) 8133 return SDValue(N, 0); 8134 8135 break; 8136 } 8137 case RISCVISD::BCOMPRESSW: 8138 case RISCVISD::BDECOMPRESSW: { 8139 // Only the lower 32 bits of LHS and RHS are read. 8140 if (SimplifyDemandedLowBitsHelper(0, 32) || 8141 SimplifyDemandedLowBitsHelper(1, 32)) 8142 return SDValue(N, 0); 8143 8144 break; 8145 } 8146 case RISCVISD::FMV_X_ANYEXTH: 8147 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8148 SDLoc DL(N); 8149 SDValue Op0 = N->getOperand(0); 8150 MVT VT = N->getSimpleValueType(0); 8151 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8152 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8153 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8154 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8155 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8156 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8157 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8158 assert(Op0.getOperand(0).getValueType() == VT && 8159 "Unexpected value type!"); 8160 return Op0.getOperand(0); 8161 } 8162 8163 // This is a target-specific version of a DAGCombine performed in 8164 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8165 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8166 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8167 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8168 !Op0.getNode()->hasOneUse()) 8169 break; 8170 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8171 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8172 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8173 if (Op0.getOpcode() == ISD::FNEG) 8174 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8175 DAG.getConstant(SignBit, DL, VT)); 8176 8177 assert(Op0.getOpcode() == ISD::FABS); 8178 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8179 DAG.getConstant(~SignBit, DL, VT)); 8180 } 8181 case ISD::ADD: 8182 return performADDCombine(N, DAG, Subtarget); 8183 case ISD::SUB: 8184 return performSUBCombine(N, DAG); 8185 case ISD::AND: 8186 return performANDCombine(N, DAG); 8187 case ISD::OR: 8188 return performORCombine(N, DAG, Subtarget); 8189 case ISD::XOR: 8190 return performXORCombine(N, DAG); 8191 case ISD::SIGN_EXTEND_INREG: 8192 return performSIGN_EXTEND_INREG(N, DAG); 8193 case ISD::ANY_EXTEND: 8194 return performANY_EXTENDCombine(N, DCI, Subtarget); 8195 case ISD::ZERO_EXTEND: 8196 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8197 // type legalization. This is safe because fp_to_uint produces poison if 8198 // it overflows. 8199 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8200 SDValue Src = N->getOperand(0); 8201 if (Src.getOpcode() == ISD::FP_TO_UINT && 8202 isTypeLegal(Src.getOperand(0).getValueType())) 8203 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8204 Src.getOperand(0)); 8205 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8206 isTypeLegal(Src.getOperand(1).getValueType())) { 8207 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8208 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8209 Src.getOperand(0), Src.getOperand(1)); 8210 DCI.CombineTo(N, Res); 8211 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8212 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8213 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8214 } 8215 } 8216 return SDValue(); 8217 case RISCVISD::SELECT_CC: { 8218 // Transform 8219 SDValue LHS = N->getOperand(0); 8220 SDValue RHS = N->getOperand(1); 8221 SDValue TrueV = N->getOperand(3); 8222 SDValue FalseV = N->getOperand(4); 8223 8224 // If the True and False values are the same, we don't need a select_cc. 8225 if (TrueV == FalseV) 8226 return TrueV; 8227 8228 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8229 if (!ISD::isIntEqualitySetCC(CCVal)) 8230 break; 8231 8232 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8233 // (select_cc X, Y, lt, trueV, falseV) 8234 // Sometimes the setcc is introduced after select_cc has been formed. 8235 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8236 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8237 // If we're looking for eq 0 instead of ne 0, we need to invert the 8238 // condition. 8239 bool Invert = CCVal == ISD::SETEQ; 8240 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8241 if (Invert) 8242 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8243 8244 SDLoc DL(N); 8245 RHS = LHS.getOperand(1); 8246 LHS = LHS.getOperand(0); 8247 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8248 8249 SDValue TargetCC = DAG.getCondCode(CCVal); 8250 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8251 {LHS, RHS, TargetCC, TrueV, FalseV}); 8252 } 8253 8254 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8255 // (select_cc X, Y, eq/ne, trueV, falseV) 8256 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8257 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8258 {LHS.getOperand(0), LHS.getOperand(1), 8259 N->getOperand(2), TrueV, FalseV}); 8260 // (select_cc X, 1, setne, trueV, falseV) -> 8261 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8262 // This can occur when legalizing some floating point comparisons. 8263 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8264 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8265 SDLoc DL(N); 8266 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8267 SDValue TargetCC = DAG.getCondCode(CCVal); 8268 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8269 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8270 {LHS, RHS, TargetCC, TrueV, FalseV}); 8271 } 8272 8273 break; 8274 } 8275 case RISCVISD::BR_CC: { 8276 SDValue LHS = N->getOperand(1); 8277 SDValue RHS = N->getOperand(2); 8278 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8279 if (!ISD::isIntEqualitySetCC(CCVal)) 8280 break; 8281 8282 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8283 // (br_cc X, Y, lt, dest) 8284 // Sometimes the setcc is introduced after br_cc has been formed. 8285 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8286 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8287 // If we're looking for eq 0 instead of ne 0, we need to invert the 8288 // condition. 8289 bool Invert = CCVal == ISD::SETEQ; 8290 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8291 if (Invert) 8292 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8293 8294 SDLoc DL(N); 8295 RHS = LHS.getOperand(1); 8296 LHS = LHS.getOperand(0); 8297 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8298 8299 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8300 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8301 N->getOperand(4)); 8302 } 8303 8304 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8305 // (br_cc X, Y, eq/ne, trueV, falseV) 8306 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8307 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8308 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8309 N->getOperand(3), N->getOperand(4)); 8310 8311 // (br_cc X, 1, setne, br_cc) -> 8312 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8313 // This can occur when legalizing some floating point comparisons. 8314 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8315 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8316 SDLoc DL(N); 8317 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8318 SDValue TargetCC = DAG.getCondCode(CCVal); 8319 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8320 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8321 N->getOperand(0), LHS, RHS, TargetCC, 8322 N->getOperand(4)); 8323 } 8324 break; 8325 } 8326 case ISD::FP_TO_SINT: 8327 case ISD::FP_TO_UINT: 8328 return performFP_TO_INTCombine(N, DCI, Subtarget); 8329 case ISD::FP_TO_SINT_SAT: 8330 case ISD::FP_TO_UINT_SAT: 8331 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8332 case ISD::FCOPYSIGN: { 8333 EVT VT = N->getValueType(0); 8334 if (!VT.isVector()) 8335 break; 8336 // There is a form of VFSGNJ which injects the negated sign of its second 8337 // operand. Try and bubble any FNEG up after the extend/round to produce 8338 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8339 // TRUNC=1. 8340 SDValue In2 = N->getOperand(1); 8341 // Avoid cases where the extend/round has multiple uses, as duplicating 8342 // those is typically more expensive than removing a fneg. 8343 if (!In2.hasOneUse()) 8344 break; 8345 if (In2.getOpcode() != ISD::FP_EXTEND && 8346 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8347 break; 8348 In2 = In2.getOperand(0); 8349 if (In2.getOpcode() != ISD::FNEG) 8350 break; 8351 SDLoc DL(N); 8352 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8353 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8354 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8355 } 8356 case ISD::MGATHER: 8357 case ISD::MSCATTER: 8358 case ISD::VP_GATHER: 8359 case ISD::VP_SCATTER: { 8360 if (!DCI.isBeforeLegalize()) 8361 break; 8362 SDValue Index, ScaleOp; 8363 bool IsIndexScaled = false; 8364 bool IsIndexSigned = false; 8365 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8366 Index = VPGSN->getIndex(); 8367 ScaleOp = VPGSN->getScale(); 8368 IsIndexScaled = VPGSN->isIndexScaled(); 8369 IsIndexSigned = VPGSN->isIndexSigned(); 8370 } else { 8371 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8372 Index = MGSN->getIndex(); 8373 ScaleOp = MGSN->getScale(); 8374 IsIndexScaled = MGSN->isIndexScaled(); 8375 IsIndexSigned = MGSN->isIndexSigned(); 8376 } 8377 EVT IndexVT = Index.getValueType(); 8378 MVT XLenVT = Subtarget.getXLenVT(); 8379 // RISCV indexed loads only support the "unsigned unscaled" addressing 8380 // mode, so anything else must be manually legalized. 8381 bool NeedsIdxLegalization = 8382 IsIndexScaled || 8383 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8384 if (!NeedsIdxLegalization) 8385 break; 8386 8387 SDLoc DL(N); 8388 8389 // Any index legalization should first promote to XLenVT, so we don't lose 8390 // bits when scaling. This may create an illegal index type so we let 8391 // LLVM's legalization take care of the splitting. 8392 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8393 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8394 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8395 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8396 DL, IndexVT, Index); 8397 } 8398 8399 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8400 if (IsIndexScaled && Scale != 1) { 8401 // Manually scale the indices by the element size. 8402 // TODO: Sanitize the scale operand here? 8403 // TODO: For VP nodes, should we use VP_SHL here? 8404 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8405 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8406 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8407 } 8408 8409 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8410 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8411 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8412 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8413 VPGN->getScale(), VPGN->getMask(), 8414 VPGN->getVectorLength()}, 8415 VPGN->getMemOperand(), NewIndexTy); 8416 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8417 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8418 {VPSN->getChain(), VPSN->getValue(), 8419 VPSN->getBasePtr(), Index, VPSN->getScale(), 8420 VPSN->getMask(), VPSN->getVectorLength()}, 8421 VPSN->getMemOperand(), NewIndexTy); 8422 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8423 return DAG.getMaskedGather( 8424 N->getVTList(), MGN->getMemoryVT(), DL, 8425 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8426 MGN->getBasePtr(), Index, MGN->getScale()}, 8427 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8428 const auto *MSN = cast<MaskedScatterSDNode>(N); 8429 return DAG.getMaskedScatter( 8430 N->getVTList(), MSN->getMemoryVT(), DL, 8431 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8432 Index, MSN->getScale()}, 8433 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8434 } 8435 case RISCVISD::SRA_VL: 8436 case RISCVISD::SRL_VL: 8437 case RISCVISD::SHL_VL: { 8438 SDValue ShAmt = N->getOperand(1); 8439 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8440 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8441 SDLoc DL(N); 8442 SDValue VL = N->getOperand(3); 8443 EVT VT = N->getValueType(0); 8444 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8445 ShAmt.getOperand(1), VL); 8446 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8447 N->getOperand(2), N->getOperand(3)); 8448 } 8449 break; 8450 } 8451 case ISD::SRA: 8452 case ISD::SRL: 8453 case ISD::SHL: { 8454 SDValue ShAmt = N->getOperand(1); 8455 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8456 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8457 SDLoc DL(N); 8458 EVT VT = N->getValueType(0); 8459 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8460 ShAmt.getOperand(1), 8461 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8462 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8463 } 8464 break; 8465 } 8466 case RISCVISD::ADD_VL: 8467 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8468 return V; 8469 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8470 case RISCVISD::SUB_VL: 8471 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8472 case RISCVISD::VWADD_W_VL: 8473 case RISCVISD::VWADDU_W_VL: 8474 case RISCVISD::VWSUB_W_VL: 8475 case RISCVISD::VWSUBU_W_VL: 8476 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8477 case RISCVISD::MUL_VL: 8478 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8479 return V; 8480 // Mul is commutative. 8481 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8482 case ISD::STORE: { 8483 auto *Store = cast<StoreSDNode>(N); 8484 SDValue Val = Store->getValue(); 8485 // Combine store of vmv.x.s to vse with VL of 1. 8486 // FIXME: Support FP. 8487 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8488 SDValue Src = Val.getOperand(0); 8489 EVT VecVT = Src.getValueType(); 8490 EVT MemVT = Store->getMemoryVT(); 8491 // The memory VT and the element type must match. 8492 if (VecVT.getVectorElementType() == MemVT) { 8493 SDLoc DL(N); 8494 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8495 return DAG.getStoreVP( 8496 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8497 DAG.getConstant(1, DL, MaskVT), 8498 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8499 Store->getMemOperand(), Store->getAddressingMode(), 8500 Store->isTruncatingStore(), /*IsCompress*/ false); 8501 } 8502 } 8503 8504 break; 8505 } 8506 case ISD::SPLAT_VECTOR: { 8507 EVT VT = N->getValueType(0); 8508 // Only perform this combine on legal MVT types. 8509 if (!isTypeLegal(VT)) 8510 break; 8511 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8512 DAG, Subtarget)) 8513 return Gather; 8514 break; 8515 } 8516 case RISCVISD::VMV_V_X_VL: { 8517 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8518 // scalar input. 8519 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8520 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8521 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8522 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8523 return SDValue(N, 0); 8524 8525 break; 8526 } 8527 case ISD::INTRINSIC_WO_CHAIN: { 8528 unsigned IntNo = N->getConstantOperandVal(0); 8529 switch (IntNo) { 8530 // By default we do not combine any intrinsic. 8531 default: 8532 return SDValue(); 8533 case Intrinsic::riscv_vcpop: 8534 case Intrinsic::riscv_vcpop_mask: 8535 case Intrinsic::riscv_vfirst: 8536 case Intrinsic::riscv_vfirst_mask: { 8537 SDValue VL = N->getOperand(2); 8538 if (IntNo == Intrinsic::riscv_vcpop_mask || 8539 IntNo == Intrinsic::riscv_vfirst_mask) 8540 VL = N->getOperand(3); 8541 if (!isNullConstant(VL)) 8542 return SDValue(); 8543 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8544 SDLoc DL(N); 8545 EVT VT = N->getValueType(0); 8546 if (IntNo == Intrinsic::riscv_vfirst || 8547 IntNo == Intrinsic::riscv_vfirst_mask) 8548 return DAG.getConstant(-1, DL, VT); 8549 return DAG.getConstant(0, DL, VT); 8550 } 8551 } 8552 } 8553 } 8554 8555 return SDValue(); 8556 } 8557 8558 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8559 const SDNode *N, CombineLevel Level) const { 8560 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8561 // materialised in fewer instructions than `(OP _, c1)`: 8562 // 8563 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8564 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8565 SDValue N0 = N->getOperand(0); 8566 EVT Ty = N0.getValueType(); 8567 if (Ty.isScalarInteger() && 8568 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8569 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8570 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8571 if (C1 && C2) { 8572 const APInt &C1Int = C1->getAPIntValue(); 8573 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8574 8575 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8576 // and the combine should happen, to potentially allow further combines 8577 // later. 8578 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8579 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8580 return true; 8581 8582 // We can materialise `c1` in an add immediate, so it's "free", and the 8583 // combine should be prevented. 8584 if (C1Int.getMinSignedBits() <= 64 && 8585 isLegalAddImmediate(C1Int.getSExtValue())) 8586 return false; 8587 8588 // Neither constant will fit into an immediate, so find materialisation 8589 // costs. 8590 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8591 Subtarget.getFeatureBits(), 8592 /*CompressionCost*/true); 8593 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8594 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8595 /*CompressionCost*/true); 8596 8597 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8598 // combine should be prevented. 8599 if (C1Cost < ShiftedC1Cost) 8600 return false; 8601 } 8602 } 8603 return true; 8604 } 8605 8606 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8607 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8608 TargetLoweringOpt &TLO) const { 8609 // Delay this optimization as late as possible. 8610 if (!TLO.LegalOps) 8611 return false; 8612 8613 EVT VT = Op.getValueType(); 8614 if (VT.isVector()) 8615 return false; 8616 8617 // Only handle AND for now. 8618 if (Op.getOpcode() != ISD::AND) 8619 return false; 8620 8621 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8622 if (!C) 8623 return false; 8624 8625 const APInt &Mask = C->getAPIntValue(); 8626 8627 // Clear all non-demanded bits initially. 8628 APInt ShrunkMask = Mask & DemandedBits; 8629 8630 // Try to make a smaller immediate by setting undemanded bits. 8631 8632 APInt ExpandedMask = Mask | ~DemandedBits; 8633 8634 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8635 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8636 }; 8637 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8638 if (NewMask == Mask) 8639 return true; 8640 SDLoc DL(Op); 8641 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8642 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8643 return TLO.CombineTo(Op, NewOp); 8644 }; 8645 8646 // If the shrunk mask fits in sign extended 12 bits, let the target 8647 // independent code apply it. 8648 if (ShrunkMask.isSignedIntN(12)) 8649 return false; 8650 8651 // Preserve (and X, 0xffff) when zext.h is supported. 8652 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8653 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8654 if (IsLegalMask(NewMask)) 8655 return UseMask(NewMask); 8656 } 8657 8658 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8659 if (VT == MVT::i64) { 8660 APInt NewMask = APInt(64, 0xffffffff); 8661 if (IsLegalMask(NewMask)) 8662 return UseMask(NewMask); 8663 } 8664 8665 // For the remaining optimizations, we need to be able to make a negative 8666 // number through a combination of mask and undemanded bits. 8667 if (!ExpandedMask.isNegative()) 8668 return false; 8669 8670 // What is the fewest number of bits we need to represent the negative number. 8671 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8672 8673 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8674 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8675 APInt NewMask = ShrunkMask; 8676 if (MinSignedBits <= 12) 8677 NewMask.setBitsFrom(11); 8678 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8679 NewMask.setBitsFrom(31); 8680 else 8681 return false; 8682 8683 // Check that our new mask is a subset of the demanded mask. 8684 assert(IsLegalMask(NewMask)); 8685 return UseMask(NewMask); 8686 } 8687 8688 static void computeGREV(APInt &Src, unsigned ShAmt) { 8689 ShAmt &= Src.getBitWidth() - 1; 8690 uint64_t x = Src.getZExtValue(); 8691 if (ShAmt & 1) 8692 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8693 if (ShAmt & 2) 8694 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8695 if (ShAmt & 4) 8696 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8697 if (ShAmt & 8) 8698 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8699 if (ShAmt & 16) 8700 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8701 if (ShAmt & 32) 8702 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8703 Src = x; 8704 } 8705 8706 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8707 KnownBits &Known, 8708 const APInt &DemandedElts, 8709 const SelectionDAG &DAG, 8710 unsigned Depth) const { 8711 unsigned BitWidth = Known.getBitWidth(); 8712 unsigned Opc = Op.getOpcode(); 8713 assert((Opc >= ISD::BUILTIN_OP_END || 8714 Opc == ISD::INTRINSIC_WO_CHAIN || 8715 Opc == ISD::INTRINSIC_W_CHAIN || 8716 Opc == ISD::INTRINSIC_VOID) && 8717 "Should use MaskedValueIsZero if you don't know whether Op" 8718 " is a target node!"); 8719 8720 Known.resetAll(); 8721 switch (Opc) { 8722 default: break; 8723 case RISCVISD::SELECT_CC: { 8724 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8725 // If we don't know any bits, early out. 8726 if (Known.isUnknown()) 8727 break; 8728 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8729 8730 // Only known if known in both the LHS and RHS. 8731 Known = KnownBits::commonBits(Known, Known2); 8732 break; 8733 } 8734 case RISCVISD::REMUW: { 8735 KnownBits Known2; 8736 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8737 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8738 // We only care about the lower 32 bits. 8739 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8740 // Restore the original width by sign extending. 8741 Known = Known.sext(BitWidth); 8742 break; 8743 } 8744 case RISCVISD::DIVUW: { 8745 KnownBits Known2; 8746 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8747 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8748 // We only care about the lower 32 bits. 8749 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8750 // Restore the original width by sign extending. 8751 Known = Known.sext(BitWidth); 8752 break; 8753 } 8754 case RISCVISD::CTZW: { 8755 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8756 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8757 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8758 Known.Zero.setBitsFrom(LowBits); 8759 break; 8760 } 8761 case RISCVISD::CLZW: { 8762 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8763 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8764 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8765 Known.Zero.setBitsFrom(LowBits); 8766 break; 8767 } 8768 case RISCVISD::GREV: 8769 case RISCVISD::GREVW: { 8770 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8771 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8772 if (Opc == RISCVISD::GREVW) 8773 Known = Known.trunc(32); 8774 unsigned ShAmt = C->getZExtValue(); 8775 computeGREV(Known.Zero, ShAmt); 8776 computeGREV(Known.One, ShAmt); 8777 if (Opc == RISCVISD::GREVW) 8778 Known = Known.sext(BitWidth); 8779 } 8780 break; 8781 } 8782 case RISCVISD::READ_VLENB: { 8783 // If we know the minimum VLen from Zvl extensions, we can use that to 8784 // determine the trailing zeros of VLENB. 8785 // FIXME: Limit to 128 bit vectors until we have more testing. 8786 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8787 if (MinVLenB > 0) 8788 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8789 // We assume VLENB is no more than 65536 / 8 bytes. 8790 Known.Zero.setBitsFrom(14); 8791 break; 8792 } 8793 case ISD::INTRINSIC_W_CHAIN: 8794 case ISD::INTRINSIC_WO_CHAIN: { 8795 unsigned IntNo = 8796 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8797 switch (IntNo) { 8798 default: 8799 // We can't do anything for most intrinsics. 8800 break; 8801 case Intrinsic::riscv_vsetvli: 8802 case Intrinsic::riscv_vsetvlimax: 8803 case Intrinsic::riscv_vsetvli_opt: 8804 case Intrinsic::riscv_vsetvlimax_opt: 8805 // Assume that VL output is positive and would fit in an int32_t. 8806 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8807 if (BitWidth >= 32) 8808 Known.Zero.setBitsFrom(31); 8809 break; 8810 } 8811 break; 8812 } 8813 } 8814 } 8815 8816 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8817 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8818 unsigned Depth) const { 8819 switch (Op.getOpcode()) { 8820 default: 8821 break; 8822 case RISCVISD::SELECT_CC: { 8823 unsigned Tmp = 8824 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8825 if (Tmp == 1) return 1; // Early out. 8826 unsigned Tmp2 = 8827 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8828 return std::min(Tmp, Tmp2); 8829 } 8830 case RISCVISD::SLLW: 8831 case RISCVISD::SRAW: 8832 case RISCVISD::SRLW: 8833 case RISCVISD::DIVW: 8834 case RISCVISD::DIVUW: 8835 case RISCVISD::REMUW: 8836 case RISCVISD::ROLW: 8837 case RISCVISD::RORW: 8838 case RISCVISD::GREVW: 8839 case RISCVISD::GORCW: 8840 case RISCVISD::FSLW: 8841 case RISCVISD::FSRW: 8842 case RISCVISD::SHFLW: 8843 case RISCVISD::UNSHFLW: 8844 case RISCVISD::BCOMPRESSW: 8845 case RISCVISD::BDECOMPRESSW: 8846 case RISCVISD::BFPW: 8847 case RISCVISD::FCVT_W_RV64: 8848 case RISCVISD::FCVT_WU_RV64: 8849 case RISCVISD::STRICT_FCVT_W_RV64: 8850 case RISCVISD::STRICT_FCVT_WU_RV64: 8851 // TODO: As the result is sign-extended, this is conservatively correct. A 8852 // more precise answer could be calculated for SRAW depending on known 8853 // bits in the shift amount. 8854 return 33; 8855 case RISCVISD::SHFL: 8856 case RISCVISD::UNSHFL: { 8857 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8858 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8859 // will stay within the upper 32 bits. If there were more than 32 sign bits 8860 // before there will be at least 33 sign bits after. 8861 if (Op.getValueType() == MVT::i64 && 8862 isa<ConstantSDNode>(Op.getOperand(1)) && 8863 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8864 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8865 if (Tmp > 32) 8866 return 33; 8867 } 8868 break; 8869 } 8870 case RISCVISD::VMV_X_S: { 8871 // The number of sign bits of the scalar result is computed by obtaining the 8872 // element type of the input vector operand, subtracting its width from the 8873 // XLEN, and then adding one (sign bit within the element type). If the 8874 // element type is wider than XLen, the least-significant XLEN bits are 8875 // taken. 8876 unsigned XLen = Subtarget.getXLen(); 8877 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8878 if (EltBits <= XLen) 8879 return XLen - EltBits + 1; 8880 break; 8881 } 8882 } 8883 8884 return 1; 8885 } 8886 8887 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8888 MachineBasicBlock *BB) { 8889 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8890 8891 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8892 // Should the count have wrapped while it was being read, we need to try 8893 // again. 8894 // ... 8895 // read: 8896 // rdcycleh x3 # load high word of cycle 8897 // rdcycle x2 # load low word of cycle 8898 // rdcycleh x4 # load high word of cycle 8899 // bne x3, x4, read # check if high word reads match, otherwise try again 8900 // ... 8901 8902 MachineFunction &MF = *BB->getParent(); 8903 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8904 MachineFunction::iterator It = ++BB->getIterator(); 8905 8906 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8907 MF.insert(It, LoopMBB); 8908 8909 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8910 MF.insert(It, DoneMBB); 8911 8912 // Transfer the remainder of BB and its successor edges to DoneMBB. 8913 DoneMBB->splice(DoneMBB->begin(), BB, 8914 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8915 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8916 8917 BB->addSuccessor(LoopMBB); 8918 8919 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8920 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8921 Register LoReg = MI.getOperand(0).getReg(); 8922 Register HiReg = MI.getOperand(1).getReg(); 8923 DebugLoc DL = MI.getDebugLoc(); 8924 8925 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8926 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8927 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8928 .addReg(RISCV::X0); 8929 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8930 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8931 .addReg(RISCV::X0); 8932 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8933 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8934 .addReg(RISCV::X0); 8935 8936 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8937 .addReg(HiReg) 8938 .addReg(ReadAgainReg) 8939 .addMBB(LoopMBB); 8940 8941 LoopMBB->addSuccessor(LoopMBB); 8942 LoopMBB->addSuccessor(DoneMBB); 8943 8944 MI.eraseFromParent(); 8945 8946 return DoneMBB; 8947 } 8948 8949 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8950 MachineBasicBlock *BB) { 8951 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8952 8953 MachineFunction &MF = *BB->getParent(); 8954 DebugLoc DL = MI.getDebugLoc(); 8955 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8956 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8957 Register LoReg = MI.getOperand(0).getReg(); 8958 Register HiReg = MI.getOperand(1).getReg(); 8959 Register SrcReg = MI.getOperand(2).getReg(); 8960 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8961 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8962 8963 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8964 RI); 8965 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8966 MachineMemOperand *MMOLo = 8967 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8968 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8969 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8970 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8971 .addFrameIndex(FI) 8972 .addImm(0) 8973 .addMemOperand(MMOLo); 8974 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8975 .addFrameIndex(FI) 8976 .addImm(4) 8977 .addMemOperand(MMOHi); 8978 MI.eraseFromParent(); // The pseudo instruction is gone now. 8979 return BB; 8980 } 8981 8982 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8983 MachineBasicBlock *BB) { 8984 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8985 "Unexpected instruction"); 8986 8987 MachineFunction &MF = *BB->getParent(); 8988 DebugLoc DL = MI.getDebugLoc(); 8989 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8990 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8991 Register DstReg = MI.getOperand(0).getReg(); 8992 Register LoReg = MI.getOperand(1).getReg(); 8993 Register HiReg = MI.getOperand(2).getReg(); 8994 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8995 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8996 8997 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8998 MachineMemOperand *MMOLo = 8999 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9000 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9001 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9002 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9003 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9004 .addFrameIndex(FI) 9005 .addImm(0) 9006 .addMemOperand(MMOLo); 9007 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9008 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9009 .addFrameIndex(FI) 9010 .addImm(4) 9011 .addMemOperand(MMOHi); 9012 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9013 MI.eraseFromParent(); // The pseudo instruction is gone now. 9014 return BB; 9015 } 9016 9017 static bool isSelectPseudo(MachineInstr &MI) { 9018 switch (MI.getOpcode()) { 9019 default: 9020 return false; 9021 case RISCV::Select_GPR_Using_CC_GPR: 9022 case RISCV::Select_FPR16_Using_CC_GPR: 9023 case RISCV::Select_FPR32_Using_CC_GPR: 9024 case RISCV::Select_FPR64_Using_CC_GPR: 9025 return true; 9026 } 9027 } 9028 9029 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9030 unsigned RelOpcode, unsigned EqOpcode, 9031 const RISCVSubtarget &Subtarget) { 9032 DebugLoc DL = MI.getDebugLoc(); 9033 Register DstReg = MI.getOperand(0).getReg(); 9034 Register Src1Reg = MI.getOperand(1).getReg(); 9035 Register Src2Reg = MI.getOperand(2).getReg(); 9036 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9037 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9038 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9039 9040 // Save the current FFLAGS. 9041 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9042 9043 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9044 .addReg(Src1Reg) 9045 .addReg(Src2Reg); 9046 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9047 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9048 9049 // Restore the FFLAGS. 9050 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9051 .addReg(SavedFFlags, RegState::Kill); 9052 9053 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9054 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9055 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9056 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9057 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9058 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9059 9060 // Erase the pseudoinstruction. 9061 MI.eraseFromParent(); 9062 return BB; 9063 } 9064 9065 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9066 MachineBasicBlock *BB, 9067 const RISCVSubtarget &Subtarget) { 9068 // To "insert" Select_* instructions, we actually have to insert the triangle 9069 // control-flow pattern. The incoming instructions know the destination vreg 9070 // to set, the condition code register to branch on, the true/false values to 9071 // select between, and the condcode to use to select the appropriate branch. 9072 // 9073 // We produce the following control flow: 9074 // HeadMBB 9075 // | \ 9076 // | IfFalseMBB 9077 // | / 9078 // TailMBB 9079 // 9080 // When we find a sequence of selects we attempt to optimize their emission 9081 // by sharing the control flow. Currently we only handle cases where we have 9082 // multiple selects with the exact same condition (same LHS, RHS and CC). 9083 // The selects may be interleaved with other instructions if the other 9084 // instructions meet some requirements we deem safe: 9085 // - They are debug instructions. Otherwise, 9086 // - They do not have side-effects, do not access memory and their inputs do 9087 // not depend on the results of the select pseudo-instructions. 9088 // The TrueV/FalseV operands of the selects cannot depend on the result of 9089 // previous selects in the sequence. 9090 // These conditions could be further relaxed. See the X86 target for a 9091 // related approach and more information. 9092 Register LHS = MI.getOperand(1).getReg(); 9093 Register RHS = MI.getOperand(2).getReg(); 9094 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9095 9096 SmallVector<MachineInstr *, 4> SelectDebugValues; 9097 SmallSet<Register, 4> SelectDests; 9098 SelectDests.insert(MI.getOperand(0).getReg()); 9099 9100 MachineInstr *LastSelectPseudo = &MI; 9101 9102 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9103 SequenceMBBI != E; ++SequenceMBBI) { 9104 if (SequenceMBBI->isDebugInstr()) 9105 continue; 9106 else if (isSelectPseudo(*SequenceMBBI)) { 9107 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9108 SequenceMBBI->getOperand(2).getReg() != RHS || 9109 SequenceMBBI->getOperand(3).getImm() != CC || 9110 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9111 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9112 break; 9113 LastSelectPseudo = &*SequenceMBBI; 9114 SequenceMBBI->collectDebugValues(SelectDebugValues); 9115 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9116 } else { 9117 if (SequenceMBBI->hasUnmodeledSideEffects() || 9118 SequenceMBBI->mayLoadOrStore()) 9119 break; 9120 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9121 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9122 })) 9123 break; 9124 } 9125 } 9126 9127 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9128 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9129 DebugLoc DL = MI.getDebugLoc(); 9130 MachineFunction::iterator I = ++BB->getIterator(); 9131 9132 MachineBasicBlock *HeadMBB = BB; 9133 MachineFunction *F = BB->getParent(); 9134 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9135 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9136 9137 F->insert(I, IfFalseMBB); 9138 F->insert(I, TailMBB); 9139 9140 // Transfer debug instructions associated with the selects to TailMBB. 9141 for (MachineInstr *DebugInstr : SelectDebugValues) { 9142 TailMBB->push_back(DebugInstr->removeFromParent()); 9143 } 9144 9145 // Move all instructions after the sequence to TailMBB. 9146 TailMBB->splice(TailMBB->end(), HeadMBB, 9147 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9148 // Update machine-CFG edges by transferring all successors of the current 9149 // block to the new block which will contain the Phi nodes for the selects. 9150 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9151 // Set the successors for HeadMBB. 9152 HeadMBB->addSuccessor(IfFalseMBB); 9153 HeadMBB->addSuccessor(TailMBB); 9154 9155 // Insert appropriate branch. 9156 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9157 .addReg(LHS) 9158 .addReg(RHS) 9159 .addMBB(TailMBB); 9160 9161 // IfFalseMBB just falls through to TailMBB. 9162 IfFalseMBB->addSuccessor(TailMBB); 9163 9164 // Create PHIs for all of the select pseudo-instructions. 9165 auto SelectMBBI = MI.getIterator(); 9166 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9167 auto InsertionPoint = TailMBB->begin(); 9168 while (SelectMBBI != SelectEnd) { 9169 auto Next = std::next(SelectMBBI); 9170 if (isSelectPseudo(*SelectMBBI)) { 9171 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9172 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9173 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9174 .addReg(SelectMBBI->getOperand(4).getReg()) 9175 .addMBB(HeadMBB) 9176 .addReg(SelectMBBI->getOperand(5).getReg()) 9177 .addMBB(IfFalseMBB); 9178 SelectMBBI->eraseFromParent(); 9179 } 9180 SelectMBBI = Next; 9181 } 9182 9183 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9184 return TailMBB; 9185 } 9186 9187 MachineBasicBlock * 9188 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9189 MachineBasicBlock *BB) const { 9190 switch (MI.getOpcode()) { 9191 default: 9192 llvm_unreachable("Unexpected instr type to insert"); 9193 case RISCV::ReadCycleWide: 9194 assert(!Subtarget.is64Bit() && 9195 "ReadCycleWrite is only to be used on riscv32"); 9196 return emitReadCycleWidePseudo(MI, BB); 9197 case RISCV::Select_GPR_Using_CC_GPR: 9198 case RISCV::Select_FPR16_Using_CC_GPR: 9199 case RISCV::Select_FPR32_Using_CC_GPR: 9200 case RISCV::Select_FPR64_Using_CC_GPR: 9201 return emitSelectPseudo(MI, BB, Subtarget); 9202 case RISCV::BuildPairF64Pseudo: 9203 return emitBuildPairF64Pseudo(MI, BB); 9204 case RISCV::SplitF64Pseudo: 9205 return emitSplitF64Pseudo(MI, BB); 9206 case RISCV::PseudoQuietFLE_H: 9207 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9208 case RISCV::PseudoQuietFLT_H: 9209 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9210 case RISCV::PseudoQuietFLE_S: 9211 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9212 case RISCV::PseudoQuietFLT_S: 9213 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9214 case RISCV::PseudoQuietFLE_D: 9215 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9216 case RISCV::PseudoQuietFLT_D: 9217 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9218 } 9219 } 9220 9221 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9222 SDNode *Node) const { 9223 // Add FRM dependency to any instructions with dynamic rounding mode. 9224 unsigned Opc = MI.getOpcode(); 9225 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9226 if (Idx < 0) 9227 return; 9228 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9229 return; 9230 // If the instruction already reads FRM, don't add another read. 9231 if (MI.readsRegister(RISCV::FRM)) 9232 return; 9233 MI.addOperand( 9234 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9235 } 9236 9237 // Calling Convention Implementation. 9238 // The expectations for frontend ABI lowering vary from target to target. 9239 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9240 // details, but this is a longer term goal. For now, we simply try to keep the 9241 // role of the frontend as simple and well-defined as possible. The rules can 9242 // be summarised as: 9243 // * Never split up large scalar arguments. We handle them here. 9244 // * If a hardfloat calling convention is being used, and the struct may be 9245 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9246 // available, then pass as two separate arguments. If either the GPRs or FPRs 9247 // are exhausted, then pass according to the rule below. 9248 // * If a struct could never be passed in registers or directly in a stack 9249 // slot (as it is larger than 2*XLEN and the floating point rules don't 9250 // apply), then pass it using a pointer with the byval attribute. 9251 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9252 // word-sized array or a 2*XLEN scalar (depending on alignment). 9253 // * The frontend can determine whether a struct is returned by reference or 9254 // not based on its size and fields. If it will be returned by reference, the 9255 // frontend must modify the prototype so a pointer with the sret annotation is 9256 // passed as the first argument. This is not necessary for large scalar 9257 // returns. 9258 // * Struct return values and varargs should be coerced to structs containing 9259 // register-size fields in the same situations they would be for fixed 9260 // arguments. 9261 9262 static const MCPhysReg ArgGPRs[] = { 9263 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9264 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9265 }; 9266 static const MCPhysReg ArgFPR16s[] = { 9267 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9268 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9269 }; 9270 static const MCPhysReg ArgFPR32s[] = { 9271 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9272 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9273 }; 9274 static const MCPhysReg ArgFPR64s[] = { 9275 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9276 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9277 }; 9278 // This is an interim calling convention and it may be changed in the future. 9279 static const MCPhysReg ArgVRs[] = { 9280 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9281 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9282 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9283 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9284 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9285 RISCV::V20M2, RISCV::V22M2}; 9286 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9287 RISCV::V20M4}; 9288 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9289 9290 // Pass a 2*XLEN argument that has been split into two XLEN values through 9291 // registers or the stack as necessary. 9292 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9293 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9294 MVT ValVT2, MVT LocVT2, 9295 ISD::ArgFlagsTy ArgFlags2) { 9296 unsigned XLenInBytes = XLen / 8; 9297 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9298 // At least one half can be passed via register. 9299 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9300 VA1.getLocVT(), CCValAssign::Full)); 9301 } else { 9302 // Both halves must be passed on the stack, with proper alignment. 9303 Align StackAlign = 9304 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9305 State.addLoc( 9306 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9307 State.AllocateStack(XLenInBytes, StackAlign), 9308 VA1.getLocVT(), CCValAssign::Full)); 9309 State.addLoc(CCValAssign::getMem( 9310 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9311 LocVT2, CCValAssign::Full)); 9312 return false; 9313 } 9314 9315 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9316 // The second half can also be passed via register. 9317 State.addLoc( 9318 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9319 } else { 9320 // The second half is passed via the stack, without additional alignment. 9321 State.addLoc(CCValAssign::getMem( 9322 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9323 LocVT2, CCValAssign::Full)); 9324 } 9325 9326 return false; 9327 } 9328 9329 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9330 Optional<unsigned> FirstMaskArgument, 9331 CCState &State, const RISCVTargetLowering &TLI) { 9332 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9333 if (RC == &RISCV::VRRegClass) { 9334 // Assign the first mask argument to V0. 9335 // This is an interim calling convention and it may be changed in the 9336 // future. 9337 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9338 return State.AllocateReg(RISCV::V0); 9339 return State.AllocateReg(ArgVRs); 9340 } 9341 if (RC == &RISCV::VRM2RegClass) 9342 return State.AllocateReg(ArgVRM2s); 9343 if (RC == &RISCV::VRM4RegClass) 9344 return State.AllocateReg(ArgVRM4s); 9345 if (RC == &RISCV::VRM8RegClass) 9346 return State.AllocateReg(ArgVRM8s); 9347 llvm_unreachable("Unhandled register class for ValueType"); 9348 } 9349 9350 // Implements the RISC-V calling convention. Returns true upon failure. 9351 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9352 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9353 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9354 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9355 Optional<unsigned> FirstMaskArgument) { 9356 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9357 assert(XLen == 32 || XLen == 64); 9358 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9359 9360 // Any return value split in to more than two values can't be returned 9361 // directly. Vectors are returned via the available vector registers. 9362 if (!LocVT.isVector() && IsRet && ValNo > 1) 9363 return true; 9364 9365 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9366 // variadic argument, or if no F16/F32 argument registers are available. 9367 bool UseGPRForF16_F32 = true; 9368 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9369 // variadic argument, or if no F64 argument registers are available. 9370 bool UseGPRForF64 = true; 9371 9372 switch (ABI) { 9373 default: 9374 llvm_unreachable("Unexpected ABI"); 9375 case RISCVABI::ABI_ILP32: 9376 case RISCVABI::ABI_LP64: 9377 break; 9378 case RISCVABI::ABI_ILP32F: 9379 case RISCVABI::ABI_LP64F: 9380 UseGPRForF16_F32 = !IsFixed; 9381 break; 9382 case RISCVABI::ABI_ILP32D: 9383 case RISCVABI::ABI_LP64D: 9384 UseGPRForF16_F32 = !IsFixed; 9385 UseGPRForF64 = !IsFixed; 9386 break; 9387 } 9388 9389 // FPR16, FPR32, and FPR64 alias each other. 9390 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9391 UseGPRForF16_F32 = true; 9392 UseGPRForF64 = true; 9393 } 9394 9395 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9396 // similar local variables rather than directly checking against the target 9397 // ABI. 9398 9399 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9400 LocVT = XLenVT; 9401 LocInfo = CCValAssign::BCvt; 9402 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9403 LocVT = MVT::i64; 9404 LocInfo = CCValAssign::BCvt; 9405 } 9406 9407 // If this is a variadic argument, the RISC-V calling convention requires 9408 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9409 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9410 // be used regardless of whether the original argument was split during 9411 // legalisation or not. The argument will not be passed by registers if the 9412 // original type is larger than 2*XLEN, so the register alignment rule does 9413 // not apply. 9414 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9415 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9416 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9417 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9418 // Skip 'odd' register if necessary. 9419 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9420 State.AllocateReg(ArgGPRs); 9421 } 9422 9423 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9424 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9425 State.getPendingArgFlags(); 9426 9427 assert(PendingLocs.size() == PendingArgFlags.size() && 9428 "PendingLocs and PendingArgFlags out of sync"); 9429 9430 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9431 // registers are exhausted. 9432 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9433 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9434 "Can't lower f64 if it is split"); 9435 // Depending on available argument GPRS, f64 may be passed in a pair of 9436 // GPRs, split between a GPR and the stack, or passed completely on the 9437 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9438 // cases. 9439 Register Reg = State.AllocateReg(ArgGPRs); 9440 LocVT = MVT::i32; 9441 if (!Reg) { 9442 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9443 State.addLoc( 9444 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9445 return false; 9446 } 9447 if (!State.AllocateReg(ArgGPRs)) 9448 State.AllocateStack(4, Align(4)); 9449 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9450 return false; 9451 } 9452 9453 // Fixed-length vectors are located in the corresponding scalable-vector 9454 // container types. 9455 if (ValVT.isFixedLengthVector()) 9456 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9457 9458 // Split arguments might be passed indirectly, so keep track of the pending 9459 // values. Split vectors are passed via a mix of registers and indirectly, so 9460 // treat them as we would any other argument. 9461 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9462 LocVT = XLenVT; 9463 LocInfo = CCValAssign::Indirect; 9464 PendingLocs.push_back( 9465 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9466 PendingArgFlags.push_back(ArgFlags); 9467 if (!ArgFlags.isSplitEnd()) { 9468 return false; 9469 } 9470 } 9471 9472 // If the split argument only had two elements, it should be passed directly 9473 // in registers or on the stack. 9474 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9475 PendingLocs.size() <= 2) { 9476 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9477 // Apply the normal calling convention rules to the first half of the 9478 // split argument. 9479 CCValAssign VA = PendingLocs[0]; 9480 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9481 PendingLocs.clear(); 9482 PendingArgFlags.clear(); 9483 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9484 ArgFlags); 9485 } 9486 9487 // Allocate to a register if possible, or else a stack slot. 9488 Register Reg; 9489 unsigned StoreSizeBytes = XLen / 8; 9490 Align StackAlign = Align(XLen / 8); 9491 9492 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9493 Reg = State.AllocateReg(ArgFPR16s); 9494 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9495 Reg = State.AllocateReg(ArgFPR32s); 9496 else if (ValVT == MVT::f64 && !UseGPRForF64) 9497 Reg = State.AllocateReg(ArgFPR64s); 9498 else if (ValVT.isVector()) { 9499 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9500 if (!Reg) { 9501 // For return values, the vector must be passed fully via registers or 9502 // via the stack. 9503 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9504 // but we're using all of them. 9505 if (IsRet) 9506 return true; 9507 // Try using a GPR to pass the address 9508 if ((Reg = State.AllocateReg(ArgGPRs))) { 9509 LocVT = XLenVT; 9510 LocInfo = CCValAssign::Indirect; 9511 } else if (ValVT.isScalableVector()) { 9512 LocVT = XLenVT; 9513 LocInfo = CCValAssign::Indirect; 9514 } else { 9515 // Pass fixed-length vectors on the stack. 9516 LocVT = ValVT; 9517 StoreSizeBytes = ValVT.getStoreSize(); 9518 // Align vectors to their element sizes, being careful for vXi1 9519 // vectors. 9520 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9521 } 9522 } 9523 } else { 9524 Reg = State.AllocateReg(ArgGPRs); 9525 } 9526 9527 unsigned StackOffset = 9528 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9529 9530 // If we reach this point and PendingLocs is non-empty, we must be at the 9531 // end of a split argument that must be passed indirectly. 9532 if (!PendingLocs.empty()) { 9533 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9534 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9535 9536 for (auto &It : PendingLocs) { 9537 if (Reg) 9538 It.convertToReg(Reg); 9539 else 9540 It.convertToMem(StackOffset); 9541 State.addLoc(It); 9542 } 9543 PendingLocs.clear(); 9544 PendingArgFlags.clear(); 9545 return false; 9546 } 9547 9548 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9549 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9550 "Expected an XLenVT or vector types at this stage"); 9551 9552 if (Reg) { 9553 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9554 return false; 9555 } 9556 9557 // When a floating-point value is passed on the stack, no bit-conversion is 9558 // needed. 9559 if (ValVT.isFloatingPoint()) { 9560 LocVT = ValVT; 9561 LocInfo = CCValAssign::Full; 9562 } 9563 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9564 return false; 9565 } 9566 9567 template <typename ArgTy> 9568 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9569 for (const auto &ArgIdx : enumerate(Args)) { 9570 MVT ArgVT = ArgIdx.value().VT; 9571 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9572 return ArgIdx.index(); 9573 } 9574 return None; 9575 } 9576 9577 void RISCVTargetLowering::analyzeInputArgs( 9578 MachineFunction &MF, CCState &CCInfo, 9579 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9580 RISCVCCAssignFn Fn) const { 9581 unsigned NumArgs = Ins.size(); 9582 FunctionType *FType = MF.getFunction().getFunctionType(); 9583 9584 Optional<unsigned> FirstMaskArgument; 9585 if (Subtarget.hasVInstructions()) 9586 FirstMaskArgument = preAssignMask(Ins); 9587 9588 for (unsigned i = 0; i != NumArgs; ++i) { 9589 MVT ArgVT = Ins[i].VT; 9590 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9591 9592 Type *ArgTy = nullptr; 9593 if (IsRet) 9594 ArgTy = FType->getReturnType(); 9595 else if (Ins[i].isOrigArg()) 9596 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9597 9598 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9599 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9600 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9601 FirstMaskArgument)) { 9602 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9603 << EVT(ArgVT).getEVTString() << '\n'); 9604 llvm_unreachable(nullptr); 9605 } 9606 } 9607 } 9608 9609 void RISCVTargetLowering::analyzeOutputArgs( 9610 MachineFunction &MF, CCState &CCInfo, 9611 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9612 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9613 unsigned NumArgs = Outs.size(); 9614 9615 Optional<unsigned> FirstMaskArgument; 9616 if (Subtarget.hasVInstructions()) 9617 FirstMaskArgument = preAssignMask(Outs); 9618 9619 for (unsigned i = 0; i != NumArgs; i++) { 9620 MVT ArgVT = Outs[i].VT; 9621 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9622 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9623 9624 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9625 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9626 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9627 FirstMaskArgument)) { 9628 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9629 << EVT(ArgVT).getEVTString() << "\n"); 9630 llvm_unreachable(nullptr); 9631 } 9632 } 9633 } 9634 9635 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9636 // values. 9637 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9638 const CCValAssign &VA, const SDLoc &DL, 9639 const RISCVSubtarget &Subtarget) { 9640 switch (VA.getLocInfo()) { 9641 default: 9642 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9643 case CCValAssign::Full: 9644 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9645 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9646 break; 9647 case CCValAssign::BCvt: 9648 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9649 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9650 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9651 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9652 else 9653 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9654 break; 9655 } 9656 return Val; 9657 } 9658 9659 // The caller is responsible for loading the full value if the argument is 9660 // passed with CCValAssign::Indirect. 9661 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9662 const CCValAssign &VA, const SDLoc &DL, 9663 const RISCVTargetLowering &TLI) { 9664 MachineFunction &MF = DAG.getMachineFunction(); 9665 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9666 EVT LocVT = VA.getLocVT(); 9667 SDValue Val; 9668 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9669 Register VReg = RegInfo.createVirtualRegister(RC); 9670 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9671 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9672 9673 if (VA.getLocInfo() == CCValAssign::Indirect) 9674 return Val; 9675 9676 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9677 } 9678 9679 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9680 const CCValAssign &VA, const SDLoc &DL, 9681 const RISCVSubtarget &Subtarget) { 9682 EVT LocVT = VA.getLocVT(); 9683 9684 switch (VA.getLocInfo()) { 9685 default: 9686 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9687 case CCValAssign::Full: 9688 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9689 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9690 break; 9691 case CCValAssign::BCvt: 9692 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9693 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9694 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9695 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9696 else 9697 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9698 break; 9699 } 9700 return Val; 9701 } 9702 9703 // The caller is responsible for loading the full value if the argument is 9704 // passed with CCValAssign::Indirect. 9705 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9706 const CCValAssign &VA, const SDLoc &DL) { 9707 MachineFunction &MF = DAG.getMachineFunction(); 9708 MachineFrameInfo &MFI = MF.getFrameInfo(); 9709 EVT LocVT = VA.getLocVT(); 9710 EVT ValVT = VA.getValVT(); 9711 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9712 if (ValVT.isScalableVector()) { 9713 // When the value is a scalable vector, we save the pointer which points to 9714 // the scalable vector value in the stack. The ValVT will be the pointer 9715 // type, instead of the scalable vector type. 9716 ValVT = LocVT; 9717 } 9718 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9719 /*IsImmutable=*/true); 9720 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9721 SDValue Val; 9722 9723 ISD::LoadExtType ExtType; 9724 switch (VA.getLocInfo()) { 9725 default: 9726 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9727 case CCValAssign::Full: 9728 case CCValAssign::Indirect: 9729 case CCValAssign::BCvt: 9730 ExtType = ISD::NON_EXTLOAD; 9731 break; 9732 } 9733 Val = DAG.getExtLoad( 9734 ExtType, DL, LocVT, Chain, FIN, 9735 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9736 return Val; 9737 } 9738 9739 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9740 const CCValAssign &VA, const SDLoc &DL) { 9741 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9742 "Unexpected VA"); 9743 MachineFunction &MF = DAG.getMachineFunction(); 9744 MachineFrameInfo &MFI = MF.getFrameInfo(); 9745 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9746 9747 if (VA.isMemLoc()) { 9748 // f64 is passed on the stack. 9749 int FI = 9750 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9751 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9752 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9753 MachinePointerInfo::getFixedStack(MF, FI)); 9754 } 9755 9756 assert(VA.isRegLoc() && "Expected register VA assignment"); 9757 9758 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9759 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9760 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9761 SDValue Hi; 9762 if (VA.getLocReg() == RISCV::X17) { 9763 // Second half of f64 is passed on the stack. 9764 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9765 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9766 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9767 MachinePointerInfo::getFixedStack(MF, FI)); 9768 } else { 9769 // Second half of f64 is passed in another GPR. 9770 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9771 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9772 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9773 } 9774 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9775 } 9776 9777 // FastCC has less than 1% performance improvement for some particular 9778 // benchmark. But theoretically, it may has benenfit for some cases. 9779 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9780 unsigned ValNo, MVT ValVT, MVT LocVT, 9781 CCValAssign::LocInfo LocInfo, 9782 ISD::ArgFlagsTy ArgFlags, CCState &State, 9783 bool IsFixed, bool IsRet, Type *OrigTy, 9784 const RISCVTargetLowering &TLI, 9785 Optional<unsigned> FirstMaskArgument) { 9786 9787 // X5 and X6 might be used for save-restore libcall. 9788 static const MCPhysReg GPRList[] = { 9789 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9790 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9791 RISCV::X29, RISCV::X30, RISCV::X31}; 9792 9793 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9794 if (unsigned Reg = State.AllocateReg(GPRList)) { 9795 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9796 return false; 9797 } 9798 } 9799 9800 if (LocVT == MVT::f16) { 9801 static const MCPhysReg FPR16List[] = { 9802 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9803 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9804 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9805 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9806 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9807 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9808 return false; 9809 } 9810 } 9811 9812 if (LocVT == MVT::f32) { 9813 static const MCPhysReg FPR32List[] = { 9814 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9815 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9816 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9817 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9818 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9819 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9820 return false; 9821 } 9822 } 9823 9824 if (LocVT == MVT::f64) { 9825 static const MCPhysReg FPR64List[] = { 9826 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9827 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9828 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9829 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9830 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9831 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9832 return false; 9833 } 9834 } 9835 9836 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9837 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9838 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9839 return false; 9840 } 9841 9842 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9843 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9844 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9845 return false; 9846 } 9847 9848 if (LocVT.isVector()) { 9849 if (unsigned Reg = 9850 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9851 // Fixed-length vectors are located in the corresponding scalable-vector 9852 // container types. 9853 if (ValVT.isFixedLengthVector()) 9854 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9855 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9856 } else { 9857 // Try and pass the address via a "fast" GPR. 9858 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9859 LocInfo = CCValAssign::Indirect; 9860 LocVT = TLI.getSubtarget().getXLenVT(); 9861 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9862 } else if (ValVT.isFixedLengthVector()) { 9863 auto StackAlign = 9864 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9865 unsigned StackOffset = 9866 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9867 State.addLoc( 9868 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9869 } else { 9870 // Can't pass scalable vectors on the stack. 9871 return true; 9872 } 9873 } 9874 9875 return false; 9876 } 9877 9878 return true; // CC didn't match. 9879 } 9880 9881 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9882 CCValAssign::LocInfo LocInfo, 9883 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9884 9885 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9886 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9887 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9888 static const MCPhysReg GPRList[] = { 9889 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9890 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9891 if (unsigned Reg = State.AllocateReg(GPRList)) { 9892 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9893 return false; 9894 } 9895 } 9896 9897 if (LocVT == MVT::f32) { 9898 // Pass in STG registers: F1, ..., F6 9899 // fs0 ... fs5 9900 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9901 RISCV::F18_F, RISCV::F19_F, 9902 RISCV::F20_F, RISCV::F21_F}; 9903 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9904 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9905 return false; 9906 } 9907 } 9908 9909 if (LocVT == MVT::f64) { 9910 // Pass in STG registers: D1, ..., D6 9911 // fs6 ... fs11 9912 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9913 RISCV::F24_D, RISCV::F25_D, 9914 RISCV::F26_D, RISCV::F27_D}; 9915 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9916 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9917 return false; 9918 } 9919 } 9920 9921 report_fatal_error("No registers left in GHC calling convention"); 9922 return true; 9923 } 9924 9925 // Transform physical registers into virtual registers. 9926 SDValue RISCVTargetLowering::LowerFormalArguments( 9927 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9928 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9929 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9930 9931 MachineFunction &MF = DAG.getMachineFunction(); 9932 9933 switch (CallConv) { 9934 default: 9935 report_fatal_error("Unsupported calling convention"); 9936 case CallingConv::C: 9937 case CallingConv::Fast: 9938 break; 9939 case CallingConv::GHC: 9940 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9941 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9942 report_fatal_error( 9943 "GHC calling convention requires the F and D instruction set extensions"); 9944 } 9945 9946 const Function &Func = MF.getFunction(); 9947 if (Func.hasFnAttribute("interrupt")) { 9948 if (!Func.arg_empty()) 9949 report_fatal_error( 9950 "Functions with the interrupt attribute cannot have arguments!"); 9951 9952 StringRef Kind = 9953 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9954 9955 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9956 report_fatal_error( 9957 "Function interrupt attribute argument not supported!"); 9958 } 9959 9960 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9961 MVT XLenVT = Subtarget.getXLenVT(); 9962 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9963 // Used with vargs to acumulate store chains. 9964 std::vector<SDValue> OutChains; 9965 9966 // Assign locations to all of the incoming arguments. 9967 SmallVector<CCValAssign, 16> ArgLocs; 9968 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9969 9970 if (CallConv == CallingConv::GHC) 9971 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9972 else 9973 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9974 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9975 : CC_RISCV); 9976 9977 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9978 CCValAssign &VA = ArgLocs[i]; 9979 SDValue ArgValue; 9980 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9981 // case. 9982 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9983 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9984 else if (VA.isRegLoc()) 9985 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9986 else 9987 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9988 9989 if (VA.getLocInfo() == CCValAssign::Indirect) { 9990 // If the original argument was split and passed by reference (e.g. i128 9991 // on RV32), we need to load all parts of it here (using the same 9992 // address). Vectors may be partly split to registers and partly to the 9993 // stack, in which case the base address is partly offset and subsequent 9994 // stores are relative to that. 9995 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9996 MachinePointerInfo())); 9997 unsigned ArgIndex = Ins[i].OrigArgIndex; 9998 unsigned ArgPartOffset = Ins[i].PartOffset; 9999 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10000 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10001 CCValAssign &PartVA = ArgLocs[i + 1]; 10002 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10003 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10004 if (PartVA.getValVT().isScalableVector()) 10005 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10006 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10007 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10008 MachinePointerInfo())); 10009 ++i; 10010 } 10011 continue; 10012 } 10013 InVals.push_back(ArgValue); 10014 } 10015 10016 if (IsVarArg) { 10017 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10018 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10019 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10020 MachineFrameInfo &MFI = MF.getFrameInfo(); 10021 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10022 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10023 10024 // Offset of the first variable argument from stack pointer, and size of 10025 // the vararg save area. For now, the varargs save area is either zero or 10026 // large enough to hold a0-a7. 10027 int VaArgOffset, VarArgsSaveSize; 10028 10029 // If all registers are allocated, then all varargs must be passed on the 10030 // stack and we don't need to save any argregs. 10031 if (ArgRegs.size() == Idx) { 10032 VaArgOffset = CCInfo.getNextStackOffset(); 10033 VarArgsSaveSize = 0; 10034 } else { 10035 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10036 VaArgOffset = -VarArgsSaveSize; 10037 } 10038 10039 // Record the frame index of the first variable argument 10040 // which is a value necessary to VASTART. 10041 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10042 RVFI->setVarArgsFrameIndex(FI); 10043 10044 // If saving an odd number of registers then create an extra stack slot to 10045 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10046 // offsets to even-numbered registered remain 2*XLEN-aligned. 10047 if (Idx % 2) { 10048 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10049 VarArgsSaveSize += XLenInBytes; 10050 } 10051 10052 // Copy the integer registers that may have been used for passing varargs 10053 // to the vararg save area. 10054 for (unsigned I = Idx; I < ArgRegs.size(); 10055 ++I, VaArgOffset += XLenInBytes) { 10056 const Register Reg = RegInfo.createVirtualRegister(RC); 10057 RegInfo.addLiveIn(ArgRegs[I], Reg); 10058 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10059 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10060 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10061 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10062 MachinePointerInfo::getFixedStack(MF, FI)); 10063 cast<StoreSDNode>(Store.getNode()) 10064 ->getMemOperand() 10065 ->setValue((Value *)nullptr); 10066 OutChains.push_back(Store); 10067 } 10068 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10069 } 10070 10071 // All stores are grouped in one node to allow the matching between 10072 // the size of Ins and InVals. This only happens for vararg functions. 10073 if (!OutChains.empty()) { 10074 OutChains.push_back(Chain); 10075 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10076 } 10077 10078 return Chain; 10079 } 10080 10081 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10082 /// for tail call optimization. 10083 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10084 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10085 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10086 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10087 10088 auto &Callee = CLI.Callee; 10089 auto CalleeCC = CLI.CallConv; 10090 auto &Outs = CLI.Outs; 10091 auto &Caller = MF.getFunction(); 10092 auto CallerCC = Caller.getCallingConv(); 10093 10094 // Exception-handling functions need a special set of instructions to 10095 // indicate a return to the hardware. Tail-calling another function would 10096 // probably break this. 10097 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10098 // should be expanded as new function attributes are introduced. 10099 if (Caller.hasFnAttribute("interrupt")) 10100 return false; 10101 10102 // Do not tail call opt if the stack is used to pass parameters. 10103 if (CCInfo.getNextStackOffset() != 0) 10104 return false; 10105 10106 // Do not tail call opt if any parameters need to be passed indirectly. 10107 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10108 // passed indirectly. So the address of the value will be passed in a 10109 // register, or if not available, then the address is put on the stack. In 10110 // order to pass indirectly, space on the stack often needs to be allocated 10111 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10112 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10113 // are passed CCValAssign::Indirect. 10114 for (auto &VA : ArgLocs) 10115 if (VA.getLocInfo() == CCValAssign::Indirect) 10116 return false; 10117 10118 // Do not tail call opt if either caller or callee uses struct return 10119 // semantics. 10120 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10121 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10122 if (IsCallerStructRet || IsCalleeStructRet) 10123 return false; 10124 10125 // Externally-defined functions with weak linkage should not be 10126 // tail-called. The behaviour of branch instructions in this situation (as 10127 // used for tail calls) is implementation-defined, so we cannot rely on the 10128 // linker replacing the tail call with a return. 10129 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10130 const GlobalValue *GV = G->getGlobal(); 10131 if (GV->hasExternalWeakLinkage()) 10132 return false; 10133 } 10134 10135 // The callee has to preserve all registers the caller needs to preserve. 10136 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10137 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10138 if (CalleeCC != CallerCC) { 10139 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10140 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10141 return false; 10142 } 10143 10144 // Byval parameters hand the function a pointer directly into the stack area 10145 // we want to reuse during a tail call. Working around this *is* possible 10146 // but less efficient and uglier in LowerCall. 10147 for (auto &Arg : Outs) 10148 if (Arg.Flags.isByVal()) 10149 return false; 10150 10151 return true; 10152 } 10153 10154 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10155 return DAG.getDataLayout().getPrefTypeAlign( 10156 VT.getTypeForEVT(*DAG.getContext())); 10157 } 10158 10159 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10160 // and output parameter nodes. 10161 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10162 SmallVectorImpl<SDValue> &InVals) const { 10163 SelectionDAG &DAG = CLI.DAG; 10164 SDLoc &DL = CLI.DL; 10165 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10166 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10167 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10168 SDValue Chain = CLI.Chain; 10169 SDValue Callee = CLI.Callee; 10170 bool &IsTailCall = CLI.IsTailCall; 10171 CallingConv::ID CallConv = CLI.CallConv; 10172 bool IsVarArg = CLI.IsVarArg; 10173 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10174 MVT XLenVT = Subtarget.getXLenVT(); 10175 10176 MachineFunction &MF = DAG.getMachineFunction(); 10177 10178 // Analyze the operands of the call, assigning locations to each operand. 10179 SmallVector<CCValAssign, 16> ArgLocs; 10180 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10181 10182 if (CallConv == CallingConv::GHC) 10183 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10184 else 10185 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10186 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10187 : CC_RISCV); 10188 10189 // Check if it's really possible to do a tail call. 10190 if (IsTailCall) 10191 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10192 10193 if (IsTailCall) 10194 ++NumTailCalls; 10195 else if (CLI.CB && CLI.CB->isMustTailCall()) 10196 report_fatal_error("failed to perform tail call elimination on a call " 10197 "site marked musttail"); 10198 10199 // Get a count of how many bytes are to be pushed on the stack. 10200 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10201 10202 // Create local copies for byval args 10203 SmallVector<SDValue, 8> ByValArgs; 10204 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10205 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10206 if (!Flags.isByVal()) 10207 continue; 10208 10209 SDValue Arg = OutVals[i]; 10210 unsigned Size = Flags.getByValSize(); 10211 Align Alignment = Flags.getNonZeroByValAlign(); 10212 10213 int FI = 10214 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10215 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10216 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10217 10218 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10219 /*IsVolatile=*/false, 10220 /*AlwaysInline=*/false, IsTailCall, 10221 MachinePointerInfo(), MachinePointerInfo()); 10222 ByValArgs.push_back(FIPtr); 10223 } 10224 10225 if (!IsTailCall) 10226 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10227 10228 // Copy argument values to their designated locations. 10229 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10230 SmallVector<SDValue, 8> MemOpChains; 10231 SDValue StackPtr; 10232 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10233 CCValAssign &VA = ArgLocs[i]; 10234 SDValue ArgValue = OutVals[i]; 10235 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10236 10237 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10238 bool IsF64OnRV32DSoftABI = 10239 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10240 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10241 SDValue SplitF64 = DAG.getNode( 10242 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10243 SDValue Lo = SplitF64.getValue(0); 10244 SDValue Hi = SplitF64.getValue(1); 10245 10246 Register RegLo = VA.getLocReg(); 10247 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10248 10249 if (RegLo == RISCV::X17) { 10250 // Second half of f64 is passed on the stack. 10251 // Work out the address of the stack slot. 10252 if (!StackPtr.getNode()) 10253 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10254 // Emit the store. 10255 MemOpChains.push_back( 10256 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10257 } else { 10258 // Second half of f64 is passed in another GPR. 10259 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10260 Register RegHigh = RegLo + 1; 10261 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10262 } 10263 continue; 10264 } 10265 10266 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10267 // as any other MemLoc. 10268 10269 // Promote the value if needed. 10270 // For now, only handle fully promoted and indirect arguments. 10271 if (VA.getLocInfo() == CCValAssign::Indirect) { 10272 // Store the argument in a stack slot and pass its address. 10273 Align StackAlign = 10274 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10275 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10276 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10277 // If the original argument was split (e.g. i128), we need 10278 // to store the required parts of it here (and pass just one address). 10279 // Vectors may be partly split to registers and partly to the stack, in 10280 // which case the base address is partly offset and subsequent stores are 10281 // relative to that. 10282 unsigned ArgIndex = Outs[i].OrigArgIndex; 10283 unsigned ArgPartOffset = Outs[i].PartOffset; 10284 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10285 // Calculate the total size to store. We don't have access to what we're 10286 // actually storing other than performing the loop and collecting the 10287 // info. 10288 SmallVector<std::pair<SDValue, SDValue>> Parts; 10289 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10290 SDValue PartValue = OutVals[i + 1]; 10291 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10292 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10293 EVT PartVT = PartValue.getValueType(); 10294 if (PartVT.isScalableVector()) 10295 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10296 StoredSize += PartVT.getStoreSize(); 10297 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10298 Parts.push_back(std::make_pair(PartValue, Offset)); 10299 ++i; 10300 } 10301 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10302 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10303 MemOpChains.push_back( 10304 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10305 MachinePointerInfo::getFixedStack(MF, FI))); 10306 for (const auto &Part : Parts) { 10307 SDValue PartValue = Part.first; 10308 SDValue PartOffset = Part.second; 10309 SDValue Address = 10310 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10311 MemOpChains.push_back( 10312 DAG.getStore(Chain, DL, PartValue, Address, 10313 MachinePointerInfo::getFixedStack(MF, FI))); 10314 } 10315 ArgValue = SpillSlot; 10316 } else { 10317 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10318 } 10319 10320 // Use local copy if it is a byval arg. 10321 if (Flags.isByVal()) 10322 ArgValue = ByValArgs[j++]; 10323 10324 if (VA.isRegLoc()) { 10325 // Queue up the argument copies and emit them at the end. 10326 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10327 } else { 10328 assert(VA.isMemLoc() && "Argument not register or memory"); 10329 assert(!IsTailCall && "Tail call not allowed if stack is used " 10330 "for passing parameters"); 10331 10332 // Work out the address of the stack slot. 10333 if (!StackPtr.getNode()) 10334 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10335 SDValue Address = 10336 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10337 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10338 10339 // Emit the store. 10340 MemOpChains.push_back( 10341 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10342 } 10343 } 10344 10345 // Join the stores, which are independent of one another. 10346 if (!MemOpChains.empty()) 10347 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10348 10349 SDValue Glue; 10350 10351 // Build a sequence of copy-to-reg nodes, chained and glued together. 10352 for (auto &Reg : RegsToPass) { 10353 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10354 Glue = Chain.getValue(1); 10355 } 10356 10357 // Validate that none of the argument registers have been marked as 10358 // reserved, if so report an error. Do the same for the return address if this 10359 // is not a tailcall. 10360 validateCCReservedRegs(RegsToPass, MF); 10361 if (!IsTailCall && 10362 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10363 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10364 MF.getFunction(), 10365 "Return address register required, but has been reserved."}); 10366 10367 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10368 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10369 // split it and then direct call can be matched by PseudoCALL. 10370 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10371 const GlobalValue *GV = S->getGlobal(); 10372 10373 unsigned OpFlags = RISCVII::MO_CALL; 10374 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10375 OpFlags = RISCVII::MO_PLT; 10376 10377 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10378 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10379 unsigned OpFlags = RISCVII::MO_CALL; 10380 10381 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10382 nullptr)) 10383 OpFlags = RISCVII::MO_PLT; 10384 10385 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10386 } 10387 10388 // The first call operand is the chain and the second is the target address. 10389 SmallVector<SDValue, 8> Ops; 10390 Ops.push_back(Chain); 10391 Ops.push_back(Callee); 10392 10393 // Add argument registers to the end of the list so that they are 10394 // known live into the call. 10395 for (auto &Reg : RegsToPass) 10396 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10397 10398 if (!IsTailCall) { 10399 // Add a register mask operand representing the call-preserved registers. 10400 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10401 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10402 assert(Mask && "Missing call preserved mask for calling convention"); 10403 Ops.push_back(DAG.getRegisterMask(Mask)); 10404 } 10405 10406 // Glue the call to the argument copies, if any. 10407 if (Glue.getNode()) 10408 Ops.push_back(Glue); 10409 10410 // Emit the call. 10411 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10412 10413 if (IsTailCall) { 10414 MF.getFrameInfo().setHasTailCall(); 10415 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10416 } 10417 10418 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10419 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10420 Glue = Chain.getValue(1); 10421 10422 // Mark the end of the call, which is glued to the call itself. 10423 Chain = DAG.getCALLSEQ_END(Chain, 10424 DAG.getConstant(NumBytes, DL, PtrVT, true), 10425 DAG.getConstant(0, DL, PtrVT, true), 10426 Glue, DL); 10427 Glue = Chain.getValue(1); 10428 10429 // Assign locations to each value returned by this call. 10430 SmallVector<CCValAssign, 16> RVLocs; 10431 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10432 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10433 10434 // Copy all of the result registers out of their specified physreg. 10435 for (auto &VA : RVLocs) { 10436 // Copy the value out 10437 SDValue RetValue = 10438 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10439 // Glue the RetValue to the end of the call sequence 10440 Chain = RetValue.getValue(1); 10441 Glue = RetValue.getValue(2); 10442 10443 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10444 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10445 SDValue RetValue2 = 10446 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10447 Chain = RetValue2.getValue(1); 10448 Glue = RetValue2.getValue(2); 10449 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10450 RetValue2); 10451 } 10452 10453 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10454 10455 InVals.push_back(RetValue); 10456 } 10457 10458 return Chain; 10459 } 10460 10461 bool RISCVTargetLowering::CanLowerReturn( 10462 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10463 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10464 SmallVector<CCValAssign, 16> RVLocs; 10465 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10466 10467 Optional<unsigned> FirstMaskArgument; 10468 if (Subtarget.hasVInstructions()) 10469 FirstMaskArgument = preAssignMask(Outs); 10470 10471 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10472 MVT VT = Outs[i].VT; 10473 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10474 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10475 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10476 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10477 *this, FirstMaskArgument)) 10478 return false; 10479 } 10480 return true; 10481 } 10482 10483 SDValue 10484 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10485 bool IsVarArg, 10486 const SmallVectorImpl<ISD::OutputArg> &Outs, 10487 const SmallVectorImpl<SDValue> &OutVals, 10488 const SDLoc &DL, SelectionDAG &DAG) const { 10489 const MachineFunction &MF = DAG.getMachineFunction(); 10490 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10491 10492 // Stores the assignment of the return value to a location. 10493 SmallVector<CCValAssign, 16> RVLocs; 10494 10495 // Info about the registers and stack slot. 10496 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10497 *DAG.getContext()); 10498 10499 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10500 nullptr, CC_RISCV); 10501 10502 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10503 report_fatal_error("GHC functions return void only"); 10504 10505 SDValue Glue; 10506 SmallVector<SDValue, 4> RetOps(1, Chain); 10507 10508 // Copy the result values into the output registers. 10509 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10510 SDValue Val = OutVals[i]; 10511 CCValAssign &VA = RVLocs[i]; 10512 assert(VA.isRegLoc() && "Can only return in registers!"); 10513 10514 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10515 // Handle returning f64 on RV32D with a soft float ABI. 10516 assert(VA.isRegLoc() && "Expected return via registers"); 10517 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10518 DAG.getVTList(MVT::i32, MVT::i32), Val); 10519 SDValue Lo = SplitF64.getValue(0); 10520 SDValue Hi = SplitF64.getValue(1); 10521 Register RegLo = VA.getLocReg(); 10522 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10523 Register RegHi = RegLo + 1; 10524 10525 if (STI.isRegisterReservedByUser(RegLo) || 10526 STI.isRegisterReservedByUser(RegHi)) 10527 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10528 MF.getFunction(), 10529 "Return value register required, but has been reserved."}); 10530 10531 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10532 Glue = Chain.getValue(1); 10533 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10534 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10535 Glue = Chain.getValue(1); 10536 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10537 } else { 10538 // Handle a 'normal' return. 10539 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10540 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10541 10542 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10543 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10544 MF.getFunction(), 10545 "Return value register required, but has been reserved."}); 10546 10547 // Guarantee that all emitted copies are stuck together. 10548 Glue = Chain.getValue(1); 10549 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10550 } 10551 } 10552 10553 RetOps[0] = Chain; // Update chain. 10554 10555 // Add the glue node if we have it. 10556 if (Glue.getNode()) { 10557 RetOps.push_back(Glue); 10558 } 10559 10560 unsigned RetOpc = RISCVISD::RET_FLAG; 10561 // Interrupt service routines use different return instructions. 10562 const Function &Func = DAG.getMachineFunction().getFunction(); 10563 if (Func.hasFnAttribute("interrupt")) { 10564 if (!Func.getReturnType()->isVoidTy()) 10565 report_fatal_error( 10566 "Functions with the interrupt attribute must have void return type!"); 10567 10568 MachineFunction &MF = DAG.getMachineFunction(); 10569 StringRef Kind = 10570 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10571 10572 if (Kind == "user") 10573 RetOpc = RISCVISD::URET_FLAG; 10574 else if (Kind == "supervisor") 10575 RetOpc = RISCVISD::SRET_FLAG; 10576 else 10577 RetOpc = RISCVISD::MRET_FLAG; 10578 } 10579 10580 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10581 } 10582 10583 void RISCVTargetLowering::validateCCReservedRegs( 10584 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10585 MachineFunction &MF) const { 10586 const Function &F = MF.getFunction(); 10587 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10588 10589 if (llvm::any_of(Regs, [&STI](auto Reg) { 10590 return STI.isRegisterReservedByUser(Reg.first); 10591 })) 10592 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10593 F, "Argument register required, but has been reserved."}); 10594 } 10595 10596 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10597 return CI->isTailCall(); 10598 } 10599 10600 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10601 #define NODE_NAME_CASE(NODE) \ 10602 case RISCVISD::NODE: \ 10603 return "RISCVISD::" #NODE; 10604 // clang-format off 10605 switch ((RISCVISD::NodeType)Opcode) { 10606 case RISCVISD::FIRST_NUMBER: 10607 break; 10608 NODE_NAME_CASE(RET_FLAG) 10609 NODE_NAME_CASE(URET_FLAG) 10610 NODE_NAME_CASE(SRET_FLAG) 10611 NODE_NAME_CASE(MRET_FLAG) 10612 NODE_NAME_CASE(CALL) 10613 NODE_NAME_CASE(SELECT_CC) 10614 NODE_NAME_CASE(BR_CC) 10615 NODE_NAME_CASE(BuildPairF64) 10616 NODE_NAME_CASE(SplitF64) 10617 NODE_NAME_CASE(TAIL) 10618 NODE_NAME_CASE(MULHSU) 10619 NODE_NAME_CASE(SLLW) 10620 NODE_NAME_CASE(SRAW) 10621 NODE_NAME_CASE(SRLW) 10622 NODE_NAME_CASE(DIVW) 10623 NODE_NAME_CASE(DIVUW) 10624 NODE_NAME_CASE(REMUW) 10625 NODE_NAME_CASE(ROLW) 10626 NODE_NAME_CASE(RORW) 10627 NODE_NAME_CASE(CLZW) 10628 NODE_NAME_CASE(CTZW) 10629 NODE_NAME_CASE(FSLW) 10630 NODE_NAME_CASE(FSRW) 10631 NODE_NAME_CASE(FSL) 10632 NODE_NAME_CASE(FSR) 10633 NODE_NAME_CASE(FMV_H_X) 10634 NODE_NAME_CASE(FMV_X_ANYEXTH) 10635 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10636 NODE_NAME_CASE(FMV_W_X_RV64) 10637 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10638 NODE_NAME_CASE(FCVT_X) 10639 NODE_NAME_CASE(FCVT_XU) 10640 NODE_NAME_CASE(FCVT_W_RV64) 10641 NODE_NAME_CASE(FCVT_WU_RV64) 10642 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10643 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10644 NODE_NAME_CASE(READ_CYCLE_WIDE) 10645 NODE_NAME_CASE(GREV) 10646 NODE_NAME_CASE(GREVW) 10647 NODE_NAME_CASE(GORC) 10648 NODE_NAME_CASE(GORCW) 10649 NODE_NAME_CASE(SHFL) 10650 NODE_NAME_CASE(SHFLW) 10651 NODE_NAME_CASE(UNSHFL) 10652 NODE_NAME_CASE(UNSHFLW) 10653 NODE_NAME_CASE(BFP) 10654 NODE_NAME_CASE(BFPW) 10655 NODE_NAME_CASE(BCOMPRESS) 10656 NODE_NAME_CASE(BCOMPRESSW) 10657 NODE_NAME_CASE(BDECOMPRESS) 10658 NODE_NAME_CASE(BDECOMPRESSW) 10659 NODE_NAME_CASE(VMV_V_X_VL) 10660 NODE_NAME_CASE(VFMV_V_F_VL) 10661 NODE_NAME_CASE(VMV_X_S) 10662 NODE_NAME_CASE(VMV_S_X_VL) 10663 NODE_NAME_CASE(VFMV_S_F_VL) 10664 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10665 NODE_NAME_CASE(READ_VLENB) 10666 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10667 NODE_NAME_CASE(VSLIDEUP_VL) 10668 NODE_NAME_CASE(VSLIDE1UP_VL) 10669 NODE_NAME_CASE(VSLIDEDOWN_VL) 10670 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10671 NODE_NAME_CASE(VID_VL) 10672 NODE_NAME_CASE(VFNCVT_ROD_VL) 10673 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10674 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10675 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10676 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10677 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10678 NODE_NAME_CASE(VECREDUCE_AND_VL) 10679 NODE_NAME_CASE(VECREDUCE_OR_VL) 10680 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10681 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10682 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10683 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10684 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10685 NODE_NAME_CASE(ADD_VL) 10686 NODE_NAME_CASE(AND_VL) 10687 NODE_NAME_CASE(MUL_VL) 10688 NODE_NAME_CASE(OR_VL) 10689 NODE_NAME_CASE(SDIV_VL) 10690 NODE_NAME_CASE(SHL_VL) 10691 NODE_NAME_CASE(SREM_VL) 10692 NODE_NAME_CASE(SRA_VL) 10693 NODE_NAME_CASE(SRL_VL) 10694 NODE_NAME_CASE(SUB_VL) 10695 NODE_NAME_CASE(UDIV_VL) 10696 NODE_NAME_CASE(UREM_VL) 10697 NODE_NAME_CASE(XOR_VL) 10698 NODE_NAME_CASE(SADDSAT_VL) 10699 NODE_NAME_CASE(UADDSAT_VL) 10700 NODE_NAME_CASE(SSUBSAT_VL) 10701 NODE_NAME_CASE(USUBSAT_VL) 10702 NODE_NAME_CASE(FADD_VL) 10703 NODE_NAME_CASE(FSUB_VL) 10704 NODE_NAME_CASE(FMUL_VL) 10705 NODE_NAME_CASE(FDIV_VL) 10706 NODE_NAME_CASE(FNEG_VL) 10707 NODE_NAME_CASE(FABS_VL) 10708 NODE_NAME_CASE(FSQRT_VL) 10709 NODE_NAME_CASE(FMA_VL) 10710 NODE_NAME_CASE(FCOPYSIGN_VL) 10711 NODE_NAME_CASE(SMIN_VL) 10712 NODE_NAME_CASE(SMAX_VL) 10713 NODE_NAME_CASE(UMIN_VL) 10714 NODE_NAME_CASE(UMAX_VL) 10715 NODE_NAME_CASE(FMINNUM_VL) 10716 NODE_NAME_CASE(FMAXNUM_VL) 10717 NODE_NAME_CASE(MULHS_VL) 10718 NODE_NAME_CASE(MULHU_VL) 10719 NODE_NAME_CASE(FP_TO_SINT_VL) 10720 NODE_NAME_CASE(FP_TO_UINT_VL) 10721 NODE_NAME_CASE(SINT_TO_FP_VL) 10722 NODE_NAME_CASE(UINT_TO_FP_VL) 10723 NODE_NAME_CASE(FP_EXTEND_VL) 10724 NODE_NAME_CASE(FP_ROUND_VL) 10725 NODE_NAME_CASE(VWMUL_VL) 10726 NODE_NAME_CASE(VWMULU_VL) 10727 NODE_NAME_CASE(VWMULSU_VL) 10728 NODE_NAME_CASE(VWADD_VL) 10729 NODE_NAME_CASE(VWADDU_VL) 10730 NODE_NAME_CASE(VWSUB_VL) 10731 NODE_NAME_CASE(VWSUBU_VL) 10732 NODE_NAME_CASE(VWADD_W_VL) 10733 NODE_NAME_CASE(VWADDU_W_VL) 10734 NODE_NAME_CASE(VWSUB_W_VL) 10735 NODE_NAME_CASE(VWSUBU_W_VL) 10736 NODE_NAME_CASE(SETCC_VL) 10737 NODE_NAME_CASE(VSELECT_VL) 10738 NODE_NAME_CASE(VP_MERGE_VL) 10739 NODE_NAME_CASE(VMAND_VL) 10740 NODE_NAME_CASE(VMOR_VL) 10741 NODE_NAME_CASE(VMXOR_VL) 10742 NODE_NAME_CASE(VMCLR_VL) 10743 NODE_NAME_CASE(VMSET_VL) 10744 NODE_NAME_CASE(VRGATHER_VX_VL) 10745 NODE_NAME_CASE(VRGATHER_VV_VL) 10746 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10747 NODE_NAME_CASE(VSEXT_VL) 10748 NODE_NAME_CASE(VZEXT_VL) 10749 NODE_NAME_CASE(VCPOP_VL) 10750 NODE_NAME_CASE(VLE_VL) 10751 NODE_NAME_CASE(VSE_VL) 10752 NODE_NAME_CASE(READ_CSR) 10753 NODE_NAME_CASE(WRITE_CSR) 10754 NODE_NAME_CASE(SWAP_CSR) 10755 } 10756 // clang-format on 10757 return nullptr; 10758 #undef NODE_NAME_CASE 10759 } 10760 10761 /// getConstraintType - Given a constraint letter, return the type of 10762 /// constraint it is for this target. 10763 RISCVTargetLowering::ConstraintType 10764 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10765 if (Constraint.size() == 1) { 10766 switch (Constraint[0]) { 10767 default: 10768 break; 10769 case 'f': 10770 return C_RegisterClass; 10771 case 'I': 10772 case 'J': 10773 case 'K': 10774 return C_Immediate; 10775 case 'A': 10776 return C_Memory; 10777 case 'S': // A symbolic address 10778 return C_Other; 10779 } 10780 } else { 10781 if (Constraint == "vr" || Constraint == "vm") 10782 return C_RegisterClass; 10783 } 10784 return TargetLowering::getConstraintType(Constraint); 10785 } 10786 10787 std::pair<unsigned, const TargetRegisterClass *> 10788 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10789 StringRef Constraint, 10790 MVT VT) const { 10791 // First, see if this is a constraint that directly corresponds to a 10792 // RISCV register class. 10793 if (Constraint.size() == 1) { 10794 switch (Constraint[0]) { 10795 case 'r': 10796 // TODO: Support fixed vectors up to XLen for P extension? 10797 if (VT.isVector()) 10798 break; 10799 return std::make_pair(0U, &RISCV::GPRRegClass); 10800 case 'f': 10801 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10802 return std::make_pair(0U, &RISCV::FPR16RegClass); 10803 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10804 return std::make_pair(0U, &RISCV::FPR32RegClass); 10805 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10806 return std::make_pair(0U, &RISCV::FPR64RegClass); 10807 break; 10808 default: 10809 break; 10810 } 10811 } else if (Constraint == "vr") { 10812 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10813 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10814 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10815 return std::make_pair(0U, RC); 10816 } 10817 } else if (Constraint == "vm") { 10818 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10819 return std::make_pair(0U, &RISCV::VMV0RegClass); 10820 } 10821 10822 // Clang will correctly decode the usage of register name aliases into their 10823 // official names. However, other frontends like `rustc` do not. This allows 10824 // users of these frontends to use the ABI names for registers in LLVM-style 10825 // register constraints. 10826 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10827 .Case("{zero}", RISCV::X0) 10828 .Case("{ra}", RISCV::X1) 10829 .Case("{sp}", RISCV::X2) 10830 .Case("{gp}", RISCV::X3) 10831 .Case("{tp}", RISCV::X4) 10832 .Case("{t0}", RISCV::X5) 10833 .Case("{t1}", RISCV::X6) 10834 .Case("{t2}", RISCV::X7) 10835 .Cases("{s0}", "{fp}", RISCV::X8) 10836 .Case("{s1}", RISCV::X9) 10837 .Case("{a0}", RISCV::X10) 10838 .Case("{a1}", RISCV::X11) 10839 .Case("{a2}", RISCV::X12) 10840 .Case("{a3}", RISCV::X13) 10841 .Case("{a4}", RISCV::X14) 10842 .Case("{a5}", RISCV::X15) 10843 .Case("{a6}", RISCV::X16) 10844 .Case("{a7}", RISCV::X17) 10845 .Case("{s2}", RISCV::X18) 10846 .Case("{s3}", RISCV::X19) 10847 .Case("{s4}", RISCV::X20) 10848 .Case("{s5}", RISCV::X21) 10849 .Case("{s6}", RISCV::X22) 10850 .Case("{s7}", RISCV::X23) 10851 .Case("{s8}", RISCV::X24) 10852 .Case("{s9}", RISCV::X25) 10853 .Case("{s10}", RISCV::X26) 10854 .Case("{s11}", RISCV::X27) 10855 .Case("{t3}", RISCV::X28) 10856 .Case("{t4}", RISCV::X29) 10857 .Case("{t5}", RISCV::X30) 10858 .Case("{t6}", RISCV::X31) 10859 .Default(RISCV::NoRegister); 10860 if (XRegFromAlias != RISCV::NoRegister) 10861 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10862 10863 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10864 // TableGen record rather than the AsmName to choose registers for InlineAsm 10865 // constraints, plus we want to match those names to the widest floating point 10866 // register type available, manually select floating point registers here. 10867 // 10868 // The second case is the ABI name of the register, so that frontends can also 10869 // use the ABI names in register constraint lists. 10870 if (Subtarget.hasStdExtF()) { 10871 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10872 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10873 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10874 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10875 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10876 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10877 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10878 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10879 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10880 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10881 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10882 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10883 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10884 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10885 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10886 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10887 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10888 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10889 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10890 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10891 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10892 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10893 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10894 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10895 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10896 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10897 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10898 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10899 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10900 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10901 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10902 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10903 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10904 .Default(RISCV::NoRegister); 10905 if (FReg != RISCV::NoRegister) { 10906 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10907 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10908 unsigned RegNo = FReg - RISCV::F0_F; 10909 unsigned DReg = RISCV::F0_D + RegNo; 10910 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10911 } 10912 if (VT == MVT::f32 || VT == MVT::Other) 10913 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10914 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10915 unsigned RegNo = FReg - RISCV::F0_F; 10916 unsigned HReg = RISCV::F0_H + RegNo; 10917 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10918 } 10919 } 10920 } 10921 10922 if (Subtarget.hasVInstructions()) { 10923 Register VReg = StringSwitch<Register>(Constraint.lower()) 10924 .Case("{v0}", RISCV::V0) 10925 .Case("{v1}", RISCV::V1) 10926 .Case("{v2}", RISCV::V2) 10927 .Case("{v3}", RISCV::V3) 10928 .Case("{v4}", RISCV::V4) 10929 .Case("{v5}", RISCV::V5) 10930 .Case("{v6}", RISCV::V6) 10931 .Case("{v7}", RISCV::V7) 10932 .Case("{v8}", RISCV::V8) 10933 .Case("{v9}", RISCV::V9) 10934 .Case("{v10}", RISCV::V10) 10935 .Case("{v11}", RISCV::V11) 10936 .Case("{v12}", RISCV::V12) 10937 .Case("{v13}", RISCV::V13) 10938 .Case("{v14}", RISCV::V14) 10939 .Case("{v15}", RISCV::V15) 10940 .Case("{v16}", RISCV::V16) 10941 .Case("{v17}", RISCV::V17) 10942 .Case("{v18}", RISCV::V18) 10943 .Case("{v19}", RISCV::V19) 10944 .Case("{v20}", RISCV::V20) 10945 .Case("{v21}", RISCV::V21) 10946 .Case("{v22}", RISCV::V22) 10947 .Case("{v23}", RISCV::V23) 10948 .Case("{v24}", RISCV::V24) 10949 .Case("{v25}", RISCV::V25) 10950 .Case("{v26}", RISCV::V26) 10951 .Case("{v27}", RISCV::V27) 10952 .Case("{v28}", RISCV::V28) 10953 .Case("{v29}", RISCV::V29) 10954 .Case("{v30}", RISCV::V30) 10955 .Case("{v31}", RISCV::V31) 10956 .Default(RISCV::NoRegister); 10957 if (VReg != RISCV::NoRegister) { 10958 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10959 return std::make_pair(VReg, &RISCV::VMRegClass); 10960 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10961 return std::make_pair(VReg, &RISCV::VRRegClass); 10962 for (const auto *RC : 10963 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10964 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10965 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10966 return std::make_pair(VReg, RC); 10967 } 10968 } 10969 } 10970 } 10971 10972 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10973 } 10974 10975 unsigned 10976 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10977 // Currently only support length 1 constraints. 10978 if (ConstraintCode.size() == 1) { 10979 switch (ConstraintCode[0]) { 10980 case 'A': 10981 return InlineAsm::Constraint_A; 10982 default: 10983 break; 10984 } 10985 } 10986 10987 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10988 } 10989 10990 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10991 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10992 SelectionDAG &DAG) const { 10993 // Currently only support length 1 constraints. 10994 if (Constraint.length() == 1) { 10995 switch (Constraint[0]) { 10996 case 'I': 10997 // Validate & create a 12-bit signed immediate operand. 10998 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10999 uint64_t CVal = C->getSExtValue(); 11000 if (isInt<12>(CVal)) 11001 Ops.push_back( 11002 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11003 } 11004 return; 11005 case 'J': 11006 // Validate & create an integer zero operand. 11007 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11008 if (C->getZExtValue() == 0) 11009 Ops.push_back( 11010 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11011 return; 11012 case 'K': 11013 // Validate & create a 5-bit unsigned immediate operand. 11014 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11015 uint64_t CVal = C->getZExtValue(); 11016 if (isUInt<5>(CVal)) 11017 Ops.push_back( 11018 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11019 } 11020 return; 11021 case 'S': 11022 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11023 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11024 GA->getValueType(0))); 11025 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11026 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11027 BA->getValueType(0))); 11028 } 11029 return; 11030 default: 11031 break; 11032 } 11033 } 11034 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11035 } 11036 11037 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11038 Instruction *Inst, 11039 AtomicOrdering Ord) const { 11040 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11041 return Builder.CreateFence(Ord); 11042 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11043 return Builder.CreateFence(AtomicOrdering::Release); 11044 return nullptr; 11045 } 11046 11047 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11048 Instruction *Inst, 11049 AtomicOrdering Ord) const { 11050 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11051 return Builder.CreateFence(AtomicOrdering::Acquire); 11052 return nullptr; 11053 } 11054 11055 TargetLowering::AtomicExpansionKind 11056 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11057 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11058 // point operations can't be used in an lr/sc sequence without breaking the 11059 // forward-progress guarantee. 11060 if (AI->isFloatingPointOperation()) 11061 return AtomicExpansionKind::CmpXChg; 11062 11063 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11064 if (Size == 8 || Size == 16) 11065 return AtomicExpansionKind::MaskedIntrinsic; 11066 return AtomicExpansionKind::None; 11067 } 11068 11069 static Intrinsic::ID 11070 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11071 if (XLen == 32) { 11072 switch (BinOp) { 11073 default: 11074 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11075 case AtomicRMWInst::Xchg: 11076 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11077 case AtomicRMWInst::Add: 11078 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11079 case AtomicRMWInst::Sub: 11080 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11081 case AtomicRMWInst::Nand: 11082 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11083 case AtomicRMWInst::Max: 11084 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11085 case AtomicRMWInst::Min: 11086 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11087 case AtomicRMWInst::UMax: 11088 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11089 case AtomicRMWInst::UMin: 11090 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11091 } 11092 } 11093 11094 if (XLen == 64) { 11095 switch (BinOp) { 11096 default: 11097 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11098 case AtomicRMWInst::Xchg: 11099 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11100 case AtomicRMWInst::Add: 11101 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11102 case AtomicRMWInst::Sub: 11103 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11104 case AtomicRMWInst::Nand: 11105 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11106 case AtomicRMWInst::Max: 11107 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11108 case AtomicRMWInst::Min: 11109 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11110 case AtomicRMWInst::UMax: 11111 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11112 case AtomicRMWInst::UMin: 11113 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11114 } 11115 } 11116 11117 llvm_unreachable("Unexpected XLen\n"); 11118 } 11119 11120 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11121 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11122 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11123 unsigned XLen = Subtarget.getXLen(); 11124 Value *Ordering = 11125 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11126 Type *Tys[] = {AlignedAddr->getType()}; 11127 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11128 AI->getModule(), 11129 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11130 11131 if (XLen == 64) { 11132 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11133 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11134 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11135 } 11136 11137 Value *Result; 11138 11139 // Must pass the shift amount needed to sign extend the loaded value prior 11140 // to performing a signed comparison for min/max. ShiftAmt is the number of 11141 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11142 // is the number of bits to left+right shift the value in order to 11143 // sign-extend. 11144 if (AI->getOperation() == AtomicRMWInst::Min || 11145 AI->getOperation() == AtomicRMWInst::Max) { 11146 const DataLayout &DL = AI->getModule()->getDataLayout(); 11147 unsigned ValWidth = 11148 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11149 Value *SextShamt = 11150 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11151 Result = Builder.CreateCall(LrwOpScwLoop, 11152 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11153 } else { 11154 Result = 11155 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11156 } 11157 11158 if (XLen == 64) 11159 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11160 return Result; 11161 } 11162 11163 TargetLowering::AtomicExpansionKind 11164 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11165 AtomicCmpXchgInst *CI) const { 11166 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11167 if (Size == 8 || Size == 16) 11168 return AtomicExpansionKind::MaskedIntrinsic; 11169 return AtomicExpansionKind::None; 11170 } 11171 11172 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11173 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11174 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11175 unsigned XLen = Subtarget.getXLen(); 11176 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11177 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11178 if (XLen == 64) { 11179 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11180 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11181 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11182 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11183 } 11184 Type *Tys[] = {AlignedAddr->getType()}; 11185 Function *MaskedCmpXchg = 11186 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11187 Value *Result = Builder.CreateCall( 11188 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11189 if (XLen == 64) 11190 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11191 return Result; 11192 } 11193 11194 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11195 return false; 11196 } 11197 11198 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11199 EVT VT) const { 11200 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11201 return false; 11202 11203 switch (FPVT.getSimpleVT().SimpleTy) { 11204 case MVT::f16: 11205 return Subtarget.hasStdExtZfh(); 11206 case MVT::f32: 11207 return Subtarget.hasStdExtF(); 11208 case MVT::f64: 11209 return Subtarget.hasStdExtD(); 11210 default: 11211 return false; 11212 } 11213 } 11214 11215 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11216 // If we are using the small code model, we can reduce size of jump table 11217 // entry to 4 bytes. 11218 if (Subtarget.is64Bit() && !isPositionIndependent() && 11219 getTargetMachine().getCodeModel() == CodeModel::Small) { 11220 return MachineJumpTableInfo::EK_Custom32; 11221 } 11222 return TargetLowering::getJumpTableEncoding(); 11223 } 11224 11225 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11226 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11227 unsigned uid, MCContext &Ctx) const { 11228 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11229 getTargetMachine().getCodeModel() == CodeModel::Small); 11230 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11231 } 11232 11233 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11234 EVT VT) const { 11235 VT = VT.getScalarType(); 11236 11237 if (!VT.isSimple()) 11238 return false; 11239 11240 switch (VT.getSimpleVT().SimpleTy) { 11241 case MVT::f16: 11242 return Subtarget.hasStdExtZfh(); 11243 case MVT::f32: 11244 return Subtarget.hasStdExtF(); 11245 case MVT::f64: 11246 return Subtarget.hasStdExtD(); 11247 default: 11248 break; 11249 } 11250 11251 return false; 11252 } 11253 11254 Register RISCVTargetLowering::getExceptionPointerRegister( 11255 const Constant *PersonalityFn) const { 11256 return RISCV::X10; 11257 } 11258 11259 Register RISCVTargetLowering::getExceptionSelectorRegister( 11260 const Constant *PersonalityFn) const { 11261 return RISCV::X11; 11262 } 11263 11264 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11265 // Return false to suppress the unnecessary extensions if the LibCall 11266 // arguments or return value is f32 type for LP64 ABI. 11267 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11268 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11269 return false; 11270 11271 return true; 11272 } 11273 11274 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11275 if (Subtarget.is64Bit() && Type == MVT::i32) 11276 return true; 11277 11278 return IsSigned; 11279 } 11280 11281 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11282 SDValue C) const { 11283 // Check integral scalar types. 11284 if (VT.isScalarInteger()) { 11285 // Omit the optimization if the sub target has the M extension and the data 11286 // size exceeds XLen. 11287 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11288 return false; 11289 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11290 // Break the MUL to a SLLI and an ADD/SUB. 11291 const APInt &Imm = ConstNode->getAPIntValue(); 11292 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11293 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11294 return true; 11295 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11296 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11297 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11298 (Imm - 8).isPowerOf2())) 11299 return true; 11300 // Omit the following optimization if the sub target has the M extension 11301 // and the data size >= XLen. 11302 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11303 return false; 11304 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11305 // a pair of LUI/ADDI. 11306 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11307 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11308 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11309 (1 - ImmS).isPowerOf2()) 11310 return true; 11311 } 11312 } 11313 } 11314 11315 return false; 11316 } 11317 11318 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11319 SDValue ConstNode) const { 11320 // Let the DAGCombiner decide for vectors. 11321 EVT VT = AddNode.getValueType(); 11322 if (VT.isVector()) 11323 return true; 11324 11325 // Let the DAGCombiner decide for larger types. 11326 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11327 return true; 11328 11329 // It is worse if c1 is simm12 while c1*c2 is not. 11330 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11331 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11332 const APInt &C1 = C1Node->getAPIntValue(); 11333 const APInt &C2 = C2Node->getAPIntValue(); 11334 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11335 return false; 11336 11337 // Default to true and let the DAGCombiner decide. 11338 return true; 11339 } 11340 11341 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11342 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11343 bool *Fast) const { 11344 if (!VT.isVector()) 11345 return false; 11346 11347 EVT ElemVT = VT.getVectorElementType(); 11348 if (Alignment >= ElemVT.getStoreSize()) { 11349 if (Fast) 11350 *Fast = true; 11351 return true; 11352 } 11353 11354 return false; 11355 } 11356 11357 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11358 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11359 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11360 bool IsABIRegCopy = CC.hasValue(); 11361 EVT ValueVT = Val.getValueType(); 11362 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11363 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11364 // and cast to f32. 11365 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11366 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11367 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11368 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11369 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11370 Parts[0] = Val; 11371 return true; 11372 } 11373 11374 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11375 LLVMContext &Context = *DAG.getContext(); 11376 EVT ValueEltVT = ValueVT.getVectorElementType(); 11377 EVT PartEltVT = PartVT.getVectorElementType(); 11378 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11379 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11380 if (PartVTBitSize % ValueVTBitSize == 0) { 11381 assert(PartVTBitSize >= ValueVTBitSize); 11382 // If the element types are different, bitcast to the same element type of 11383 // PartVT first. 11384 // Give an example here, we want copy a <vscale x 1 x i8> value to 11385 // <vscale x 4 x i16>. 11386 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11387 // subvector, then we can bitcast to <vscale x 4 x i16>. 11388 if (ValueEltVT != PartEltVT) { 11389 if (PartVTBitSize > ValueVTBitSize) { 11390 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11391 assert(Count != 0 && "The number of element should not be zero."); 11392 EVT SameEltTypeVT = 11393 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11394 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11395 DAG.getUNDEF(SameEltTypeVT), Val, 11396 DAG.getVectorIdxConstant(0, DL)); 11397 } 11398 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11399 } else { 11400 Val = 11401 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11402 Val, DAG.getVectorIdxConstant(0, DL)); 11403 } 11404 Parts[0] = Val; 11405 return true; 11406 } 11407 } 11408 return false; 11409 } 11410 11411 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11412 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11413 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11414 bool IsABIRegCopy = CC.hasValue(); 11415 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11416 SDValue Val = Parts[0]; 11417 11418 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11419 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11420 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11421 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11422 return Val; 11423 } 11424 11425 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11426 LLVMContext &Context = *DAG.getContext(); 11427 SDValue Val = Parts[0]; 11428 EVT ValueEltVT = ValueVT.getVectorElementType(); 11429 EVT PartEltVT = PartVT.getVectorElementType(); 11430 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11431 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11432 if (PartVTBitSize % ValueVTBitSize == 0) { 11433 assert(PartVTBitSize >= ValueVTBitSize); 11434 EVT SameEltTypeVT = ValueVT; 11435 // If the element types are different, convert it to the same element type 11436 // of PartVT. 11437 // Give an example here, we want copy a <vscale x 1 x i8> value from 11438 // <vscale x 4 x i16>. 11439 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11440 // then we can extract <vscale x 1 x i8>. 11441 if (ValueEltVT != PartEltVT) { 11442 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11443 assert(Count != 0 && "The number of element should not be zero."); 11444 SameEltTypeVT = 11445 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11446 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11447 } 11448 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11449 DAG.getVectorIdxConstant(0, DL)); 11450 return Val; 11451 } 11452 } 11453 return SDValue(); 11454 } 11455 11456 SDValue 11457 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11458 SelectionDAG &DAG, 11459 SmallVectorImpl<SDNode *> &Created) const { 11460 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11461 if (isIntDivCheap(N->getValueType(0), Attr)) 11462 return SDValue(N, 0); // Lower SDIV as SDIV 11463 11464 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11465 "Unexpected divisor!"); 11466 11467 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11468 if (!Subtarget.hasStdExtZbt()) 11469 return SDValue(); 11470 11471 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11472 // Besides, more critical path instructions will be generated when dividing 11473 // by 2. So we keep using the original DAGs for these cases. 11474 unsigned Lg2 = Divisor.countTrailingZeros(); 11475 if (Lg2 == 1 || Lg2 >= 12) 11476 return SDValue(); 11477 11478 // fold (sdiv X, pow2) 11479 EVT VT = N->getValueType(0); 11480 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11481 return SDValue(); 11482 11483 SDLoc DL(N); 11484 SDValue N0 = N->getOperand(0); 11485 SDValue Zero = DAG.getConstant(0, DL, VT); 11486 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11487 11488 // Add (N0 < 0) ? Pow2 - 1 : 0; 11489 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11490 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11491 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11492 11493 Created.push_back(Cmp.getNode()); 11494 Created.push_back(Add.getNode()); 11495 Created.push_back(Sel.getNode()); 11496 11497 // Divide by pow2. 11498 SDValue SRA = 11499 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11500 11501 // If we're dividing by a positive value, we're done. Otherwise, we must 11502 // negate the result. 11503 if (Divisor.isNonNegative()) 11504 return SRA; 11505 11506 Created.push_back(SRA.getNode()); 11507 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11508 } 11509 11510 #define GET_REGISTER_MATCHER 11511 #include "RISCVGenAsmMatcher.inc" 11512 11513 Register 11514 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11515 const MachineFunction &MF) const { 11516 Register Reg = MatchRegisterAltName(RegName); 11517 if (Reg == RISCV::NoRegister) 11518 Reg = MatchRegisterName(RegName); 11519 if (Reg == RISCV::NoRegister) 11520 report_fatal_error( 11521 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11522 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11523 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11524 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11525 StringRef(RegName) + "\".")); 11526 return Reg; 11527 } 11528 11529 namespace llvm { 11530 namespace RISCVVIntrinsicsTable { 11531 11532 #define GET_RISCVVIntrinsicsTable_IMPL 11533 #include "RISCVGenSearchableTables.inc" 11534 11535 } // namespace RISCVVIntrinsicsTable 11536 11537 } // namespace llvm 11538