1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 307 if (Subtarget.is64Bit()) 308 setOperationAction(ISD::ABS, MVT::i32, Custom); 309 } 310 311 if (Subtarget.hasStdExtZbt()) { 312 setOperationAction(ISD::FSHL, XLenVT, Custom); 313 setOperationAction(ISD::FSHR, XLenVT, Custom); 314 setOperationAction(ISD::SELECT, XLenVT, Legal); 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FSHL, MVT::i32, Custom); 318 setOperationAction(ISD::FSHR, MVT::i32, Custom); 319 } 320 } else { 321 setOperationAction(ISD::SELECT, XLenVT, Custom); 322 } 323 324 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 325 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 326 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 327 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 328 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 329 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 330 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 331 332 static const ISD::CondCode FPCCToExpand[] = { 333 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 334 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 335 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 336 337 static const ISD::NodeType FPOpToExpand[] = { 338 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 339 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 340 341 if (Subtarget.hasStdExtZfh()) 342 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 343 344 if (Subtarget.hasStdExtZfh()) { 345 for (auto NT : FPLegalNodeTypes) 346 setOperationAction(NT, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 352 setOperationAction(ISD::SELECT, MVT::f16, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 354 355 setOperationAction(ISD::FREM, MVT::f16, Promote); 356 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 357 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 358 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 359 setOperationAction(ISD::FRINT, MVT::f16, Promote); 360 setOperationAction(ISD::FROUND, MVT::f16, Promote); 361 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 362 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 363 setOperationAction(ISD::FPOW, MVT::f16, Promote); 364 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 365 setOperationAction(ISD::FCOS, MVT::f16, Promote); 366 setOperationAction(ISD::FSIN, MVT::f16, Promote); 367 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP, MVT::f16, Promote); 369 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 373 374 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 375 // complete support for all operations in LegalizeDAG. 376 377 // We need to custom promote this. 378 if (Subtarget.is64Bit()) 379 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 380 } 381 382 if (Subtarget.hasStdExtF()) { 383 for (auto NT : FPLegalNodeTypes) 384 setOperationAction(NT, MVT::f32, Legal); 385 for (auto CC : FPCCToExpand) 386 setCondCodeAction(CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 388 setOperationAction(ISD::SELECT, MVT::f32, Custom); 389 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 390 for (auto Op : FPOpToExpand) 391 setOperationAction(Op, MVT::f32, Expand); 392 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 393 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 394 } 395 396 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 397 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtD()) { 400 for (auto NT : FPLegalNodeTypes) 401 setOperationAction(NT, MVT::f64, Legal); 402 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 404 for (auto CC : FPCCToExpand) 405 setCondCodeAction(CC, MVT::f64, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Custom); 408 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 409 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 410 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f64, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 415 } 416 417 if (Subtarget.is64Bit()) { 418 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 419 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 420 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 421 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 422 } 423 424 if (Subtarget.hasStdExtF()) { 425 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 426 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 427 428 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 429 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 430 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 431 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 432 433 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 434 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 435 } 436 437 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 438 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 439 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 440 setOperationAction(ISD::JumpTable, XLenVT, Custom); 441 442 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 443 444 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 445 // Unfortunately this can't be determined just from the ISA naming string. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 447 Subtarget.is64Bit() ? Legal : Custom); 448 449 setOperationAction(ISD::TRAP, MVT::Other, Legal); 450 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 451 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 452 if (Subtarget.is64Bit()) 453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 454 455 if (Subtarget.hasStdExtA()) { 456 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 457 setMinCmpXchgSizeInBits(32); 458 } else { 459 setMaxAtomicSizeInBitsSupported(0); 460 } 461 462 setBooleanContents(ZeroOrOneBooleanContent); 463 464 if (Subtarget.hasVInstructions()) { 465 setBooleanVectorContents(ZeroOrOneBooleanContent); 466 467 setOperationAction(ISD::VSCALE, XLenVT, Custom); 468 469 // RVV intrinsics may have illegal operands. 470 // We also need to custom legalize vmv.x.s. 471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 475 if (Subtarget.is64Bit()) { 476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 477 } else { 478 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 480 } 481 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 static const unsigned IntegerVPOps[] = { 486 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 487 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 488 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 489 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 490 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 491 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 492 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 493 ISD::VP_MERGE, ISD::VP_SELECT}; 494 495 static const unsigned FloatingPointVPOps[] = { 496 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 497 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FMA, 498 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN, 499 ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, ISD::VP_SELECT}; 500 501 if (!Subtarget.is64Bit()) { 502 // We must custom-lower certain vXi64 operations on RV32 due to the vector 503 // element type being illegal. 504 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 505 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 506 507 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 508 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 509 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 510 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 511 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 512 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 513 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 514 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 515 516 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 517 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 518 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 519 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 520 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 521 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 522 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 523 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 524 } 525 526 for (MVT VT : BoolVecVTs) { 527 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 528 529 // Mask VTs are custom-expanded into a series of standard nodes 530 setOperationAction(ISD::TRUNCATE, VT, Custom); 531 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 532 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 533 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 534 535 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 536 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 537 538 setOperationAction(ISD::SELECT, VT, Custom); 539 setOperationAction(ISD::SELECT_CC, VT, Expand); 540 setOperationAction(ISD::VSELECT, VT, Expand); 541 setOperationAction(ISD::VP_MERGE, VT, Expand); 542 setOperationAction(ISD::VP_SELECT, VT, Expand); 543 544 setOperationAction(ISD::VP_AND, VT, Custom); 545 setOperationAction(ISD::VP_OR, VT, Custom); 546 setOperationAction(ISD::VP_XOR, VT, Custom); 547 548 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 549 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 550 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 551 552 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 553 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 554 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 555 556 // RVV has native int->float & float->int conversions where the 557 // element type sizes are within one power-of-two of each other. Any 558 // wider distances between type sizes have to be lowered as sequences 559 // which progressively narrow the gap in stages. 560 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 561 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 562 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 563 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 564 565 // Expand all extending loads to types larger than this, and truncating 566 // stores from types larger than this. 567 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 568 setTruncStoreAction(OtherVT, VT, Expand); 569 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 570 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 571 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 572 } 573 } 574 575 for (MVT VT : IntVecVTs) { 576 if (VT.getVectorElementType() == MVT::i64 && 577 !Subtarget.hasVInstructionsI64()) 578 continue; 579 580 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 581 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 582 583 // Vectors implement MULHS/MULHU. 584 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 585 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 586 587 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 588 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 589 setOperationAction(ISD::MULHU, VT, Expand); 590 setOperationAction(ISD::MULHS, VT, Expand); 591 } 592 593 setOperationAction(ISD::SMIN, VT, Legal); 594 setOperationAction(ISD::SMAX, VT, Legal); 595 setOperationAction(ISD::UMIN, VT, Legal); 596 setOperationAction(ISD::UMAX, VT, Legal); 597 598 setOperationAction(ISD::ROTL, VT, Expand); 599 setOperationAction(ISD::ROTR, VT, Expand); 600 601 setOperationAction(ISD::CTTZ, VT, Expand); 602 setOperationAction(ISD::CTLZ, VT, Expand); 603 setOperationAction(ISD::CTPOP, VT, Expand); 604 605 setOperationAction(ISD::BSWAP, VT, Expand); 606 607 // Custom-lower extensions and truncations from/to mask types. 608 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 609 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 610 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 611 612 // RVV has native int->float & float->int conversions where the 613 // element type sizes are within one power-of-two of each other. Any 614 // wider distances between type sizes have to be lowered as sequences 615 // which progressively narrow the gap in stages. 616 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 617 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 618 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 619 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 620 621 setOperationAction(ISD::SADDSAT, VT, Legal); 622 setOperationAction(ISD::UADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::USUBSAT, VT, Legal); 625 626 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 627 // nodes which truncate by one power of two at a time. 628 setOperationAction(ISD::TRUNCATE, VT, Custom); 629 630 // Custom-lower insert/extract operations to simplify patterns. 631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 633 634 // Custom-lower reduction operations to set up the corresponding custom 635 // nodes' operands. 636 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 644 645 for (unsigned VPOpc : IntegerVPOps) 646 setOperationAction(VPOpc, VT, Custom); 647 648 setOperationAction(ISD::LOAD, VT, Custom); 649 setOperationAction(ISD::STORE, VT, Custom); 650 651 setOperationAction(ISD::MLOAD, VT, Custom); 652 setOperationAction(ISD::MSTORE, VT, Custom); 653 setOperationAction(ISD::MGATHER, VT, Custom); 654 setOperationAction(ISD::MSCATTER, VT, Custom); 655 656 setOperationAction(ISD::VP_LOAD, VT, Custom); 657 setOperationAction(ISD::VP_STORE, VT, Custom); 658 setOperationAction(ISD::VP_GATHER, VT, Custom); 659 setOperationAction(ISD::VP_SCATTER, VT, Custom); 660 661 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 662 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 663 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 664 665 setOperationAction(ISD::SELECT, VT, Custom); 666 setOperationAction(ISD::SELECT_CC, VT, Expand); 667 668 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 669 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 670 671 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 672 setTruncStoreAction(VT, OtherVT, Expand); 673 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 674 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 675 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 676 } 677 678 // Splice 679 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 680 681 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 682 // type that can represent the value exactly. 683 if (VT.getVectorElementType() != MVT::i64) { 684 MVT FloatEltVT = 685 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 686 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 687 if (isTypeLegal(FloatVT)) { 688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 690 } 691 } 692 } 693 694 // Expand various CCs to best match the RVV ISA, which natively supports UNE 695 // but no other unordered comparisons, and supports all ordered comparisons 696 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 697 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 698 // and we pattern-match those back to the "original", swapping operands once 699 // more. This way we catch both operations and both "vf" and "fv" forms with 700 // fewer patterns. 701 static const ISD::CondCode VFPCCToExpand[] = { 702 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 703 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 704 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 705 }; 706 707 // Sets common operation actions on RVV floating-point vector types. 708 const auto SetCommonVFPActions = [&](MVT VT) { 709 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 710 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 711 // sizes are within one power-of-two of each other. Therefore conversions 712 // between vXf16 and vXf64 must be lowered as sequences which convert via 713 // vXf32. 714 setOperationAction(ISD::FP_ROUND, VT, Custom); 715 setOperationAction(ISD::FP_EXTEND, VT, Custom); 716 // Custom-lower insert/extract operations to simplify patterns. 717 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 719 // Expand various condition codes (explained above). 720 for (auto CC : VFPCCToExpand) 721 setCondCodeAction(CC, VT, Expand); 722 723 setOperationAction(ISD::FMINNUM, VT, Legal); 724 setOperationAction(ISD::FMAXNUM, VT, Legal); 725 726 setOperationAction(ISD::FTRUNC, VT, Custom); 727 setOperationAction(ISD::FCEIL, VT, Custom); 728 setOperationAction(ISD::FFLOOR, VT, Custom); 729 setOperationAction(ISD::FROUND, VT, Custom); 730 731 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 732 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 733 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 734 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 735 736 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 737 738 setOperationAction(ISD::LOAD, VT, Custom); 739 setOperationAction(ISD::STORE, VT, Custom); 740 741 setOperationAction(ISD::MLOAD, VT, Custom); 742 setOperationAction(ISD::MSTORE, VT, Custom); 743 setOperationAction(ISD::MGATHER, VT, Custom); 744 setOperationAction(ISD::MSCATTER, VT, Custom); 745 746 setOperationAction(ISD::VP_LOAD, VT, Custom); 747 setOperationAction(ISD::VP_STORE, VT, Custom); 748 setOperationAction(ISD::VP_GATHER, VT, Custom); 749 setOperationAction(ISD::VP_SCATTER, VT, Custom); 750 751 setOperationAction(ISD::SELECT, VT, Custom); 752 setOperationAction(ISD::SELECT_CC, VT, Expand); 753 754 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 755 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 756 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 757 758 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 759 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 760 761 for (unsigned VPOpc : FloatingPointVPOps) 762 setOperationAction(VPOpc, VT, Custom); 763 }; 764 765 // Sets common extload/truncstore actions on RVV floating-point vector 766 // types. 767 const auto SetCommonVFPExtLoadTruncStoreActions = 768 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 769 for (auto SmallVT : SmallerVTs) { 770 setTruncStoreAction(VT, SmallVT, Expand); 771 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 772 } 773 }; 774 775 if (Subtarget.hasVInstructionsF16()) 776 for (MVT VT : F16VecVTs) 777 SetCommonVFPActions(VT); 778 779 for (MVT VT : F32VecVTs) { 780 if (Subtarget.hasVInstructionsF32()) 781 SetCommonVFPActions(VT); 782 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 783 } 784 785 for (MVT VT : F64VecVTs) { 786 if (Subtarget.hasVInstructionsF64()) 787 SetCommonVFPActions(VT); 788 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 789 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 790 } 791 792 if (Subtarget.useRVVForFixedLengthVectors()) { 793 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 794 if (!useRVVForFixedLengthVectorVT(VT)) 795 continue; 796 797 // By default everything must be expanded. 798 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 799 setOperationAction(Op, VT, Expand); 800 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 801 setTruncStoreAction(VT, OtherVT, Expand); 802 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 803 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 804 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 805 } 806 807 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 808 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 809 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 810 811 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 812 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 813 814 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 816 817 setOperationAction(ISD::LOAD, VT, Custom); 818 setOperationAction(ISD::STORE, VT, Custom); 819 820 setOperationAction(ISD::SETCC, VT, Custom); 821 822 setOperationAction(ISD::SELECT, VT, Custom); 823 824 setOperationAction(ISD::TRUNCATE, VT, Custom); 825 826 setOperationAction(ISD::BITCAST, VT, Custom); 827 828 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 829 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 830 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 831 832 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 833 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 834 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 835 836 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 837 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 838 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 839 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 840 841 // Operations below are different for between masks and other vectors. 842 if (VT.getVectorElementType() == MVT::i1) { 843 setOperationAction(ISD::VP_AND, VT, Custom); 844 setOperationAction(ISD::VP_OR, VT, Custom); 845 setOperationAction(ISD::VP_XOR, VT, Custom); 846 setOperationAction(ISD::AND, VT, Custom); 847 setOperationAction(ISD::OR, VT, Custom); 848 setOperationAction(ISD::XOR, VT, Custom); 849 continue; 850 } 851 852 // Use SPLAT_VECTOR to prevent type legalization from destroying the 853 // splats when type legalizing i64 scalar on RV32. 854 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 855 // improvements first. 856 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 857 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 858 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 859 } 860 861 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 862 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 863 864 setOperationAction(ISD::MLOAD, VT, Custom); 865 setOperationAction(ISD::MSTORE, VT, Custom); 866 setOperationAction(ISD::MGATHER, VT, Custom); 867 setOperationAction(ISD::MSCATTER, VT, Custom); 868 869 setOperationAction(ISD::VP_LOAD, VT, Custom); 870 setOperationAction(ISD::VP_STORE, VT, Custom); 871 setOperationAction(ISD::VP_GATHER, VT, Custom); 872 setOperationAction(ISD::VP_SCATTER, VT, Custom); 873 874 setOperationAction(ISD::ADD, VT, Custom); 875 setOperationAction(ISD::MUL, VT, Custom); 876 setOperationAction(ISD::SUB, VT, Custom); 877 setOperationAction(ISD::AND, VT, Custom); 878 setOperationAction(ISD::OR, VT, Custom); 879 setOperationAction(ISD::XOR, VT, Custom); 880 setOperationAction(ISD::SDIV, VT, Custom); 881 setOperationAction(ISD::SREM, VT, Custom); 882 setOperationAction(ISD::UDIV, VT, Custom); 883 setOperationAction(ISD::UREM, VT, Custom); 884 setOperationAction(ISD::SHL, VT, Custom); 885 setOperationAction(ISD::SRA, VT, Custom); 886 setOperationAction(ISD::SRL, VT, Custom); 887 888 setOperationAction(ISD::SMIN, VT, Custom); 889 setOperationAction(ISD::SMAX, VT, Custom); 890 setOperationAction(ISD::UMIN, VT, Custom); 891 setOperationAction(ISD::UMAX, VT, Custom); 892 setOperationAction(ISD::ABS, VT, Custom); 893 894 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 895 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 896 setOperationAction(ISD::MULHS, VT, Custom); 897 setOperationAction(ISD::MULHU, VT, Custom); 898 } 899 900 setOperationAction(ISD::SADDSAT, VT, Custom); 901 setOperationAction(ISD::UADDSAT, VT, Custom); 902 setOperationAction(ISD::SSUBSAT, VT, Custom); 903 setOperationAction(ISD::USUBSAT, VT, Custom); 904 905 setOperationAction(ISD::VSELECT, VT, Custom); 906 setOperationAction(ISD::SELECT_CC, VT, Expand); 907 908 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 909 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 910 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 911 912 // Custom-lower reduction operations to set up the corresponding custom 913 // nodes' operands. 914 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 915 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 916 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 917 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 918 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 919 920 for (unsigned VPOpc : IntegerVPOps) 921 setOperationAction(VPOpc, VT, Custom); 922 923 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 924 // type that can represent the value exactly. 925 if (VT.getVectorElementType() != MVT::i64) { 926 MVT FloatEltVT = 927 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 928 EVT FloatVT = 929 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 930 if (isTypeLegal(FloatVT)) { 931 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 932 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 933 } 934 } 935 } 936 937 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 938 if (!useRVVForFixedLengthVectorVT(VT)) 939 continue; 940 941 // By default everything must be expanded. 942 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 943 setOperationAction(Op, VT, Expand); 944 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 945 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 946 setTruncStoreAction(VT, OtherVT, Expand); 947 } 948 949 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 950 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 951 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 952 953 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 954 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 955 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 956 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 957 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 958 959 setOperationAction(ISD::LOAD, VT, Custom); 960 setOperationAction(ISD::STORE, VT, Custom); 961 setOperationAction(ISD::MLOAD, VT, Custom); 962 setOperationAction(ISD::MSTORE, VT, Custom); 963 setOperationAction(ISD::MGATHER, VT, Custom); 964 setOperationAction(ISD::MSCATTER, VT, Custom); 965 966 setOperationAction(ISD::VP_LOAD, VT, Custom); 967 setOperationAction(ISD::VP_STORE, VT, Custom); 968 setOperationAction(ISD::VP_GATHER, VT, Custom); 969 setOperationAction(ISD::VP_SCATTER, VT, Custom); 970 971 setOperationAction(ISD::FADD, VT, Custom); 972 setOperationAction(ISD::FSUB, VT, Custom); 973 setOperationAction(ISD::FMUL, VT, Custom); 974 setOperationAction(ISD::FDIV, VT, Custom); 975 setOperationAction(ISD::FNEG, VT, Custom); 976 setOperationAction(ISD::FABS, VT, Custom); 977 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 978 setOperationAction(ISD::FSQRT, VT, Custom); 979 setOperationAction(ISD::FMA, VT, Custom); 980 setOperationAction(ISD::FMINNUM, VT, Custom); 981 setOperationAction(ISD::FMAXNUM, VT, Custom); 982 983 setOperationAction(ISD::FP_ROUND, VT, Custom); 984 setOperationAction(ISD::FP_EXTEND, VT, Custom); 985 986 setOperationAction(ISD::FTRUNC, VT, Custom); 987 setOperationAction(ISD::FCEIL, VT, Custom); 988 setOperationAction(ISD::FFLOOR, VT, Custom); 989 setOperationAction(ISD::FROUND, VT, Custom); 990 991 for (auto CC : VFPCCToExpand) 992 setCondCodeAction(CC, VT, Expand); 993 994 setOperationAction(ISD::VSELECT, VT, Custom); 995 setOperationAction(ISD::SELECT, VT, Custom); 996 setOperationAction(ISD::SELECT_CC, VT, Expand); 997 998 setOperationAction(ISD::BITCAST, VT, Custom); 999 1000 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1001 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1002 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1003 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1004 1005 for (unsigned VPOpc : FloatingPointVPOps) 1006 setOperationAction(VPOpc, VT, Custom); 1007 } 1008 1009 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1010 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1011 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1012 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1013 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1014 if (Subtarget.hasStdExtZfh()) 1015 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1016 if (Subtarget.hasStdExtF()) 1017 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1018 if (Subtarget.hasStdExtD()) 1019 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1020 } 1021 } 1022 1023 // Function alignments. 1024 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1025 setMinFunctionAlignment(FunctionAlignment); 1026 setPrefFunctionAlignment(FunctionAlignment); 1027 1028 setMinimumJumpTableEntries(5); 1029 1030 // Jumps are expensive, compared to logic 1031 setJumpIsExpensive(); 1032 1033 setTargetDAGCombine(ISD::ADD); 1034 setTargetDAGCombine(ISD::SUB); 1035 setTargetDAGCombine(ISD::AND); 1036 setTargetDAGCombine(ISD::OR); 1037 setTargetDAGCombine(ISD::XOR); 1038 if (Subtarget.hasStdExtZbp()) { 1039 setTargetDAGCombine(ISD::ROTL); 1040 setTargetDAGCombine(ISD::ROTR); 1041 } 1042 setTargetDAGCombine(ISD::ANY_EXTEND); 1043 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1044 if (Subtarget.hasStdExtZfh()) 1045 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1046 if (Subtarget.hasStdExtF()) { 1047 setTargetDAGCombine(ISD::ZERO_EXTEND); 1048 setTargetDAGCombine(ISD::FP_TO_SINT); 1049 setTargetDAGCombine(ISD::FP_TO_UINT); 1050 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1051 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1052 } 1053 if (Subtarget.hasVInstructions()) { 1054 setTargetDAGCombine(ISD::FCOPYSIGN); 1055 setTargetDAGCombine(ISD::MGATHER); 1056 setTargetDAGCombine(ISD::MSCATTER); 1057 setTargetDAGCombine(ISD::VP_GATHER); 1058 setTargetDAGCombine(ISD::VP_SCATTER); 1059 setTargetDAGCombine(ISD::SRA); 1060 setTargetDAGCombine(ISD::SRL); 1061 setTargetDAGCombine(ISD::SHL); 1062 setTargetDAGCombine(ISD::STORE); 1063 setTargetDAGCombine(ISD::SPLAT_VECTOR); 1064 } 1065 1066 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1067 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1068 } 1069 1070 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1071 LLVMContext &Context, 1072 EVT VT) const { 1073 if (!VT.isVector()) 1074 return getPointerTy(DL); 1075 if (Subtarget.hasVInstructions() && 1076 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1077 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1078 return VT.changeVectorElementTypeToInteger(); 1079 } 1080 1081 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1082 return Subtarget.getXLenVT(); 1083 } 1084 1085 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1086 const CallInst &I, 1087 MachineFunction &MF, 1088 unsigned Intrinsic) const { 1089 auto &DL = I.getModule()->getDataLayout(); 1090 switch (Intrinsic) { 1091 default: 1092 return false; 1093 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1094 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1099 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1100 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1101 case Intrinsic::riscv_masked_cmpxchg_i32: 1102 Info.opc = ISD::INTRINSIC_W_CHAIN; 1103 Info.memVT = MVT::i32; 1104 Info.ptrVal = I.getArgOperand(0); 1105 Info.offset = 0; 1106 Info.align = Align(4); 1107 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1108 MachineMemOperand::MOVolatile; 1109 return true; 1110 case Intrinsic::riscv_masked_strided_load: 1111 Info.opc = ISD::INTRINSIC_W_CHAIN; 1112 Info.ptrVal = I.getArgOperand(1); 1113 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1114 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1115 Info.size = MemoryLocation::UnknownSize; 1116 Info.flags |= MachineMemOperand::MOLoad; 1117 return true; 1118 case Intrinsic::riscv_masked_strided_store: 1119 Info.opc = ISD::INTRINSIC_VOID; 1120 Info.ptrVal = I.getArgOperand(1); 1121 Info.memVT = 1122 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1123 Info.align = Align( 1124 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1125 8); 1126 Info.size = MemoryLocation::UnknownSize; 1127 Info.flags |= MachineMemOperand::MOStore; 1128 return true; 1129 } 1130 } 1131 1132 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1133 const AddrMode &AM, Type *Ty, 1134 unsigned AS, 1135 Instruction *I) const { 1136 // No global is ever allowed as a base. 1137 if (AM.BaseGV) 1138 return false; 1139 1140 // Require a 12-bit signed offset. 1141 if (!isInt<12>(AM.BaseOffs)) 1142 return false; 1143 1144 switch (AM.Scale) { 1145 case 0: // "r+i" or just "i", depending on HasBaseReg. 1146 break; 1147 case 1: 1148 if (!AM.HasBaseReg) // allow "r+i". 1149 break; 1150 return false; // disallow "r+r" or "r+r+i". 1151 default: 1152 return false; 1153 } 1154 1155 return true; 1156 } 1157 1158 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1159 return isInt<12>(Imm); 1160 } 1161 1162 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1163 return isInt<12>(Imm); 1164 } 1165 1166 // On RV32, 64-bit integers are split into their high and low parts and held 1167 // in two different registers, so the trunc is free since the low register can 1168 // just be used. 1169 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1170 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1171 return false; 1172 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1173 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1174 return (SrcBits == 64 && DestBits == 32); 1175 } 1176 1177 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1178 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1179 !SrcVT.isInteger() || !DstVT.isInteger()) 1180 return false; 1181 unsigned SrcBits = SrcVT.getSizeInBits(); 1182 unsigned DestBits = DstVT.getSizeInBits(); 1183 return (SrcBits == 64 && DestBits == 32); 1184 } 1185 1186 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1187 // Zexts are free if they can be combined with a load. 1188 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1189 // poorly with type legalization of compares preferring sext. 1190 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1191 EVT MemVT = LD->getMemoryVT(); 1192 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1193 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1194 LD->getExtensionType() == ISD::ZEXTLOAD)) 1195 return true; 1196 } 1197 1198 return TargetLowering::isZExtFree(Val, VT2); 1199 } 1200 1201 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1202 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1203 } 1204 1205 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1206 return Subtarget.hasStdExtZbb(); 1207 } 1208 1209 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1210 return Subtarget.hasStdExtZbb(); 1211 } 1212 1213 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1214 EVT VT = Y.getValueType(); 1215 1216 // FIXME: Support vectors once we have tests. 1217 if (VT.isVector()) 1218 return false; 1219 1220 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1221 Subtarget.hasStdExtZbkb()) && 1222 !isa<ConstantSDNode>(Y); 1223 } 1224 1225 /// Check if sinking \p I's operands to I's basic block is profitable, because 1226 /// the operands can be folded into a target instruction, e.g. 1227 /// splats of scalars can fold into vector instructions. 1228 bool RISCVTargetLowering::shouldSinkOperands( 1229 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1230 using namespace llvm::PatternMatch; 1231 1232 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1233 return false; 1234 1235 auto IsSinker = [&](Instruction *I, int Operand) { 1236 switch (I->getOpcode()) { 1237 case Instruction::Add: 1238 case Instruction::Sub: 1239 case Instruction::Mul: 1240 case Instruction::And: 1241 case Instruction::Or: 1242 case Instruction::Xor: 1243 case Instruction::FAdd: 1244 case Instruction::FSub: 1245 case Instruction::FMul: 1246 case Instruction::FDiv: 1247 case Instruction::ICmp: 1248 case Instruction::FCmp: 1249 return true; 1250 case Instruction::Shl: 1251 case Instruction::LShr: 1252 case Instruction::AShr: 1253 case Instruction::UDiv: 1254 case Instruction::SDiv: 1255 case Instruction::URem: 1256 case Instruction::SRem: 1257 return Operand == 1; 1258 case Instruction::Call: 1259 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1260 switch (II->getIntrinsicID()) { 1261 case Intrinsic::fma: 1262 case Intrinsic::vp_fma: 1263 return Operand == 0 || Operand == 1; 1264 // FIXME: Our patterns can only match vx/vf instructions when the splat 1265 // it on the RHS, because TableGen doesn't recognize our VP operations 1266 // as commutative. 1267 case Intrinsic::vp_add: 1268 case Intrinsic::vp_mul: 1269 case Intrinsic::vp_and: 1270 case Intrinsic::vp_or: 1271 case Intrinsic::vp_xor: 1272 case Intrinsic::vp_fadd: 1273 case Intrinsic::vp_fmul: 1274 case Intrinsic::vp_shl: 1275 case Intrinsic::vp_lshr: 1276 case Intrinsic::vp_ashr: 1277 case Intrinsic::vp_udiv: 1278 case Intrinsic::vp_sdiv: 1279 case Intrinsic::vp_urem: 1280 case Intrinsic::vp_srem: 1281 return Operand == 1; 1282 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1283 // explicit patterns for both LHS and RHS (as 'vr' versions). 1284 case Intrinsic::vp_sub: 1285 case Intrinsic::vp_fsub: 1286 case Intrinsic::vp_fdiv: 1287 return Operand == 0 || Operand == 1; 1288 default: 1289 return false; 1290 } 1291 } 1292 return false; 1293 default: 1294 return false; 1295 } 1296 }; 1297 1298 for (auto OpIdx : enumerate(I->operands())) { 1299 if (!IsSinker(I, OpIdx.index())) 1300 continue; 1301 1302 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1303 // Make sure we are not already sinking this operand 1304 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1305 continue; 1306 1307 // We are looking for a splat that can be sunk. 1308 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1309 m_Undef(), m_ZeroMask()))) 1310 continue; 1311 1312 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1313 // and vector registers 1314 for (Use &U : Op->uses()) { 1315 Instruction *Insn = cast<Instruction>(U.getUser()); 1316 if (!IsSinker(Insn, U.getOperandNo())) 1317 return false; 1318 } 1319 1320 Ops.push_back(&Op->getOperandUse(0)); 1321 Ops.push_back(&OpIdx.value()); 1322 } 1323 return true; 1324 } 1325 1326 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1327 bool ForCodeSize) const { 1328 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1329 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1330 return false; 1331 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1332 return false; 1333 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1334 return false; 1335 return Imm.isZero(); 1336 } 1337 1338 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1339 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1340 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1341 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1342 } 1343 1344 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1345 CallingConv::ID CC, 1346 EVT VT) const { 1347 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1348 // We might still end up using a GPR but that will be decided based on ABI. 1349 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1350 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1351 return MVT::f32; 1352 1353 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1354 } 1355 1356 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1357 CallingConv::ID CC, 1358 EVT VT) const { 1359 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1360 // We might still end up using a GPR but that will be decided based on ABI. 1361 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1362 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1363 return 1; 1364 1365 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1366 } 1367 1368 // Changes the condition code and swaps operands if necessary, so the SetCC 1369 // operation matches one of the comparisons supported directly by branches 1370 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1371 // with 1/-1. 1372 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1373 ISD::CondCode &CC, SelectionDAG &DAG) { 1374 // Convert X > -1 to X >= 0. 1375 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1376 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1377 CC = ISD::SETGE; 1378 return; 1379 } 1380 // Convert X < 1 to 0 >= X. 1381 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1382 RHS = LHS; 1383 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1384 CC = ISD::SETGE; 1385 return; 1386 } 1387 1388 switch (CC) { 1389 default: 1390 break; 1391 case ISD::SETGT: 1392 case ISD::SETLE: 1393 case ISD::SETUGT: 1394 case ISD::SETULE: 1395 CC = ISD::getSetCCSwappedOperands(CC); 1396 std::swap(LHS, RHS); 1397 break; 1398 } 1399 } 1400 1401 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1402 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1403 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1404 if (VT.getVectorElementType() == MVT::i1) 1405 KnownSize *= 8; 1406 1407 switch (KnownSize) { 1408 default: 1409 llvm_unreachable("Invalid LMUL."); 1410 case 8: 1411 return RISCVII::VLMUL::LMUL_F8; 1412 case 16: 1413 return RISCVII::VLMUL::LMUL_F4; 1414 case 32: 1415 return RISCVII::VLMUL::LMUL_F2; 1416 case 64: 1417 return RISCVII::VLMUL::LMUL_1; 1418 case 128: 1419 return RISCVII::VLMUL::LMUL_2; 1420 case 256: 1421 return RISCVII::VLMUL::LMUL_4; 1422 case 512: 1423 return RISCVII::VLMUL::LMUL_8; 1424 } 1425 } 1426 1427 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1428 switch (LMul) { 1429 default: 1430 llvm_unreachable("Invalid LMUL."); 1431 case RISCVII::VLMUL::LMUL_F8: 1432 case RISCVII::VLMUL::LMUL_F4: 1433 case RISCVII::VLMUL::LMUL_F2: 1434 case RISCVII::VLMUL::LMUL_1: 1435 return RISCV::VRRegClassID; 1436 case RISCVII::VLMUL::LMUL_2: 1437 return RISCV::VRM2RegClassID; 1438 case RISCVII::VLMUL::LMUL_4: 1439 return RISCV::VRM4RegClassID; 1440 case RISCVII::VLMUL::LMUL_8: 1441 return RISCV::VRM8RegClassID; 1442 } 1443 } 1444 1445 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1446 RISCVII::VLMUL LMUL = getLMUL(VT); 1447 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1448 LMUL == RISCVII::VLMUL::LMUL_F4 || 1449 LMUL == RISCVII::VLMUL::LMUL_F2 || 1450 LMUL == RISCVII::VLMUL::LMUL_1) { 1451 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1452 "Unexpected subreg numbering"); 1453 return RISCV::sub_vrm1_0 + Index; 1454 } 1455 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1456 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1457 "Unexpected subreg numbering"); 1458 return RISCV::sub_vrm2_0 + Index; 1459 } 1460 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1461 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1462 "Unexpected subreg numbering"); 1463 return RISCV::sub_vrm4_0 + Index; 1464 } 1465 llvm_unreachable("Invalid vector type."); 1466 } 1467 1468 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1469 if (VT.getVectorElementType() == MVT::i1) 1470 return RISCV::VRRegClassID; 1471 return getRegClassIDForLMUL(getLMUL(VT)); 1472 } 1473 1474 // Attempt to decompose a subvector insert/extract between VecVT and 1475 // SubVecVT via subregister indices. Returns the subregister index that 1476 // can perform the subvector insert/extract with the given element index, as 1477 // well as the index corresponding to any leftover subvectors that must be 1478 // further inserted/extracted within the register class for SubVecVT. 1479 std::pair<unsigned, unsigned> 1480 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1481 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1482 const RISCVRegisterInfo *TRI) { 1483 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1484 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1485 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1486 "Register classes not ordered"); 1487 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1488 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1489 // Try to compose a subregister index that takes us from the incoming 1490 // LMUL>1 register class down to the outgoing one. At each step we half 1491 // the LMUL: 1492 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1493 // Note that this is not guaranteed to find a subregister index, such as 1494 // when we are extracting from one VR type to another. 1495 unsigned SubRegIdx = RISCV::NoSubRegister; 1496 for (const unsigned RCID : 1497 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1498 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1499 VecVT = VecVT.getHalfNumVectorElementsVT(); 1500 bool IsHi = 1501 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1502 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1503 getSubregIndexByMVT(VecVT, IsHi)); 1504 if (IsHi) 1505 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1506 } 1507 return {SubRegIdx, InsertExtractIdx}; 1508 } 1509 1510 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1511 // stores for those types. 1512 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1513 return !Subtarget.useRVVForFixedLengthVectors() || 1514 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1515 } 1516 1517 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1518 if (ScalarTy->isPointerTy()) 1519 return true; 1520 1521 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1522 ScalarTy->isIntegerTy(32)) 1523 return true; 1524 1525 if (ScalarTy->isIntegerTy(64)) 1526 return Subtarget.hasVInstructionsI64(); 1527 1528 if (ScalarTy->isHalfTy()) 1529 return Subtarget.hasVInstructionsF16(); 1530 if (ScalarTy->isFloatTy()) 1531 return Subtarget.hasVInstructionsF32(); 1532 if (ScalarTy->isDoubleTy()) 1533 return Subtarget.hasVInstructionsF64(); 1534 1535 return false; 1536 } 1537 1538 static SDValue getVLOperand(SDValue Op) { 1539 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1540 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1541 "Unexpected opcode"); 1542 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1543 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1544 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1545 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1546 if (!II) 1547 return SDValue(); 1548 return Op.getOperand(II->VLOperand + 1 + HasChain); 1549 } 1550 1551 static bool useRVVForFixedLengthVectorVT(MVT VT, 1552 const RISCVSubtarget &Subtarget) { 1553 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1554 if (!Subtarget.useRVVForFixedLengthVectors()) 1555 return false; 1556 1557 // We only support a set of vector types with a consistent maximum fixed size 1558 // across all supported vector element types to avoid legalization issues. 1559 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1560 // fixed-length vector type we support is 1024 bytes. 1561 if (VT.getFixedSizeInBits() > 1024 * 8) 1562 return false; 1563 1564 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1565 1566 MVT EltVT = VT.getVectorElementType(); 1567 1568 // Don't use RVV for vectors we cannot scalarize if required. 1569 switch (EltVT.SimpleTy) { 1570 // i1 is supported but has different rules. 1571 default: 1572 return false; 1573 case MVT::i1: 1574 // Masks can only use a single register. 1575 if (VT.getVectorNumElements() > MinVLen) 1576 return false; 1577 MinVLen /= 8; 1578 break; 1579 case MVT::i8: 1580 case MVT::i16: 1581 case MVT::i32: 1582 break; 1583 case MVT::i64: 1584 if (!Subtarget.hasVInstructionsI64()) 1585 return false; 1586 break; 1587 case MVT::f16: 1588 if (!Subtarget.hasVInstructionsF16()) 1589 return false; 1590 break; 1591 case MVT::f32: 1592 if (!Subtarget.hasVInstructionsF32()) 1593 return false; 1594 break; 1595 case MVT::f64: 1596 if (!Subtarget.hasVInstructionsF64()) 1597 return false; 1598 break; 1599 } 1600 1601 // Reject elements larger than ELEN. 1602 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1603 return false; 1604 1605 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1606 // Don't use RVV for types that don't fit. 1607 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1608 return false; 1609 1610 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1611 // the base fixed length RVV support in place. 1612 if (!VT.isPow2VectorType()) 1613 return false; 1614 1615 return true; 1616 } 1617 1618 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1619 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1620 } 1621 1622 // Return the largest legal scalable vector type that matches VT's element type. 1623 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1624 const RISCVSubtarget &Subtarget) { 1625 // This may be called before legal types are setup. 1626 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1627 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1628 "Expected legal fixed length vector!"); 1629 1630 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1631 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1632 1633 MVT EltVT = VT.getVectorElementType(); 1634 switch (EltVT.SimpleTy) { 1635 default: 1636 llvm_unreachable("unexpected element type for RVV container"); 1637 case MVT::i1: 1638 case MVT::i8: 1639 case MVT::i16: 1640 case MVT::i32: 1641 case MVT::i64: 1642 case MVT::f16: 1643 case MVT::f32: 1644 case MVT::f64: { 1645 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1646 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1647 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1648 unsigned NumElts = 1649 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1650 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1651 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1652 return MVT::getScalableVectorVT(EltVT, NumElts); 1653 } 1654 } 1655 } 1656 1657 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1658 const RISCVSubtarget &Subtarget) { 1659 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1660 Subtarget); 1661 } 1662 1663 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1664 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1665 } 1666 1667 // Grow V to consume an entire RVV register. 1668 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1669 const RISCVSubtarget &Subtarget) { 1670 assert(VT.isScalableVector() && 1671 "Expected to convert into a scalable vector!"); 1672 assert(V.getValueType().isFixedLengthVector() && 1673 "Expected a fixed length vector operand!"); 1674 SDLoc DL(V); 1675 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1676 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1677 } 1678 1679 // Shrink V so it's just big enough to maintain a VT's worth of data. 1680 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1681 const RISCVSubtarget &Subtarget) { 1682 assert(VT.isFixedLengthVector() && 1683 "Expected to convert into a fixed length vector!"); 1684 assert(V.getValueType().isScalableVector() && 1685 "Expected a scalable vector operand!"); 1686 SDLoc DL(V); 1687 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1688 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1689 } 1690 1691 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1692 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1693 // the vector type that it is contained in. 1694 static std::pair<SDValue, SDValue> 1695 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1696 const RISCVSubtarget &Subtarget) { 1697 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1698 MVT XLenVT = Subtarget.getXLenVT(); 1699 SDValue VL = VecVT.isFixedLengthVector() 1700 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1701 : DAG.getRegister(RISCV::X0, XLenVT); 1702 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1703 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1704 return {Mask, VL}; 1705 } 1706 1707 // As above but assuming the given type is a scalable vector type. 1708 static std::pair<SDValue, SDValue> 1709 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1710 const RISCVSubtarget &Subtarget) { 1711 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1712 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1713 } 1714 1715 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1716 // of either is (currently) supported. This can get us into an infinite loop 1717 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1718 // as a ..., etc. 1719 // Until either (or both) of these can reliably lower any node, reporting that 1720 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1721 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1722 // which is not desirable. 1723 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1724 EVT VT, unsigned DefinedValues) const { 1725 return false; 1726 } 1727 1728 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1729 const RISCVSubtarget &Subtarget) { 1730 // RISCV FP-to-int conversions saturate to the destination register size, but 1731 // don't produce 0 for nan. We can use a conversion instruction and fix the 1732 // nan case with a compare and a select. 1733 SDValue Src = Op.getOperand(0); 1734 1735 EVT DstVT = Op.getValueType(); 1736 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1737 1738 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1739 unsigned Opc; 1740 if (SatVT == DstVT) 1741 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1742 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1743 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1744 else 1745 return SDValue(); 1746 // FIXME: Support other SatVTs by clamping before or after the conversion. 1747 1748 SDLoc DL(Op); 1749 SDValue FpToInt = DAG.getNode( 1750 Opc, DL, DstVT, Src, 1751 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1752 1753 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1754 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1755 } 1756 1757 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1758 // and back. Taking care to avoid converting values that are nan or already 1759 // correct. 1760 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1761 // have FRM dependencies modeled yet. 1762 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1763 MVT VT = Op.getSimpleValueType(); 1764 assert(VT.isVector() && "Unexpected type"); 1765 1766 SDLoc DL(Op); 1767 1768 // Freeze the source since we are increasing the number of uses. 1769 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1770 1771 // Truncate to integer and convert back to FP. 1772 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1773 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1774 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1775 1776 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1777 1778 if (Op.getOpcode() == ISD::FCEIL) { 1779 // If the truncated value is the greater than or equal to the original 1780 // value, we've computed the ceil. Otherwise, we went the wrong way and 1781 // need to increase by 1. 1782 // FIXME: This should use a masked operation. Handle here or in isel? 1783 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1784 DAG.getConstantFP(1.0, DL, VT)); 1785 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1786 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1787 } else if (Op.getOpcode() == ISD::FFLOOR) { 1788 // If the truncated value is the less than or equal to the original value, 1789 // we've computed the floor. Otherwise, we went the wrong way and need to 1790 // decrease by 1. 1791 // FIXME: This should use a masked operation. Handle here or in isel? 1792 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1793 DAG.getConstantFP(1.0, DL, VT)); 1794 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1795 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1796 } 1797 1798 // Restore the original sign so that -0.0 is preserved. 1799 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1800 1801 // Determine the largest integer that can be represented exactly. This and 1802 // values larger than it don't have any fractional bits so don't need to 1803 // be converted. 1804 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1805 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1806 APFloat MaxVal = APFloat(FltSem); 1807 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1808 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1809 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1810 1811 // If abs(Src) was larger than MaxVal or nan, keep it. 1812 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1813 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1814 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1815 } 1816 1817 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1818 // This mode isn't supported in vector hardware on RISCV. But as long as we 1819 // aren't compiling with trapping math, we can emulate this with 1820 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1821 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1822 // dependencies modeled yet. 1823 // FIXME: Use masked operations to avoid final merge. 1824 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1825 MVT VT = Op.getSimpleValueType(); 1826 assert(VT.isVector() && "Unexpected type"); 1827 1828 SDLoc DL(Op); 1829 1830 // Freeze the source since we are increasing the number of uses. 1831 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1832 1833 // We do the conversion on the absolute value and fix the sign at the end. 1834 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1835 1836 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1837 bool Ignored; 1838 APFloat Point5Pred = APFloat(0.5f); 1839 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1840 Point5Pred.next(/*nextDown*/ true); 1841 1842 // Add the adjustment. 1843 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1844 DAG.getConstantFP(Point5Pred, DL, VT)); 1845 1846 // Truncate to integer and convert back to fp. 1847 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1848 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1849 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1850 1851 // Restore the original sign. 1852 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1853 1854 // Determine the largest integer that can be represented exactly. This and 1855 // values larger than it don't have any fractional bits so don't need to 1856 // be converted. 1857 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1858 APFloat MaxVal = APFloat(FltSem); 1859 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1860 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1861 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1862 1863 // If abs(Src) was larger than MaxVal or nan, keep it. 1864 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1865 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1866 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1867 } 1868 1869 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1870 const RISCVSubtarget &Subtarget) { 1871 MVT VT = Op.getSimpleValueType(); 1872 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1873 1874 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1875 1876 SDLoc DL(Op); 1877 SDValue Mask, VL; 1878 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1879 1880 unsigned Opc = 1881 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1882 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 1883 Op.getOperand(0), VL); 1884 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1885 } 1886 1887 struct VIDSequence { 1888 int64_t StepNumerator; 1889 unsigned StepDenominator; 1890 int64_t Addend; 1891 }; 1892 1893 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1894 // to the (non-zero) step S and start value X. This can be then lowered as the 1895 // RVV sequence (VID * S) + X, for example. 1896 // The step S is represented as an integer numerator divided by a positive 1897 // denominator. Note that the implementation currently only identifies 1898 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1899 // cannot detect 2/3, for example. 1900 // Note that this method will also match potentially unappealing index 1901 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1902 // determine whether this is worth generating code for. 1903 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1904 unsigned NumElts = Op.getNumOperands(); 1905 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1906 if (!Op.getValueType().isInteger()) 1907 return None; 1908 1909 Optional<unsigned> SeqStepDenom; 1910 Optional<int64_t> SeqStepNum, SeqAddend; 1911 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1912 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1913 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1914 // Assume undef elements match the sequence; we just have to be careful 1915 // when interpolating across them. 1916 if (Op.getOperand(Idx).isUndef()) 1917 continue; 1918 // The BUILD_VECTOR must be all constants. 1919 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1920 return None; 1921 1922 uint64_t Val = Op.getConstantOperandVal(Idx) & 1923 maskTrailingOnes<uint64_t>(EltSizeInBits); 1924 1925 if (PrevElt) { 1926 // Calculate the step since the last non-undef element, and ensure 1927 // it's consistent across the entire sequence. 1928 unsigned IdxDiff = Idx - PrevElt->second; 1929 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1930 1931 // A zero-value value difference means that we're somewhere in the middle 1932 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1933 // step change before evaluating the sequence. 1934 if (ValDiff != 0) { 1935 int64_t Remainder = ValDiff % IdxDiff; 1936 // Normalize the step if it's greater than 1. 1937 if (Remainder != ValDiff) { 1938 // The difference must cleanly divide the element span. 1939 if (Remainder != 0) 1940 return None; 1941 ValDiff /= IdxDiff; 1942 IdxDiff = 1; 1943 } 1944 1945 if (!SeqStepNum) 1946 SeqStepNum = ValDiff; 1947 else if (ValDiff != SeqStepNum) 1948 return None; 1949 1950 if (!SeqStepDenom) 1951 SeqStepDenom = IdxDiff; 1952 else if (IdxDiff != *SeqStepDenom) 1953 return None; 1954 } 1955 } 1956 1957 // Record and/or check any addend. 1958 if (SeqStepNum && SeqStepDenom) { 1959 uint64_t ExpectedVal = 1960 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1961 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1962 if (!SeqAddend) 1963 SeqAddend = Addend; 1964 else if (SeqAddend != Addend) 1965 return None; 1966 } 1967 1968 // Record this non-undef element for later. 1969 if (!PrevElt || PrevElt->first != Val) 1970 PrevElt = std::make_pair(Val, Idx); 1971 } 1972 // We need to have logged both a step and an addend for this to count as 1973 // a legal index sequence. 1974 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1975 return None; 1976 1977 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1978 } 1979 1980 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1981 // and lower it as a VRGATHER_VX_VL from the source vector. 1982 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1983 SelectionDAG &DAG, 1984 const RISCVSubtarget &Subtarget) { 1985 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1986 return SDValue(); 1987 SDValue Vec = SplatVal.getOperand(0); 1988 // Only perform this optimization on vectors of the same size for simplicity. 1989 if (Vec.getValueType() != VT) 1990 return SDValue(); 1991 SDValue Idx = SplatVal.getOperand(1); 1992 // The index must be a legal type. 1993 if (Idx.getValueType() != Subtarget.getXLenVT()) 1994 return SDValue(); 1995 1996 MVT ContainerVT = VT; 1997 if (VT.isFixedLengthVector()) { 1998 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1999 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2000 } 2001 2002 SDValue Mask, VL; 2003 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2004 2005 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2006 Idx, Mask, VL); 2007 2008 if (!VT.isFixedLengthVector()) 2009 return Gather; 2010 2011 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2012 } 2013 2014 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2015 const RISCVSubtarget &Subtarget) { 2016 MVT VT = Op.getSimpleValueType(); 2017 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2018 2019 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2020 2021 SDLoc DL(Op); 2022 SDValue Mask, VL; 2023 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2024 2025 MVT XLenVT = Subtarget.getXLenVT(); 2026 unsigned NumElts = Op.getNumOperands(); 2027 2028 if (VT.getVectorElementType() == MVT::i1) { 2029 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2030 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2031 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2032 } 2033 2034 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2035 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2036 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2037 } 2038 2039 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2040 // scalar integer chunks whose bit-width depends on the number of mask 2041 // bits and XLEN. 2042 // First, determine the most appropriate scalar integer type to use. This 2043 // is at most XLenVT, but may be shrunk to a smaller vector element type 2044 // according to the size of the final vector - use i8 chunks rather than 2045 // XLenVT if we're producing a v8i1. This results in more consistent 2046 // codegen across RV32 and RV64. 2047 unsigned NumViaIntegerBits = 2048 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2049 NumViaIntegerBits = std::min(NumViaIntegerBits, 2050 Subtarget.getMaxELENForFixedLengthVectors()); 2051 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2052 // If we have to use more than one INSERT_VECTOR_ELT then this 2053 // optimization is likely to increase code size; avoid peforming it in 2054 // such a case. We can use a load from a constant pool in this case. 2055 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2056 return SDValue(); 2057 // Now we can create our integer vector type. Note that it may be larger 2058 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2059 MVT IntegerViaVecVT = 2060 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2061 divideCeil(NumElts, NumViaIntegerBits)); 2062 2063 uint64_t Bits = 0; 2064 unsigned BitPos = 0, IntegerEltIdx = 0; 2065 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2066 2067 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2068 // Once we accumulate enough bits to fill our scalar type, insert into 2069 // our vector and clear our accumulated data. 2070 if (I != 0 && I % NumViaIntegerBits == 0) { 2071 if (NumViaIntegerBits <= 32) 2072 Bits = SignExtend64(Bits, 32); 2073 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2074 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2075 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2076 Bits = 0; 2077 BitPos = 0; 2078 IntegerEltIdx++; 2079 } 2080 SDValue V = Op.getOperand(I); 2081 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2082 Bits |= ((uint64_t)BitValue << BitPos); 2083 } 2084 2085 // Insert the (remaining) scalar value into position in our integer 2086 // vector type. 2087 if (NumViaIntegerBits <= 32) 2088 Bits = SignExtend64(Bits, 32); 2089 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2090 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2091 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2092 2093 if (NumElts < NumViaIntegerBits) { 2094 // If we're producing a smaller vector than our minimum legal integer 2095 // type, bitcast to the equivalent (known-legal) mask type, and extract 2096 // our final mask. 2097 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2098 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2099 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2100 DAG.getConstant(0, DL, XLenVT)); 2101 } else { 2102 // Else we must have produced an integer type with the same size as the 2103 // mask type; bitcast for the final result. 2104 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2105 Vec = DAG.getBitcast(VT, Vec); 2106 } 2107 2108 return Vec; 2109 } 2110 2111 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2112 // vector type, we have a legal equivalently-sized i8 type, so we can use 2113 // that. 2114 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2115 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2116 2117 SDValue WideVec; 2118 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2119 // For a splat, perform a scalar truncate before creating the wider 2120 // vector. 2121 assert(Splat.getValueType() == XLenVT && 2122 "Unexpected type for i1 splat value"); 2123 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2124 DAG.getConstant(1, DL, XLenVT)); 2125 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2126 } else { 2127 SmallVector<SDValue, 8> Ops(Op->op_values()); 2128 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2129 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2130 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2131 } 2132 2133 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2134 } 2135 2136 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2137 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2138 return Gather; 2139 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2140 : RISCVISD::VMV_V_X_VL; 2141 Splat = 2142 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2143 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2144 } 2145 2146 // Try and match index sequences, which we can lower to the vid instruction 2147 // with optional modifications. An all-undef vector is matched by 2148 // getSplatValue, above. 2149 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2150 int64_t StepNumerator = SimpleVID->StepNumerator; 2151 unsigned StepDenominator = SimpleVID->StepDenominator; 2152 int64_t Addend = SimpleVID->Addend; 2153 2154 assert(StepNumerator != 0 && "Invalid step"); 2155 bool Negate = false; 2156 int64_t SplatStepVal = StepNumerator; 2157 unsigned StepOpcode = ISD::MUL; 2158 if (StepNumerator != 1) { 2159 if (isPowerOf2_64(std::abs(StepNumerator))) { 2160 Negate = StepNumerator < 0; 2161 StepOpcode = ISD::SHL; 2162 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2163 } 2164 } 2165 2166 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2167 // threshold since it's the immediate value many RVV instructions accept. 2168 // There is no vmul.vi instruction so ensure multiply constant can fit in 2169 // a single addi instruction. 2170 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2171 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2172 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2173 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2174 // Convert right out of the scalable type so we can use standard ISD 2175 // nodes for the rest of the computation. If we used scalable types with 2176 // these, we'd lose the fixed-length vector info and generate worse 2177 // vsetvli code. 2178 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2179 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2180 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2181 SDValue SplatStep = DAG.getSplatVector( 2182 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2183 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2184 } 2185 if (StepDenominator != 1) { 2186 SDValue SplatStep = DAG.getSplatVector( 2187 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2188 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2189 } 2190 if (Addend != 0 || Negate) { 2191 SDValue SplatAddend = 2192 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2193 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2194 } 2195 return VID; 2196 } 2197 } 2198 2199 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2200 // when re-interpreted as a vector with a larger element type. For example, 2201 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2202 // could be instead splat as 2203 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2204 // TODO: This optimization could also work on non-constant splats, but it 2205 // would require bit-manipulation instructions to construct the splat value. 2206 SmallVector<SDValue> Sequence; 2207 unsigned EltBitSize = VT.getScalarSizeInBits(); 2208 const auto *BV = cast<BuildVectorSDNode>(Op); 2209 if (VT.isInteger() && EltBitSize < 64 && 2210 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2211 BV->getRepeatedSequence(Sequence) && 2212 (Sequence.size() * EltBitSize) <= 64) { 2213 unsigned SeqLen = Sequence.size(); 2214 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2215 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2216 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2217 ViaIntVT == MVT::i64) && 2218 "Unexpected sequence type"); 2219 2220 unsigned EltIdx = 0; 2221 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2222 uint64_t SplatValue = 0; 2223 // Construct the amalgamated value which can be splatted as this larger 2224 // vector type. 2225 for (const auto &SeqV : Sequence) { 2226 if (!SeqV.isUndef()) 2227 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2228 << (EltIdx * EltBitSize)); 2229 EltIdx++; 2230 } 2231 2232 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2233 // achieve better constant materializion. 2234 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2235 SplatValue = SignExtend64(SplatValue, 32); 2236 2237 // Since we can't introduce illegal i64 types at this stage, we can only 2238 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2239 // way we can use RVV instructions to splat. 2240 assert((ViaIntVT.bitsLE(XLenVT) || 2241 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2242 "Unexpected bitcast sequence"); 2243 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2244 SDValue ViaVL = 2245 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2246 MVT ViaContainerVT = 2247 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2248 SDValue Splat = 2249 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2250 DAG.getUNDEF(ViaContainerVT), 2251 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2252 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2253 return DAG.getBitcast(VT, Splat); 2254 } 2255 } 2256 2257 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2258 // which constitute a large proportion of the elements. In such cases we can 2259 // splat a vector with the dominant element and make up the shortfall with 2260 // INSERT_VECTOR_ELTs. 2261 // Note that this includes vectors of 2 elements by association. The 2262 // upper-most element is the "dominant" one, allowing us to use a splat to 2263 // "insert" the upper element, and an insert of the lower element at position 2264 // 0, which improves codegen. 2265 SDValue DominantValue; 2266 unsigned MostCommonCount = 0; 2267 DenseMap<SDValue, unsigned> ValueCounts; 2268 unsigned NumUndefElts = 2269 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2270 2271 // Track the number of scalar loads we know we'd be inserting, estimated as 2272 // any non-zero floating-point constant. Other kinds of element are either 2273 // already in registers or are materialized on demand. The threshold at which 2274 // a vector load is more desirable than several scalar materializion and 2275 // vector-insertion instructions is not known. 2276 unsigned NumScalarLoads = 0; 2277 2278 for (SDValue V : Op->op_values()) { 2279 if (V.isUndef()) 2280 continue; 2281 2282 ValueCounts.insert(std::make_pair(V, 0)); 2283 unsigned &Count = ValueCounts[V]; 2284 2285 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2286 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2287 2288 // Is this value dominant? In case of a tie, prefer the highest element as 2289 // it's cheaper to insert near the beginning of a vector than it is at the 2290 // end. 2291 if (++Count >= MostCommonCount) { 2292 DominantValue = V; 2293 MostCommonCount = Count; 2294 } 2295 } 2296 2297 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2298 unsigned NumDefElts = NumElts - NumUndefElts; 2299 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2300 2301 // Don't perform this optimization when optimizing for size, since 2302 // materializing elements and inserting them tends to cause code bloat. 2303 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2304 ((MostCommonCount > DominantValueCountThreshold) || 2305 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2306 // Start by splatting the most common element. 2307 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2308 2309 DenseSet<SDValue> Processed{DominantValue}; 2310 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2311 for (const auto &OpIdx : enumerate(Op->ops())) { 2312 const SDValue &V = OpIdx.value(); 2313 if (V.isUndef() || !Processed.insert(V).second) 2314 continue; 2315 if (ValueCounts[V] == 1) { 2316 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2317 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2318 } else { 2319 // Blend in all instances of this value using a VSELECT, using a 2320 // mask where each bit signals whether that element is the one 2321 // we're after. 2322 SmallVector<SDValue> Ops; 2323 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2324 return DAG.getConstant(V == V1, DL, XLenVT); 2325 }); 2326 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2327 DAG.getBuildVector(SelMaskTy, DL, Ops), 2328 DAG.getSplatBuildVector(VT, DL, V), Vec); 2329 } 2330 } 2331 2332 return Vec; 2333 } 2334 2335 return SDValue(); 2336 } 2337 2338 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2339 SDValue Lo, SDValue Hi, SDValue VL, 2340 SelectionDAG &DAG) { 2341 bool HasPassthru = Passthru && !Passthru.isUndef(); 2342 if (!HasPassthru && !Passthru) 2343 Passthru = DAG.getUNDEF(VT); 2344 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2345 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2346 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2347 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2348 // node in order to try and match RVV vector/scalar instructions. 2349 if ((LoC >> 31) == HiC) 2350 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2351 2352 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2353 // vmv.v.x whose EEW = 32 to lower it. 2354 auto *Const = dyn_cast<ConstantSDNode>(VL); 2355 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2356 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2357 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2358 // access the subtarget here now. 2359 auto InterVec = DAG.getNode( 2360 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2361 DAG.getRegister(RISCV::X0, MVT::i32)); 2362 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2363 } 2364 } 2365 2366 // Fall back to a stack store and stride x0 vector load. 2367 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2368 Hi, VL); 2369 } 2370 2371 // Called by type legalization to handle splat of i64 on RV32. 2372 // FIXME: We can optimize this when the type has sign or zero bits in one 2373 // of the halves. 2374 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2375 SDValue Scalar, SDValue VL, 2376 SelectionDAG &DAG) { 2377 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2378 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2379 DAG.getConstant(0, DL, MVT::i32)); 2380 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2381 DAG.getConstant(1, DL, MVT::i32)); 2382 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2383 } 2384 2385 // This function lowers a splat of a scalar operand Splat with the vector 2386 // length VL. It ensures the final sequence is type legal, which is useful when 2387 // lowering a splat after type legalization. 2388 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2389 MVT VT, SDLoc DL, SelectionDAG &DAG, 2390 const RISCVSubtarget &Subtarget) { 2391 bool HasPassthru = Passthru && !Passthru.isUndef(); 2392 if (!HasPassthru && !Passthru) 2393 Passthru = DAG.getUNDEF(VT); 2394 if (VT.isFloatingPoint()) { 2395 // If VL is 1, we could use vfmv.s.f. 2396 if (isOneConstant(VL)) 2397 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2398 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2399 } 2400 2401 MVT XLenVT = Subtarget.getXLenVT(); 2402 2403 // Simplest case is that the operand needs to be promoted to XLenVT. 2404 if (Scalar.getValueType().bitsLE(XLenVT)) { 2405 // If the operand is a constant, sign extend to increase our chances 2406 // of being able to use a .vi instruction. ANY_EXTEND would become a 2407 // a zero extend and the simm5 check in isel would fail. 2408 // FIXME: Should we ignore the upper bits in isel instead? 2409 unsigned ExtOpc = 2410 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2411 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2412 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2413 // If VL is 1 and the scalar value won't benefit from immediate, we could 2414 // use vmv.s.x. 2415 if (isOneConstant(VL) && 2416 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2417 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2418 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2419 } 2420 2421 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2422 "Unexpected scalar for splat lowering!"); 2423 2424 if (isOneConstant(VL) && isNullConstant(Scalar)) 2425 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2426 DAG.getConstant(0, DL, XLenVT), VL); 2427 2428 // Otherwise use the more complicated splatting algorithm. 2429 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2430 } 2431 2432 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2433 const RISCVSubtarget &Subtarget) { 2434 // We need to be able to widen elements to the next larger integer type. 2435 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2436 return false; 2437 2438 int Size = Mask.size(); 2439 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2440 2441 int Srcs[] = {-1, -1}; 2442 for (int i = 0; i != Size; ++i) { 2443 // Ignore undef elements. 2444 if (Mask[i] < 0) 2445 continue; 2446 2447 // Is this an even or odd element. 2448 int Pol = i % 2; 2449 2450 // Ensure we consistently use the same source for this element polarity. 2451 int Src = Mask[i] / Size; 2452 if (Srcs[Pol] < 0) 2453 Srcs[Pol] = Src; 2454 if (Srcs[Pol] != Src) 2455 return false; 2456 2457 // Make sure the element within the source is appropriate for this element 2458 // in the destination. 2459 int Elt = Mask[i] % Size; 2460 if (Elt != i / 2) 2461 return false; 2462 } 2463 2464 // We need to find a source for each polarity and they can't be the same. 2465 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2466 return false; 2467 2468 // Swap the sources if the second source was in the even polarity. 2469 SwapSources = Srcs[0] > Srcs[1]; 2470 2471 return true; 2472 } 2473 2474 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2475 /// and then extract the original number of elements from the rotated result. 2476 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2477 /// returned rotation amount is for a rotate right, where elements move from 2478 /// higher elements to lower elements. \p LoSrc indicates the first source 2479 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2480 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2481 /// 0 or 1 if a rotation is found. 2482 /// 2483 /// NOTE: We talk about rotate to the right which matches how bit shift and 2484 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2485 /// and the table below write vectors with the lowest elements on the left. 2486 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2487 int Size = Mask.size(); 2488 2489 // We need to detect various ways of spelling a rotation: 2490 // [11, 12, 13, 14, 15, 0, 1, 2] 2491 // [-1, 12, 13, 14, -1, -1, 1, -1] 2492 // [-1, -1, -1, -1, -1, -1, 1, 2] 2493 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2494 // [-1, 4, 5, 6, -1, -1, 9, -1] 2495 // [-1, 4, 5, 6, -1, -1, -1, -1] 2496 int Rotation = 0; 2497 LoSrc = -1; 2498 HiSrc = -1; 2499 for (int i = 0; i != Size; ++i) { 2500 int M = Mask[i]; 2501 if (M < 0) 2502 continue; 2503 2504 // Determine where a rotate vector would have started. 2505 int StartIdx = i - (M % Size); 2506 // The identity rotation isn't interesting, stop. 2507 if (StartIdx == 0) 2508 return -1; 2509 2510 // If we found the tail of a vector the rotation must be the missing 2511 // front. If we found the head of a vector, it must be how much of the 2512 // head. 2513 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2514 2515 if (Rotation == 0) 2516 Rotation = CandidateRotation; 2517 else if (Rotation != CandidateRotation) 2518 // The rotations don't match, so we can't match this mask. 2519 return -1; 2520 2521 // Compute which value this mask is pointing at. 2522 int MaskSrc = M < Size ? 0 : 1; 2523 2524 // Compute which of the two target values this index should be assigned to. 2525 // This reflects whether the high elements are remaining or the low elemnts 2526 // are remaining. 2527 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2528 2529 // Either set up this value if we've not encountered it before, or check 2530 // that it remains consistent. 2531 if (TargetSrc < 0) 2532 TargetSrc = MaskSrc; 2533 else if (TargetSrc != MaskSrc) 2534 // This may be a rotation, but it pulls from the inputs in some 2535 // unsupported interleaving. 2536 return -1; 2537 } 2538 2539 // Check that we successfully analyzed the mask, and normalize the results. 2540 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2541 assert((LoSrc >= 0 || HiSrc >= 0) && 2542 "Failed to find a rotated input vector!"); 2543 2544 return Rotation; 2545 } 2546 2547 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2548 const RISCVSubtarget &Subtarget) { 2549 SDValue V1 = Op.getOperand(0); 2550 SDValue V2 = Op.getOperand(1); 2551 SDLoc DL(Op); 2552 MVT XLenVT = Subtarget.getXLenVT(); 2553 MVT VT = Op.getSimpleValueType(); 2554 unsigned NumElts = VT.getVectorNumElements(); 2555 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2556 2557 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2558 2559 SDValue TrueMask, VL; 2560 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2561 2562 if (SVN->isSplat()) { 2563 const int Lane = SVN->getSplatIndex(); 2564 if (Lane >= 0) { 2565 MVT SVT = VT.getVectorElementType(); 2566 2567 // Turn splatted vector load into a strided load with an X0 stride. 2568 SDValue V = V1; 2569 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2570 // with undef. 2571 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2572 int Offset = Lane; 2573 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2574 int OpElements = 2575 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2576 V = V.getOperand(Offset / OpElements); 2577 Offset %= OpElements; 2578 } 2579 2580 // We need to ensure the load isn't atomic or volatile. 2581 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2582 auto *Ld = cast<LoadSDNode>(V); 2583 Offset *= SVT.getStoreSize(); 2584 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2585 TypeSize::Fixed(Offset), DL); 2586 2587 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2588 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2589 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2590 SDValue IntID = 2591 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2592 SDValue Ops[] = {Ld->getChain(), 2593 IntID, 2594 DAG.getUNDEF(ContainerVT), 2595 NewAddr, 2596 DAG.getRegister(RISCV::X0, XLenVT), 2597 VL}; 2598 SDValue NewLoad = DAG.getMemIntrinsicNode( 2599 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2600 DAG.getMachineFunction().getMachineMemOperand( 2601 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2602 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2603 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2604 } 2605 2606 // Otherwise use a scalar load and splat. This will give the best 2607 // opportunity to fold a splat into the operation. ISel can turn it into 2608 // the x0 strided load if we aren't able to fold away the select. 2609 if (SVT.isFloatingPoint()) 2610 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2611 Ld->getPointerInfo().getWithOffset(Offset), 2612 Ld->getOriginalAlign(), 2613 Ld->getMemOperand()->getFlags()); 2614 else 2615 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2616 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2617 Ld->getOriginalAlign(), 2618 Ld->getMemOperand()->getFlags()); 2619 DAG.makeEquivalentMemoryOrdering(Ld, V); 2620 2621 unsigned Opc = 2622 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2623 SDValue Splat = 2624 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2625 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2626 } 2627 2628 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2629 assert(Lane < (int)NumElts && "Unexpected lane!"); 2630 SDValue Gather = 2631 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2632 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2633 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2634 } 2635 } 2636 2637 ArrayRef<int> Mask = SVN->getMask(); 2638 2639 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2640 // be undef which can be handled with a single SLIDEDOWN/UP. 2641 int LoSrc, HiSrc; 2642 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2643 if (Rotation > 0) { 2644 SDValue LoV, HiV; 2645 if (LoSrc >= 0) { 2646 LoV = LoSrc == 0 ? V1 : V2; 2647 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2648 } 2649 if (HiSrc >= 0) { 2650 HiV = HiSrc == 0 ? V1 : V2; 2651 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2652 } 2653 2654 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2655 // to slide LoV up by (NumElts - Rotation). 2656 unsigned InvRotate = NumElts - Rotation; 2657 2658 SDValue Res = DAG.getUNDEF(ContainerVT); 2659 if (HiV) { 2660 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2661 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2662 // causes multiple vsetvlis in some test cases such as lowering 2663 // reduce.mul 2664 SDValue DownVL = VL; 2665 if (LoV) 2666 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2667 Res = 2668 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2669 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2670 } 2671 if (LoV) 2672 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2673 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2674 2675 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2676 } 2677 2678 // Detect an interleave shuffle and lower to 2679 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2680 bool SwapSources; 2681 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2682 // Swap sources if needed. 2683 if (SwapSources) 2684 std::swap(V1, V2); 2685 2686 // Extract the lower half of the vectors. 2687 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2688 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2689 DAG.getConstant(0, DL, XLenVT)); 2690 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2691 DAG.getConstant(0, DL, XLenVT)); 2692 2693 // Double the element width and halve the number of elements in an int type. 2694 unsigned EltBits = VT.getScalarSizeInBits(); 2695 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2696 MVT WideIntVT = 2697 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2698 // Convert this to a scalable vector. We need to base this on the 2699 // destination size to ensure there's always a type with a smaller LMUL. 2700 MVT WideIntContainerVT = 2701 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2702 2703 // Convert sources to scalable vectors with the same element count as the 2704 // larger type. 2705 MVT HalfContainerVT = MVT::getVectorVT( 2706 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2707 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2708 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2709 2710 // Cast sources to integer. 2711 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2712 MVT IntHalfVT = 2713 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2714 V1 = DAG.getBitcast(IntHalfVT, V1); 2715 V2 = DAG.getBitcast(IntHalfVT, V2); 2716 2717 // Freeze V2 since we use it twice and we need to be sure that the add and 2718 // multiply see the same value. 2719 V2 = DAG.getFreeze(V2); 2720 2721 // Recreate TrueMask using the widened type's element count. 2722 MVT MaskVT = 2723 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2724 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2725 2726 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2727 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2728 V2, TrueMask, VL); 2729 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2730 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2731 DAG.getUNDEF(IntHalfVT), 2732 DAG.getAllOnesConstant(DL, XLenVT)); 2733 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2734 V2, Multiplier, TrueMask, VL); 2735 // Add the new copies to our previous addition giving us 2^eltbits copies of 2736 // V2. This is equivalent to shifting V2 left by eltbits. This should 2737 // combine with the vwmulu.vv above to form vwmaccu.vv. 2738 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2739 TrueMask, VL); 2740 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2741 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2742 // vector VT. 2743 ContainerVT = 2744 MVT::getVectorVT(VT.getVectorElementType(), 2745 WideIntContainerVT.getVectorElementCount() * 2); 2746 Add = DAG.getBitcast(ContainerVT, Add); 2747 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2748 } 2749 2750 // Detect shuffles which can be re-expressed as vector selects; these are 2751 // shuffles in which each element in the destination is taken from an element 2752 // at the corresponding index in either source vectors. 2753 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2754 int MaskIndex = MaskIdx.value(); 2755 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2756 }); 2757 2758 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2759 2760 SmallVector<SDValue> MaskVals; 2761 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2762 // merged with a second vrgather. 2763 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2764 2765 // By default we preserve the original operand order, and use a mask to 2766 // select LHS as true and RHS as false. However, since RVV vector selects may 2767 // feature splats but only on the LHS, we may choose to invert our mask and 2768 // instead select between RHS and LHS. 2769 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2770 bool InvertMask = IsSelect == SwapOps; 2771 2772 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2773 // half. 2774 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2775 2776 // Now construct the mask that will be used by the vselect or blended 2777 // vrgather operation. For vrgathers, construct the appropriate indices into 2778 // each vector. 2779 for (int MaskIndex : Mask) { 2780 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2781 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2782 if (!IsSelect) { 2783 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2784 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2785 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2786 : DAG.getUNDEF(XLenVT)); 2787 GatherIndicesRHS.push_back( 2788 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2789 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2790 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2791 ++LHSIndexCounts[MaskIndex]; 2792 if (!IsLHSOrUndefIndex) 2793 ++RHSIndexCounts[MaskIndex - NumElts]; 2794 } 2795 } 2796 2797 if (SwapOps) { 2798 std::swap(V1, V2); 2799 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2800 } 2801 2802 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2803 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2804 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2805 2806 if (IsSelect) 2807 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2808 2809 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2810 // On such a large vector we're unable to use i8 as the index type. 2811 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2812 // may involve vector splitting if we're already at LMUL=8, or our 2813 // user-supplied maximum fixed-length LMUL. 2814 return SDValue(); 2815 } 2816 2817 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2818 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2819 MVT IndexVT = VT.changeTypeToInteger(); 2820 // Since we can't introduce illegal index types at this stage, use i16 and 2821 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2822 // than XLenVT. 2823 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2824 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2825 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2826 } 2827 2828 MVT IndexContainerVT = 2829 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2830 2831 SDValue Gather; 2832 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2833 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2834 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2835 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2836 Subtarget); 2837 } else { 2838 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2839 // If only one index is used, we can use a "splat" vrgather. 2840 // TODO: We can splat the most-common index and fix-up any stragglers, if 2841 // that's beneficial. 2842 if (LHSIndexCounts.size() == 1) { 2843 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2844 Gather = 2845 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2846 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2847 } else { 2848 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2849 LHSIndices = 2850 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2851 2852 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2853 TrueMask, VL); 2854 } 2855 } 2856 2857 // If a second vector operand is used by this shuffle, blend it in with an 2858 // additional vrgather. 2859 if (!V2.isUndef()) { 2860 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2861 // If only one index is used, we can use a "splat" vrgather. 2862 // TODO: We can splat the most-common index and fix-up any stragglers, if 2863 // that's beneficial. 2864 if (RHSIndexCounts.size() == 1) { 2865 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2866 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2867 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2868 } else { 2869 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2870 RHSIndices = 2871 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2872 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2873 VL); 2874 } 2875 2876 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2877 SelectMask = 2878 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2879 2880 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2881 Gather, VL); 2882 } 2883 2884 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2885 } 2886 2887 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2888 // Support splats for any type. These should type legalize well. 2889 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2890 return true; 2891 2892 // Only support legal VTs for other shuffles for now. 2893 if (!isTypeLegal(VT)) 2894 return false; 2895 2896 MVT SVT = VT.getSimpleVT(); 2897 2898 bool SwapSources; 2899 int LoSrc, HiSrc; 2900 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2901 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2902 } 2903 2904 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2905 SDLoc DL, SelectionDAG &DAG, 2906 const RISCVSubtarget &Subtarget) { 2907 if (VT.isScalableVector()) 2908 return DAG.getFPExtendOrRound(Op, DL, VT); 2909 assert(VT.isFixedLengthVector() && 2910 "Unexpected value type for RVV FP extend/round lowering"); 2911 SDValue Mask, VL; 2912 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2913 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2914 ? RISCVISD::FP_EXTEND_VL 2915 : RISCVISD::FP_ROUND_VL; 2916 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2917 } 2918 2919 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2920 // the exponent. 2921 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2922 MVT VT = Op.getSimpleValueType(); 2923 unsigned EltSize = VT.getScalarSizeInBits(); 2924 SDValue Src = Op.getOperand(0); 2925 SDLoc DL(Op); 2926 2927 // We need a FP type that can represent the value. 2928 // TODO: Use f16 for i8 when possible? 2929 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2930 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2931 2932 // Legal types should have been checked in the RISCVTargetLowering 2933 // constructor. 2934 // TODO: Splitting may make sense in some cases. 2935 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2936 "Expected legal float type!"); 2937 2938 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2939 // The trailing zero count is equal to log2 of this single bit value. 2940 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2941 SDValue Neg = 2942 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2943 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2944 } 2945 2946 // We have a legal FP type, convert to it. 2947 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2948 // Bitcast to integer and shift the exponent to the LSB. 2949 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2950 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2951 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2952 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2953 DAG.getConstant(ShiftAmt, DL, IntVT)); 2954 // Truncate back to original type to allow vnsrl. 2955 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2956 // The exponent contains log2 of the value in biased form. 2957 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2958 2959 // For trailing zeros, we just need to subtract the bias. 2960 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2961 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2962 DAG.getConstant(ExponentBias, DL, VT)); 2963 2964 // For leading zeros, we need to remove the bias and convert from log2 to 2965 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2966 unsigned Adjust = ExponentBias + (EltSize - 1); 2967 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2968 } 2969 2970 // While RVV has alignment restrictions, we should always be able to load as a 2971 // legal equivalently-sized byte-typed vector instead. This method is 2972 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2973 // the load is already correctly-aligned, it returns SDValue(). 2974 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2975 SelectionDAG &DAG) const { 2976 auto *Load = cast<LoadSDNode>(Op); 2977 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2978 2979 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2980 Load->getMemoryVT(), 2981 *Load->getMemOperand())) 2982 return SDValue(); 2983 2984 SDLoc DL(Op); 2985 MVT VT = Op.getSimpleValueType(); 2986 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2987 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2988 "Unexpected unaligned RVV load type"); 2989 MVT NewVT = 2990 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2991 assert(NewVT.isValid() && 2992 "Expecting equally-sized RVV vector types to be legal"); 2993 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2994 Load->getPointerInfo(), Load->getOriginalAlign(), 2995 Load->getMemOperand()->getFlags()); 2996 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2997 } 2998 2999 // While RVV has alignment restrictions, we should always be able to store as a 3000 // legal equivalently-sized byte-typed vector instead. This method is 3001 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3002 // returns SDValue() if the store is already correctly aligned. 3003 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3004 SelectionDAG &DAG) const { 3005 auto *Store = cast<StoreSDNode>(Op); 3006 assert(Store && Store->getValue().getValueType().isVector() && 3007 "Expected vector store"); 3008 3009 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3010 Store->getMemoryVT(), 3011 *Store->getMemOperand())) 3012 return SDValue(); 3013 3014 SDLoc DL(Op); 3015 SDValue StoredVal = Store->getValue(); 3016 MVT VT = StoredVal.getSimpleValueType(); 3017 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3018 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3019 "Unexpected unaligned RVV store type"); 3020 MVT NewVT = 3021 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3022 assert(NewVT.isValid() && 3023 "Expecting equally-sized RVV vector types to be legal"); 3024 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3025 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3026 Store->getPointerInfo(), Store->getOriginalAlign(), 3027 Store->getMemOperand()->getFlags()); 3028 } 3029 3030 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3031 SelectionDAG &DAG) const { 3032 switch (Op.getOpcode()) { 3033 default: 3034 report_fatal_error("unimplemented operand"); 3035 case ISD::GlobalAddress: 3036 return lowerGlobalAddress(Op, DAG); 3037 case ISD::BlockAddress: 3038 return lowerBlockAddress(Op, DAG); 3039 case ISD::ConstantPool: 3040 return lowerConstantPool(Op, DAG); 3041 case ISD::JumpTable: 3042 return lowerJumpTable(Op, DAG); 3043 case ISD::GlobalTLSAddress: 3044 return lowerGlobalTLSAddress(Op, DAG); 3045 case ISD::SELECT: 3046 return lowerSELECT(Op, DAG); 3047 case ISD::BRCOND: 3048 return lowerBRCOND(Op, DAG); 3049 case ISD::VASTART: 3050 return lowerVASTART(Op, DAG); 3051 case ISD::FRAMEADDR: 3052 return lowerFRAMEADDR(Op, DAG); 3053 case ISD::RETURNADDR: 3054 return lowerRETURNADDR(Op, DAG); 3055 case ISD::SHL_PARTS: 3056 return lowerShiftLeftParts(Op, DAG); 3057 case ISD::SRA_PARTS: 3058 return lowerShiftRightParts(Op, DAG, true); 3059 case ISD::SRL_PARTS: 3060 return lowerShiftRightParts(Op, DAG, false); 3061 case ISD::BITCAST: { 3062 SDLoc DL(Op); 3063 EVT VT = Op.getValueType(); 3064 SDValue Op0 = Op.getOperand(0); 3065 EVT Op0VT = Op0.getValueType(); 3066 MVT XLenVT = Subtarget.getXLenVT(); 3067 if (VT.isFixedLengthVector()) { 3068 // We can handle fixed length vector bitcasts with a simple replacement 3069 // in isel. 3070 if (Op0VT.isFixedLengthVector()) 3071 return Op; 3072 // When bitcasting from scalar to fixed-length vector, insert the scalar 3073 // into a one-element vector of the result type, and perform a vector 3074 // bitcast. 3075 if (!Op0VT.isVector()) { 3076 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3077 if (!isTypeLegal(BVT)) 3078 return SDValue(); 3079 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3080 DAG.getUNDEF(BVT), Op0, 3081 DAG.getConstant(0, DL, XLenVT))); 3082 } 3083 return SDValue(); 3084 } 3085 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3086 // thus: bitcast the vector to a one-element vector type whose element type 3087 // is the same as the result type, and extract the first element. 3088 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3089 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3090 if (!isTypeLegal(BVT)) 3091 return SDValue(); 3092 SDValue BVec = DAG.getBitcast(BVT, Op0); 3093 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3094 DAG.getConstant(0, DL, XLenVT)); 3095 } 3096 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3097 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3098 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3099 return FPConv; 3100 } 3101 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3102 Subtarget.hasStdExtF()) { 3103 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3104 SDValue FPConv = 3105 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3106 return FPConv; 3107 } 3108 return SDValue(); 3109 } 3110 case ISD::INTRINSIC_WO_CHAIN: 3111 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3112 case ISD::INTRINSIC_W_CHAIN: 3113 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3114 case ISD::INTRINSIC_VOID: 3115 return LowerINTRINSIC_VOID(Op, DAG); 3116 case ISD::BSWAP: 3117 case ISD::BITREVERSE: { 3118 MVT VT = Op.getSimpleValueType(); 3119 SDLoc DL(Op); 3120 if (Subtarget.hasStdExtZbp()) { 3121 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3122 // Start with the maximum immediate value which is the bitwidth - 1. 3123 unsigned Imm = VT.getSizeInBits() - 1; 3124 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3125 if (Op.getOpcode() == ISD::BSWAP) 3126 Imm &= ~0x7U; 3127 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3128 DAG.getConstant(Imm, DL, VT)); 3129 } 3130 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3131 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3132 // Expand bitreverse to a bswap(rev8) followed by brev8. 3133 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3134 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3135 // as brev8 by an isel pattern. 3136 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3137 DAG.getConstant(7, DL, VT)); 3138 } 3139 case ISD::FSHL: 3140 case ISD::FSHR: { 3141 MVT VT = Op.getSimpleValueType(); 3142 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3143 SDLoc DL(Op); 3144 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3145 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3146 // accidentally setting the extra bit. 3147 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3148 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3149 DAG.getConstant(ShAmtWidth, DL, VT)); 3150 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3151 // instruction use different orders. fshl will return its first operand for 3152 // shift of zero, fshr will return its second operand. fsl and fsr both 3153 // return rs1 so the ISD nodes need to have different operand orders. 3154 // Shift amount is in rs2. 3155 SDValue Op0 = Op.getOperand(0); 3156 SDValue Op1 = Op.getOperand(1); 3157 unsigned Opc = RISCVISD::FSL; 3158 if (Op.getOpcode() == ISD::FSHR) { 3159 std::swap(Op0, Op1); 3160 Opc = RISCVISD::FSR; 3161 } 3162 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3163 } 3164 case ISD::TRUNCATE: { 3165 SDLoc DL(Op); 3166 MVT VT = Op.getSimpleValueType(); 3167 // Only custom-lower vector truncates 3168 if (!VT.isVector()) 3169 return Op; 3170 3171 // Truncates to mask types are handled differently 3172 if (VT.getVectorElementType() == MVT::i1) 3173 return lowerVectorMaskTrunc(Op, DAG); 3174 3175 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3176 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3177 // truncate by one power of two at a time. 3178 MVT DstEltVT = VT.getVectorElementType(); 3179 3180 SDValue Src = Op.getOperand(0); 3181 MVT SrcVT = Src.getSimpleValueType(); 3182 MVT SrcEltVT = SrcVT.getVectorElementType(); 3183 3184 assert(DstEltVT.bitsLT(SrcEltVT) && 3185 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3186 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3187 "Unexpected vector truncate lowering"); 3188 3189 MVT ContainerVT = SrcVT; 3190 if (SrcVT.isFixedLengthVector()) { 3191 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3192 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3193 } 3194 3195 SDValue Result = Src; 3196 SDValue Mask, VL; 3197 std::tie(Mask, VL) = 3198 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3199 LLVMContext &Context = *DAG.getContext(); 3200 const ElementCount Count = ContainerVT.getVectorElementCount(); 3201 do { 3202 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3203 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3204 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3205 Mask, VL); 3206 } while (SrcEltVT != DstEltVT); 3207 3208 if (SrcVT.isFixedLengthVector()) 3209 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3210 3211 return Result; 3212 } 3213 case ISD::ANY_EXTEND: 3214 case ISD::ZERO_EXTEND: 3215 if (Op.getOperand(0).getValueType().isVector() && 3216 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3217 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3218 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3219 case ISD::SIGN_EXTEND: 3220 if (Op.getOperand(0).getValueType().isVector() && 3221 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3222 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3223 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3224 case ISD::SPLAT_VECTOR_PARTS: 3225 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3226 case ISD::INSERT_VECTOR_ELT: 3227 return lowerINSERT_VECTOR_ELT(Op, DAG); 3228 case ISD::EXTRACT_VECTOR_ELT: 3229 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3230 case ISD::VSCALE: { 3231 MVT VT = Op.getSimpleValueType(); 3232 SDLoc DL(Op); 3233 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3234 // We define our scalable vector types for lmul=1 to use a 64 bit known 3235 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3236 // vscale as VLENB / 8. 3237 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3238 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3239 report_fatal_error("Support for VLEN==32 is incomplete."); 3240 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3241 // We assume VLENB is a multiple of 8. We manually choose the best shift 3242 // here because SimplifyDemandedBits isn't always able to simplify it. 3243 uint64_t Val = Op.getConstantOperandVal(0); 3244 if (isPowerOf2_64(Val)) { 3245 uint64_t Log2 = Log2_64(Val); 3246 if (Log2 < 3) 3247 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3248 DAG.getConstant(3 - Log2, DL, VT)); 3249 if (Log2 > 3) 3250 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3251 DAG.getConstant(Log2 - 3, DL, VT)); 3252 return VLENB; 3253 } 3254 // If the multiplier is a multiple of 8, scale it down to avoid needing 3255 // to shift the VLENB value. 3256 if ((Val % 8) == 0) 3257 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3258 DAG.getConstant(Val / 8, DL, VT)); 3259 } 3260 3261 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3262 DAG.getConstant(3, DL, VT)); 3263 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3264 } 3265 case ISD::FPOWI: { 3266 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3267 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3268 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3269 Op.getOperand(1).getValueType() == MVT::i32) { 3270 SDLoc DL(Op); 3271 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3272 SDValue Powi = 3273 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3274 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3275 DAG.getIntPtrConstant(0, DL)); 3276 } 3277 return SDValue(); 3278 } 3279 case ISD::FP_EXTEND: { 3280 // RVV can only do fp_extend to types double the size as the source. We 3281 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3282 // via f32. 3283 SDLoc DL(Op); 3284 MVT VT = Op.getSimpleValueType(); 3285 SDValue Src = Op.getOperand(0); 3286 MVT SrcVT = Src.getSimpleValueType(); 3287 3288 // Prepare any fixed-length vector operands. 3289 MVT ContainerVT = VT; 3290 if (SrcVT.isFixedLengthVector()) { 3291 ContainerVT = getContainerForFixedLengthVector(VT); 3292 MVT SrcContainerVT = 3293 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3294 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3295 } 3296 3297 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3298 SrcVT.getVectorElementType() != MVT::f16) { 3299 // For scalable vectors, we only need to close the gap between 3300 // vXf16->vXf64. 3301 if (!VT.isFixedLengthVector()) 3302 return Op; 3303 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3304 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3305 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3306 } 3307 3308 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3309 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3310 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3311 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3312 3313 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3314 DL, DAG, Subtarget); 3315 if (VT.isFixedLengthVector()) 3316 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3317 return Extend; 3318 } 3319 case ISD::FP_ROUND: { 3320 // RVV can only do fp_round to types half the size as the source. We 3321 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3322 // conversion instruction. 3323 SDLoc DL(Op); 3324 MVT VT = Op.getSimpleValueType(); 3325 SDValue Src = Op.getOperand(0); 3326 MVT SrcVT = Src.getSimpleValueType(); 3327 3328 // Prepare any fixed-length vector operands. 3329 MVT ContainerVT = VT; 3330 if (VT.isFixedLengthVector()) { 3331 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3332 ContainerVT = 3333 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3334 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3335 } 3336 3337 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3338 SrcVT.getVectorElementType() != MVT::f64) { 3339 // For scalable vectors, we only need to close the gap between 3340 // vXf64<->vXf16. 3341 if (!VT.isFixedLengthVector()) 3342 return Op; 3343 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3344 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3345 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3346 } 3347 3348 SDValue Mask, VL; 3349 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3350 3351 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3352 SDValue IntermediateRound = 3353 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3354 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3355 DL, DAG, Subtarget); 3356 3357 if (VT.isFixedLengthVector()) 3358 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3359 return Round; 3360 } 3361 case ISD::FP_TO_SINT: 3362 case ISD::FP_TO_UINT: 3363 case ISD::SINT_TO_FP: 3364 case ISD::UINT_TO_FP: { 3365 // RVV can only do fp<->int conversions to types half/double the size as 3366 // the source. We custom-lower any conversions that do two hops into 3367 // sequences. 3368 MVT VT = Op.getSimpleValueType(); 3369 if (!VT.isVector()) 3370 return Op; 3371 SDLoc DL(Op); 3372 SDValue Src = Op.getOperand(0); 3373 MVT EltVT = VT.getVectorElementType(); 3374 MVT SrcVT = Src.getSimpleValueType(); 3375 MVT SrcEltVT = SrcVT.getVectorElementType(); 3376 unsigned EltSize = EltVT.getSizeInBits(); 3377 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3378 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3379 "Unexpected vector element types"); 3380 3381 bool IsInt2FP = SrcEltVT.isInteger(); 3382 // Widening conversions 3383 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3384 if (IsInt2FP) { 3385 // Do a regular integer sign/zero extension then convert to float. 3386 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3387 VT.getVectorElementCount()); 3388 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3389 ? ISD::ZERO_EXTEND 3390 : ISD::SIGN_EXTEND; 3391 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3392 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3393 } 3394 // FP2Int 3395 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3396 // Do one doubling fp_extend then complete the operation by converting 3397 // to int. 3398 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3399 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3400 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3401 } 3402 3403 // Narrowing conversions 3404 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3405 if (IsInt2FP) { 3406 // One narrowing int_to_fp, then an fp_round. 3407 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3408 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3409 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3410 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3411 } 3412 // FP2Int 3413 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3414 // representable by the integer, the result is poison. 3415 MVT IVecVT = 3416 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3417 VT.getVectorElementCount()); 3418 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3419 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3420 } 3421 3422 // Scalable vectors can exit here. Patterns will handle equally-sized 3423 // conversions halving/doubling ones. 3424 if (!VT.isFixedLengthVector()) 3425 return Op; 3426 3427 // For fixed-length vectors we lower to a custom "VL" node. 3428 unsigned RVVOpc = 0; 3429 switch (Op.getOpcode()) { 3430 default: 3431 llvm_unreachable("Impossible opcode"); 3432 case ISD::FP_TO_SINT: 3433 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3434 break; 3435 case ISD::FP_TO_UINT: 3436 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3437 break; 3438 case ISD::SINT_TO_FP: 3439 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3440 break; 3441 case ISD::UINT_TO_FP: 3442 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3443 break; 3444 } 3445 3446 MVT ContainerVT, SrcContainerVT; 3447 // Derive the reference container type from the larger vector type. 3448 if (SrcEltSize > EltSize) { 3449 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3450 ContainerVT = 3451 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3452 } else { 3453 ContainerVT = getContainerForFixedLengthVector(VT); 3454 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3455 } 3456 3457 SDValue Mask, VL; 3458 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3459 3460 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3461 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3462 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3463 } 3464 case ISD::FP_TO_SINT_SAT: 3465 case ISD::FP_TO_UINT_SAT: 3466 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3467 case ISD::FTRUNC: 3468 case ISD::FCEIL: 3469 case ISD::FFLOOR: 3470 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3471 case ISD::FROUND: 3472 return lowerFROUND(Op, DAG); 3473 case ISD::VECREDUCE_ADD: 3474 case ISD::VECREDUCE_UMAX: 3475 case ISD::VECREDUCE_SMAX: 3476 case ISD::VECREDUCE_UMIN: 3477 case ISD::VECREDUCE_SMIN: 3478 return lowerVECREDUCE(Op, DAG); 3479 case ISD::VECREDUCE_AND: 3480 case ISD::VECREDUCE_OR: 3481 case ISD::VECREDUCE_XOR: 3482 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3483 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3484 return lowerVECREDUCE(Op, DAG); 3485 case ISD::VECREDUCE_FADD: 3486 case ISD::VECREDUCE_SEQ_FADD: 3487 case ISD::VECREDUCE_FMIN: 3488 case ISD::VECREDUCE_FMAX: 3489 return lowerFPVECREDUCE(Op, DAG); 3490 case ISD::VP_REDUCE_ADD: 3491 case ISD::VP_REDUCE_UMAX: 3492 case ISD::VP_REDUCE_SMAX: 3493 case ISD::VP_REDUCE_UMIN: 3494 case ISD::VP_REDUCE_SMIN: 3495 case ISD::VP_REDUCE_FADD: 3496 case ISD::VP_REDUCE_SEQ_FADD: 3497 case ISD::VP_REDUCE_FMIN: 3498 case ISD::VP_REDUCE_FMAX: 3499 return lowerVPREDUCE(Op, DAG); 3500 case ISD::VP_REDUCE_AND: 3501 case ISD::VP_REDUCE_OR: 3502 case ISD::VP_REDUCE_XOR: 3503 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3504 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3505 return lowerVPREDUCE(Op, DAG); 3506 case ISD::INSERT_SUBVECTOR: 3507 return lowerINSERT_SUBVECTOR(Op, DAG); 3508 case ISD::EXTRACT_SUBVECTOR: 3509 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3510 case ISD::STEP_VECTOR: 3511 return lowerSTEP_VECTOR(Op, DAG); 3512 case ISD::VECTOR_REVERSE: 3513 return lowerVECTOR_REVERSE(Op, DAG); 3514 case ISD::VECTOR_SPLICE: 3515 return lowerVECTOR_SPLICE(Op, DAG); 3516 case ISD::BUILD_VECTOR: 3517 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3518 case ISD::SPLAT_VECTOR: 3519 if (Op.getValueType().getVectorElementType() == MVT::i1) 3520 return lowerVectorMaskSplat(Op, DAG); 3521 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3522 case ISD::VECTOR_SHUFFLE: 3523 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3524 case ISD::CONCAT_VECTORS: { 3525 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3526 // better than going through the stack, as the default expansion does. 3527 SDLoc DL(Op); 3528 MVT VT = Op.getSimpleValueType(); 3529 unsigned NumOpElts = 3530 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3531 SDValue Vec = DAG.getUNDEF(VT); 3532 for (const auto &OpIdx : enumerate(Op->ops())) { 3533 SDValue SubVec = OpIdx.value(); 3534 // Don't insert undef subvectors. 3535 if (SubVec.isUndef()) 3536 continue; 3537 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3538 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3539 } 3540 return Vec; 3541 } 3542 case ISD::LOAD: 3543 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3544 return V; 3545 if (Op.getValueType().isFixedLengthVector()) 3546 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3547 return Op; 3548 case ISD::STORE: 3549 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3550 return V; 3551 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3552 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3553 return Op; 3554 case ISD::MLOAD: 3555 case ISD::VP_LOAD: 3556 return lowerMaskedLoad(Op, DAG); 3557 case ISD::MSTORE: 3558 case ISD::VP_STORE: 3559 return lowerMaskedStore(Op, DAG); 3560 case ISD::SETCC: 3561 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3562 case ISD::ADD: 3563 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3564 case ISD::SUB: 3565 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3566 case ISD::MUL: 3567 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3568 case ISD::MULHS: 3569 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3570 case ISD::MULHU: 3571 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3572 case ISD::AND: 3573 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3574 RISCVISD::AND_VL); 3575 case ISD::OR: 3576 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3577 RISCVISD::OR_VL); 3578 case ISD::XOR: 3579 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3580 RISCVISD::XOR_VL); 3581 case ISD::SDIV: 3582 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3583 case ISD::SREM: 3584 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3585 case ISD::UDIV: 3586 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3587 case ISD::UREM: 3588 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3589 case ISD::SHL: 3590 case ISD::SRA: 3591 case ISD::SRL: 3592 if (Op.getSimpleValueType().isFixedLengthVector()) 3593 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3594 // This can be called for an i32 shift amount that needs to be promoted. 3595 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3596 "Unexpected custom legalisation"); 3597 return SDValue(); 3598 case ISD::SADDSAT: 3599 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3600 case ISD::UADDSAT: 3601 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3602 case ISD::SSUBSAT: 3603 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3604 case ISD::USUBSAT: 3605 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3606 case ISD::FADD: 3607 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3608 case ISD::FSUB: 3609 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3610 case ISD::FMUL: 3611 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3612 case ISD::FDIV: 3613 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3614 case ISD::FNEG: 3615 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3616 case ISD::FABS: 3617 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3618 case ISD::FSQRT: 3619 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3620 case ISD::FMA: 3621 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3622 case ISD::SMIN: 3623 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3624 case ISD::SMAX: 3625 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3626 case ISD::UMIN: 3627 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3628 case ISD::UMAX: 3629 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3630 case ISD::FMINNUM: 3631 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3632 case ISD::FMAXNUM: 3633 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3634 case ISD::ABS: 3635 return lowerABS(Op, DAG); 3636 case ISD::CTLZ_ZERO_UNDEF: 3637 case ISD::CTTZ_ZERO_UNDEF: 3638 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3639 case ISD::VSELECT: 3640 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3641 case ISD::FCOPYSIGN: 3642 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3643 case ISD::MGATHER: 3644 case ISD::VP_GATHER: 3645 return lowerMaskedGather(Op, DAG); 3646 case ISD::MSCATTER: 3647 case ISD::VP_SCATTER: 3648 return lowerMaskedScatter(Op, DAG); 3649 case ISD::FLT_ROUNDS_: 3650 return lowerGET_ROUNDING(Op, DAG); 3651 case ISD::SET_ROUNDING: 3652 return lowerSET_ROUNDING(Op, DAG); 3653 case ISD::VP_SELECT: 3654 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3655 case ISD::VP_MERGE: 3656 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3657 case ISD::VP_ADD: 3658 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3659 case ISD::VP_SUB: 3660 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3661 case ISD::VP_MUL: 3662 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3663 case ISD::VP_SDIV: 3664 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3665 case ISD::VP_UDIV: 3666 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3667 case ISD::VP_SREM: 3668 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3669 case ISD::VP_UREM: 3670 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3671 case ISD::VP_AND: 3672 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3673 case ISD::VP_OR: 3674 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3675 case ISD::VP_XOR: 3676 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3677 case ISD::VP_ASHR: 3678 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3679 case ISD::VP_LSHR: 3680 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3681 case ISD::VP_SHL: 3682 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3683 case ISD::VP_FADD: 3684 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3685 case ISD::VP_FSUB: 3686 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3687 case ISD::VP_FMUL: 3688 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3689 case ISD::VP_FDIV: 3690 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3691 case ISD::VP_FNEG: 3692 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3693 case ISD::VP_FMA: 3694 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3695 } 3696 } 3697 3698 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3699 SelectionDAG &DAG, unsigned Flags) { 3700 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3701 } 3702 3703 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3704 SelectionDAG &DAG, unsigned Flags) { 3705 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3706 Flags); 3707 } 3708 3709 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3710 SelectionDAG &DAG, unsigned Flags) { 3711 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3712 N->getOffset(), Flags); 3713 } 3714 3715 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3716 SelectionDAG &DAG, unsigned Flags) { 3717 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3718 } 3719 3720 template <class NodeTy> 3721 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3722 bool IsLocal) const { 3723 SDLoc DL(N); 3724 EVT Ty = getPointerTy(DAG.getDataLayout()); 3725 3726 if (isPositionIndependent()) { 3727 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3728 if (IsLocal) 3729 // Use PC-relative addressing to access the symbol. This generates the 3730 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3731 // %pcrel_lo(auipc)). 3732 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3733 3734 // Use PC-relative addressing to access the GOT for this symbol, then load 3735 // the address from the GOT. This generates the pattern (PseudoLA sym), 3736 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3737 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3738 } 3739 3740 switch (getTargetMachine().getCodeModel()) { 3741 default: 3742 report_fatal_error("Unsupported code model for lowering"); 3743 case CodeModel::Small: { 3744 // Generate a sequence for accessing addresses within the first 2 GiB of 3745 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3746 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3747 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3748 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3749 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3750 } 3751 case CodeModel::Medium: { 3752 // Generate a sequence for accessing addresses within any 2GiB range within 3753 // the address space. This generates the pattern (PseudoLLA sym), which 3754 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3755 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3756 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3757 } 3758 } 3759 } 3760 3761 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3762 SelectionDAG &DAG) const { 3763 SDLoc DL(Op); 3764 EVT Ty = Op.getValueType(); 3765 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3766 int64_t Offset = N->getOffset(); 3767 MVT XLenVT = Subtarget.getXLenVT(); 3768 3769 const GlobalValue *GV = N->getGlobal(); 3770 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3771 SDValue Addr = getAddr(N, DAG, IsLocal); 3772 3773 // In order to maximise the opportunity for common subexpression elimination, 3774 // emit a separate ADD node for the global address offset instead of folding 3775 // it in the global address node. Later peephole optimisations may choose to 3776 // fold it back in when profitable. 3777 if (Offset != 0) 3778 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3779 DAG.getConstant(Offset, DL, XLenVT)); 3780 return Addr; 3781 } 3782 3783 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3784 SelectionDAG &DAG) const { 3785 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3786 3787 return getAddr(N, DAG); 3788 } 3789 3790 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3791 SelectionDAG &DAG) const { 3792 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3793 3794 return getAddr(N, DAG); 3795 } 3796 3797 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3798 SelectionDAG &DAG) const { 3799 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3800 3801 return getAddr(N, DAG); 3802 } 3803 3804 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3805 SelectionDAG &DAG, 3806 bool UseGOT) const { 3807 SDLoc DL(N); 3808 EVT Ty = getPointerTy(DAG.getDataLayout()); 3809 const GlobalValue *GV = N->getGlobal(); 3810 MVT XLenVT = Subtarget.getXLenVT(); 3811 3812 if (UseGOT) { 3813 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3814 // load the address from the GOT and add the thread pointer. This generates 3815 // the pattern (PseudoLA_TLS_IE sym), which expands to 3816 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3817 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3818 SDValue Load = 3819 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3820 3821 // Add the thread pointer. 3822 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3823 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3824 } 3825 3826 // Generate a sequence for accessing the address relative to the thread 3827 // pointer, with the appropriate adjustment for the thread pointer offset. 3828 // This generates the pattern 3829 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3830 SDValue AddrHi = 3831 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3832 SDValue AddrAdd = 3833 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3834 SDValue AddrLo = 3835 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3836 3837 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3838 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3839 SDValue MNAdd = SDValue( 3840 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3841 0); 3842 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3843 } 3844 3845 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3846 SelectionDAG &DAG) const { 3847 SDLoc DL(N); 3848 EVT Ty = getPointerTy(DAG.getDataLayout()); 3849 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3850 const GlobalValue *GV = N->getGlobal(); 3851 3852 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3853 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3854 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3855 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3856 SDValue Load = 3857 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3858 3859 // Prepare argument list to generate call. 3860 ArgListTy Args; 3861 ArgListEntry Entry; 3862 Entry.Node = Load; 3863 Entry.Ty = CallTy; 3864 Args.push_back(Entry); 3865 3866 // Setup call to __tls_get_addr. 3867 TargetLowering::CallLoweringInfo CLI(DAG); 3868 CLI.setDebugLoc(DL) 3869 .setChain(DAG.getEntryNode()) 3870 .setLibCallee(CallingConv::C, CallTy, 3871 DAG.getExternalSymbol("__tls_get_addr", Ty), 3872 std::move(Args)); 3873 3874 return LowerCallTo(CLI).first; 3875 } 3876 3877 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3878 SelectionDAG &DAG) const { 3879 SDLoc DL(Op); 3880 EVT Ty = Op.getValueType(); 3881 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3882 int64_t Offset = N->getOffset(); 3883 MVT XLenVT = Subtarget.getXLenVT(); 3884 3885 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3886 3887 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3888 CallingConv::GHC) 3889 report_fatal_error("In GHC calling convention TLS is not supported"); 3890 3891 SDValue Addr; 3892 switch (Model) { 3893 case TLSModel::LocalExec: 3894 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3895 break; 3896 case TLSModel::InitialExec: 3897 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3898 break; 3899 case TLSModel::LocalDynamic: 3900 case TLSModel::GeneralDynamic: 3901 Addr = getDynamicTLSAddr(N, DAG); 3902 break; 3903 } 3904 3905 // In order to maximise the opportunity for common subexpression elimination, 3906 // emit a separate ADD node for the global address offset instead of folding 3907 // it in the global address node. Later peephole optimisations may choose to 3908 // fold it back in when profitable. 3909 if (Offset != 0) 3910 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3911 DAG.getConstant(Offset, DL, XLenVT)); 3912 return Addr; 3913 } 3914 3915 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3916 SDValue CondV = Op.getOperand(0); 3917 SDValue TrueV = Op.getOperand(1); 3918 SDValue FalseV = Op.getOperand(2); 3919 SDLoc DL(Op); 3920 MVT VT = Op.getSimpleValueType(); 3921 MVT XLenVT = Subtarget.getXLenVT(); 3922 3923 // Lower vector SELECTs to VSELECTs by splatting the condition. 3924 if (VT.isVector()) { 3925 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3926 SDValue CondSplat = VT.isScalableVector() 3927 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3928 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3929 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3930 } 3931 3932 // If the result type is XLenVT and CondV is the output of a SETCC node 3933 // which also operated on XLenVT inputs, then merge the SETCC node into the 3934 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3935 // compare+branch instructions. i.e.: 3936 // (select (setcc lhs, rhs, cc), truev, falsev) 3937 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3938 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3939 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3940 SDValue LHS = CondV.getOperand(0); 3941 SDValue RHS = CondV.getOperand(1); 3942 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3943 ISD::CondCode CCVal = CC->get(); 3944 3945 // Special case for a select of 2 constants that have a diffence of 1. 3946 // Normally this is done by DAGCombine, but if the select is introduced by 3947 // type legalization or op legalization, we miss it. Restricting to SETLT 3948 // case for now because that is what signed saturating add/sub need. 3949 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3950 // but we would probably want to swap the true/false values if the condition 3951 // is SETGE/SETLE to avoid an XORI. 3952 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3953 CCVal == ISD::SETLT) { 3954 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3955 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3956 if (TrueVal - 1 == FalseVal) 3957 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3958 if (TrueVal + 1 == FalseVal) 3959 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3960 } 3961 3962 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3963 3964 SDValue TargetCC = DAG.getCondCode(CCVal); 3965 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3966 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3967 } 3968 3969 // Otherwise: 3970 // (select condv, truev, falsev) 3971 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3972 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3973 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3974 3975 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3976 3977 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3978 } 3979 3980 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3981 SDValue CondV = Op.getOperand(1); 3982 SDLoc DL(Op); 3983 MVT XLenVT = Subtarget.getXLenVT(); 3984 3985 if (CondV.getOpcode() == ISD::SETCC && 3986 CondV.getOperand(0).getValueType() == XLenVT) { 3987 SDValue LHS = CondV.getOperand(0); 3988 SDValue RHS = CondV.getOperand(1); 3989 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3990 3991 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3992 3993 SDValue TargetCC = DAG.getCondCode(CCVal); 3994 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3995 LHS, RHS, TargetCC, Op.getOperand(2)); 3996 } 3997 3998 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3999 CondV, DAG.getConstant(0, DL, XLenVT), 4000 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 4001 } 4002 4003 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 4004 MachineFunction &MF = DAG.getMachineFunction(); 4005 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 4006 4007 SDLoc DL(Op); 4008 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 4009 getPointerTy(MF.getDataLayout())); 4010 4011 // vastart just stores the address of the VarArgsFrameIndex slot into the 4012 // memory location argument. 4013 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4014 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 4015 MachinePointerInfo(SV)); 4016 } 4017 4018 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 4019 SelectionDAG &DAG) const { 4020 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4021 MachineFunction &MF = DAG.getMachineFunction(); 4022 MachineFrameInfo &MFI = MF.getFrameInfo(); 4023 MFI.setFrameAddressIsTaken(true); 4024 Register FrameReg = RI.getFrameRegister(MF); 4025 int XLenInBytes = Subtarget.getXLen() / 8; 4026 4027 EVT VT = Op.getValueType(); 4028 SDLoc DL(Op); 4029 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 4030 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4031 while (Depth--) { 4032 int Offset = -(XLenInBytes * 2); 4033 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 4034 DAG.getIntPtrConstant(Offset, DL)); 4035 FrameAddr = 4036 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 4037 } 4038 return FrameAddr; 4039 } 4040 4041 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4042 SelectionDAG &DAG) const { 4043 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4044 MachineFunction &MF = DAG.getMachineFunction(); 4045 MachineFrameInfo &MFI = MF.getFrameInfo(); 4046 MFI.setReturnAddressIsTaken(true); 4047 MVT XLenVT = Subtarget.getXLenVT(); 4048 int XLenInBytes = Subtarget.getXLen() / 8; 4049 4050 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4051 return SDValue(); 4052 4053 EVT VT = Op.getValueType(); 4054 SDLoc DL(Op); 4055 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4056 if (Depth) { 4057 int Off = -XLenInBytes; 4058 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4059 SDValue Offset = DAG.getConstant(Off, DL, VT); 4060 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4061 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4062 MachinePointerInfo()); 4063 } 4064 4065 // Return the value of the return address register, marking it an implicit 4066 // live-in. 4067 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4068 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4069 } 4070 4071 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4072 SelectionDAG &DAG) const { 4073 SDLoc DL(Op); 4074 SDValue Lo = Op.getOperand(0); 4075 SDValue Hi = Op.getOperand(1); 4076 SDValue Shamt = Op.getOperand(2); 4077 EVT VT = Lo.getValueType(); 4078 4079 // if Shamt-XLEN < 0: // Shamt < XLEN 4080 // Lo = Lo << Shamt 4081 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4082 // else: 4083 // Lo = 0 4084 // Hi = Lo << (Shamt-XLEN) 4085 4086 SDValue Zero = DAG.getConstant(0, DL, VT); 4087 SDValue One = DAG.getConstant(1, DL, VT); 4088 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4089 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4090 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4091 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4092 4093 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4094 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4095 SDValue ShiftRightLo = 4096 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4097 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4098 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4099 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4100 4101 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4102 4103 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4104 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4105 4106 SDValue Parts[2] = {Lo, Hi}; 4107 return DAG.getMergeValues(Parts, DL); 4108 } 4109 4110 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4111 bool IsSRA) const { 4112 SDLoc DL(Op); 4113 SDValue Lo = Op.getOperand(0); 4114 SDValue Hi = Op.getOperand(1); 4115 SDValue Shamt = Op.getOperand(2); 4116 EVT VT = Lo.getValueType(); 4117 4118 // SRA expansion: 4119 // if Shamt-XLEN < 0: // Shamt < XLEN 4120 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4121 // Hi = Hi >>s Shamt 4122 // else: 4123 // Lo = Hi >>s (Shamt-XLEN); 4124 // Hi = Hi >>s (XLEN-1) 4125 // 4126 // SRL expansion: 4127 // if Shamt-XLEN < 0: // Shamt < XLEN 4128 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4129 // Hi = Hi >>u Shamt 4130 // else: 4131 // Lo = Hi >>u (Shamt-XLEN); 4132 // Hi = 0; 4133 4134 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4135 4136 SDValue Zero = DAG.getConstant(0, DL, VT); 4137 SDValue One = DAG.getConstant(1, DL, VT); 4138 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4139 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4140 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4141 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4142 4143 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4144 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4145 SDValue ShiftLeftHi = 4146 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4147 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4148 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4149 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4150 SDValue HiFalse = 4151 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4152 4153 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4154 4155 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4156 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4157 4158 SDValue Parts[2] = {Lo, Hi}; 4159 return DAG.getMergeValues(Parts, DL); 4160 } 4161 4162 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4163 // legal equivalently-sized i8 type, so we can use that as a go-between. 4164 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4165 SelectionDAG &DAG) const { 4166 SDLoc DL(Op); 4167 MVT VT = Op.getSimpleValueType(); 4168 SDValue SplatVal = Op.getOperand(0); 4169 // All-zeros or all-ones splats are handled specially. 4170 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4171 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4172 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4173 } 4174 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4175 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4176 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4177 } 4178 MVT XLenVT = Subtarget.getXLenVT(); 4179 assert(SplatVal.getValueType() == XLenVT && 4180 "Unexpected type for i1 splat value"); 4181 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4182 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4183 DAG.getConstant(1, DL, XLenVT)); 4184 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4185 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4186 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4187 } 4188 4189 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4190 // illegal (currently only vXi64 RV32). 4191 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4192 // them to VMV_V_X_VL. 4193 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4194 SelectionDAG &DAG) const { 4195 SDLoc DL(Op); 4196 MVT VecVT = Op.getSimpleValueType(); 4197 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4198 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4199 4200 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4201 SDValue Lo = Op.getOperand(0); 4202 SDValue Hi = Op.getOperand(1); 4203 4204 if (VecVT.isFixedLengthVector()) { 4205 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4206 SDLoc DL(Op); 4207 SDValue Mask, VL; 4208 std::tie(Mask, VL) = 4209 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4210 4211 SDValue Res = 4212 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4213 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4214 } 4215 4216 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4217 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4218 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4219 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4220 // node in order to try and match RVV vector/scalar instructions. 4221 if ((LoC >> 31) == HiC) 4222 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4223 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4224 } 4225 4226 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4227 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4228 isa<ConstantSDNode>(Hi.getOperand(1)) && 4229 Hi.getConstantOperandVal(1) == 31) 4230 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4231 DAG.getRegister(RISCV::X0, MVT::i32)); 4232 4233 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4234 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4235 DAG.getUNDEF(VecVT), Lo, Hi, 4236 DAG.getRegister(RISCV::X0, MVT::i32)); 4237 } 4238 4239 // Custom-lower extensions from mask vectors by using a vselect either with 1 4240 // for zero/any-extension or -1 for sign-extension: 4241 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4242 // Note that any-extension is lowered identically to zero-extension. 4243 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4244 int64_t ExtTrueVal) const { 4245 SDLoc DL(Op); 4246 MVT VecVT = Op.getSimpleValueType(); 4247 SDValue Src = Op.getOperand(0); 4248 // Only custom-lower extensions from mask types 4249 assert(Src.getValueType().isVector() && 4250 Src.getValueType().getVectorElementType() == MVT::i1); 4251 4252 MVT XLenVT = Subtarget.getXLenVT(); 4253 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4254 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4255 4256 if (VecVT.isScalableVector()) { 4257 // Be careful not to introduce illegal scalar types at this stage, and be 4258 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4259 // illegal and must be expanded. Since we know that the constants are 4260 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4261 bool IsRV32E64 = 4262 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4263 4264 if (!IsRV32E64) { 4265 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4266 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4267 } else { 4268 SplatZero = 4269 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4270 SplatZero, DAG.getRegister(RISCV::X0, XLenVT)); 4271 SplatTrueVal = 4272 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4273 SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT)); 4274 } 4275 4276 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4277 } 4278 4279 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4280 MVT I1ContainerVT = 4281 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4282 4283 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4284 4285 SDValue Mask, VL; 4286 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4287 4288 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4289 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4290 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4291 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4292 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4293 SplatTrueVal, SplatZero, VL); 4294 4295 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4296 } 4297 4298 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4299 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4300 MVT ExtVT = Op.getSimpleValueType(); 4301 // Only custom-lower extensions from fixed-length vector types. 4302 if (!ExtVT.isFixedLengthVector()) 4303 return Op; 4304 MVT VT = Op.getOperand(0).getSimpleValueType(); 4305 // Grab the canonical container type for the extended type. Infer the smaller 4306 // type from that to ensure the same number of vector elements, as we know 4307 // the LMUL will be sufficient to hold the smaller type. 4308 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4309 // Get the extended container type manually to ensure the same number of 4310 // vector elements between source and dest. 4311 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4312 ContainerExtVT.getVectorElementCount()); 4313 4314 SDValue Op1 = 4315 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4316 4317 SDLoc DL(Op); 4318 SDValue Mask, VL; 4319 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4320 4321 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4322 4323 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4324 } 4325 4326 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4327 // setcc operation: 4328 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4329 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4330 SelectionDAG &DAG) const { 4331 SDLoc DL(Op); 4332 EVT MaskVT = Op.getValueType(); 4333 // Only expect to custom-lower truncations to mask types 4334 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4335 "Unexpected type for vector mask lowering"); 4336 SDValue Src = Op.getOperand(0); 4337 MVT VecVT = Src.getSimpleValueType(); 4338 4339 // If this is a fixed vector, we need to convert it to a scalable vector. 4340 MVT ContainerVT = VecVT; 4341 if (VecVT.isFixedLengthVector()) { 4342 ContainerVT = getContainerForFixedLengthVector(VecVT); 4343 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4344 } 4345 4346 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4347 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4348 4349 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4350 DAG.getUNDEF(ContainerVT), SplatOne); 4351 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4352 DAG.getUNDEF(ContainerVT), SplatZero); 4353 4354 if (VecVT.isScalableVector()) { 4355 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4356 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4357 } 4358 4359 SDValue Mask, VL; 4360 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4361 4362 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4363 SDValue Trunc = 4364 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4365 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4366 DAG.getCondCode(ISD::SETNE), Mask, VL); 4367 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4368 } 4369 4370 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4371 // first position of a vector, and that vector is slid up to the insert index. 4372 // By limiting the active vector length to index+1 and merging with the 4373 // original vector (with an undisturbed tail policy for elements >= VL), we 4374 // achieve the desired result of leaving all elements untouched except the one 4375 // at VL-1, which is replaced with the desired value. 4376 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4377 SelectionDAG &DAG) const { 4378 SDLoc DL(Op); 4379 MVT VecVT = Op.getSimpleValueType(); 4380 SDValue Vec = Op.getOperand(0); 4381 SDValue Val = Op.getOperand(1); 4382 SDValue Idx = Op.getOperand(2); 4383 4384 if (VecVT.getVectorElementType() == MVT::i1) { 4385 // FIXME: For now we just promote to an i8 vector and insert into that, 4386 // but this is probably not optimal. 4387 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4388 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4389 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4390 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4391 } 4392 4393 MVT ContainerVT = VecVT; 4394 // If the operand is a fixed-length vector, convert to a scalable one. 4395 if (VecVT.isFixedLengthVector()) { 4396 ContainerVT = getContainerForFixedLengthVector(VecVT); 4397 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4398 } 4399 4400 MVT XLenVT = Subtarget.getXLenVT(); 4401 4402 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4403 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4404 // Even i64-element vectors on RV32 can be lowered without scalar 4405 // legalization if the most-significant 32 bits of the value are not affected 4406 // by the sign-extension of the lower 32 bits. 4407 // TODO: We could also catch sign extensions of a 32-bit value. 4408 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4409 const auto *CVal = cast<ConstantSDNode>(Val); 4410 if (isInt<32>(CVal->getSExtValue())) { 4411 IsLegalInsert = true; 4412 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4413 } 4414 } 4415 4416 SDValue Mask, VL; 4417 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4418 4419 SDValue ValInVec; 4420 4421 if (IsLegalInsert) { 4422 unsigned Opc = 4423 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4424 if (isNullConstant(Idx)) { 4425 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4426 if (!VecVT.isFixedLengthVector()) 4427 return Vec; 4428 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4429 } 4430 ValInVec = 4431 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4432 } else { 4433 // On RV32, i64-element vectors must be specially handled to place the 4434 // value at element 0, by using two vslide1up instructions in sequence on 4435 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4436 // this. 4437 SDValue One = DAG.getConstant(1, DL, XLenVT); 4438 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4439 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4440 MVT I32ContainerVT = 4441 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4442 SDValue I32Mask = 4443 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4444 // Limit the active VL to two. 4445 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4446 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4447 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4448 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4449 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4450 // First slide in the hi value, then the lo in underneath it. 4451 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4452 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4453 I32Mask, InsertI64VL); 4454 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4455 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4456 I32Mask, InsertI64VL); 4457 // Bitcast back to the right container type. 4458 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4459 } 4460 4461 // Now that the value is in a vector, slide it into position. 4462 SDValue InsertVL = 4463 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4464 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4465 ValInVec, Idx, Mask, InsertVL); 4466 if (!VecVT.isFixedLengthVector()) 4467 return Slideup; 4468 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4469 } 4470 4471 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4472 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4473 // types this is done using VMV_X_S to allow us to glean information about the 4474 // sign bits of the result. 4475 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4476 SelectionDAG &DAG) const { 4477 SDLoc DL(Op); 4478 SDValue Idx = Op.getOperand(1); 4479 SDValue Vec = Op.getOperand(0); 4480 EVT EltVT = Op.getValueType(); 4481 MVT VecVT = Vec.getSimpleValueType(); 4482 MVT XLenVT = Subtarget.getXLenVT(); 4483 4484 if (VecVT.getVectorElementType() == MVT::i1) { 4485 if (VecVT.isFixedLengthVector()) { 4486 unsigned NumElts = VecVT.getVectorNumElements(); 4487 if (NumElts >= 8) { 4488 MVT WideEltVT; 4489 unsigned WidenVecLen; 4490 SDValue ExtractElementIdx; 4491 SDValue ExtractBitIdx; 4492 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4493 MVT LargestEltVT = MVT::getIntegerVT( 4494 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4495 if (NumElts <= LargestEltVT.getSizeInBits()) { 4496 assert(isPowerOf2_32(NumElts) && 4497 "the number of elements should be power of 2"); 4498 WideEltVT = MVT::getIntegerVT(NumElts); 4499 WidenVecLen = 1; 4500 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4501 ExtractBitIdx = Idx; 4502 } else { 4503 WideEltVT = LargestEltVT; 4504 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4505 // extract element index = index / element width 4506 ExtractElementIdx = DAG.getNode( 4507 ISD::SRL, DL, XLenVT, Idx, 4508 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4509 // mask bit index = index % element width 4510 ExtractBitIdx = DAG.getNode( 4511 ISD::AND, DL, XLenVT, Idx, 4512 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4513 } 4514 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4515 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4516 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4517 Vec, ExtractElementIdx); 4518 // Extract the bit from GPR. 4519 SDValue ShiftRight = 4520 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4521 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4522 DAG.getConstant(1, DL, XLenVT)); 4523 } 4524 } 4525 // Otherwise, promote to an i8 vector and extract from that. 4526 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4527 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4528 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4529 } 4530 4531 // If this is a fixed vector, we need to convert it to a scalable vector. 4532 MVT ContainerVT = VecVT; 4533 if (VecVT.isFixedLengthVector()) { 4534 ContainerVT = getContainerForFixedLengthVector(VecVT); 4535 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4536 } 4537 4538 // If the index is 0, the vector is already in the right position. 4539 if (!isNullConstant(Idx)) { 4540 // Use a VL of 1 to avoid processing more elements than we need. 4541 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4542 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4543 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4544 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4545 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4546 } 4547 4548 if (!EltVT.isInteger()) { 4549 // Floating-point extracts are handled in TableGen. 4550 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4551 DAG.getConstant(0, DL, XLenVT)); 4552 } 4553 4554 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4555 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4556 } 4557 4558 // Some RVV intrinsics may claim that they want an integer operand to be 4559 // promoted or expanded. 4560 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4561 const RISCVSubtarget &Subtarget) { 4562 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4563 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4564 "Unexpected opcode"); 4565 4566 if (!Subtarget.hasVInstructions()) 4567 return SDValue(); 4568 4569 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4570 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4571 SDLoc DL(Op); 4572 4573 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4574 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4575 if (!II || !II->hasSplatOperand()) 4576 return SDValue(); 4577 4578 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4579 assert(SplatOp < Op.getNumOperands()); 4580 4581 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4582 SDValue &ScalarOp = Operands[SplatOp]; 4583 MVT OpVT = ScalarOp.getSimpleValueType(); 4584 MVT XLenVT = Subtarget.getXLenVT(); 4585 4586 // If this isn't a scalar, or its type is XLenVT we're done. 4587 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4588 return SDValue(); 4589 4590 // Simplest case is that the operand needs to be promoted to XLenVT. 4591 if (OpVT.bitsLT(XLenVT)) { 4592 // If the operand is a constant, sign extend to increase our chances 4593 // of being able to use a .vi instruction. ANY_EXTEND would become a 4594 // a zero extend and the simm5 check in isel would fail. 4595 // FIXME: Should we ignore the upper bits in isel instead? 4596 unsigned ExtOpc = 4597 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4598 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4599 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4600 } 4601 4602 // Use the previous operand to get the vXi64 VT. The result might be a mask 4603 // VT for compares. Using the previous operand assumes that the previous 4604 // operand will never have a smaller element size than a scalar operand and 4605 // that a widening operation never uses SEW=64. 4606 // NOTE: If this fails the below assert, we can probably just find the 4607 // element count from any operand or result and use it to construct the VT. 4608 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4609 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4610 4611 // The more complex case is when the scalar is larger than XLenVT. 4612 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4613 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4614 4615 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4616 // on the instruction to sign-extend since SEW>XLEN. 4617 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4618 if (isInt<32>(CVal->getSExtValue())) { 4619 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4620 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4621 } 4622 } 4623 4624 // We need to convert the scalar to a splat vector. 4625 // FIXME: Can we implicitly truncate the scalar if it is known to 4626 // be sign extended? 4627 SDValue VL = getVLOperand(Op); 4628 assert(VL.getValueType() == XLenVT); 4629 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4630 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4631 } 4632 4633 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4634 SelectionDAG &DAG) const { 4635 unsigned IntNo = Op.getConstantOperandVal(0); 4636 SDLoc DL(Op); 4637 MVT XLenVT = Subtarget.getXLenVT(); 4638 4639 switch (IntNo) { 4640 default: 4641 break; // Don't custom lower most intrinsics. 4642 case Intrinsic::thread_pointer: { 4643 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4644 return DAG.getRegister(RISCV::X4, PtrVT); 4645 } 4646 case Intrinsic::riscv_orc_b: 4647 case Intrinsic::riscv_brev8: { 4648 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4649 unsigned Opc = 4650 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4651 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4652 DAG.getConstant(7, DL, XLenVT)); 4653 } 4654 case Intrinsic::riscv_grev: 4655 case Intrinsic::riscv_gorc: { 4656 unsigned Opc = 4657 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4658 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4659 } 4660 case Intrinsic::riscv_zip: 4661 case Intrinsic::riscv_unzip: { 4662 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4663 // For i32 the immdiate is 15. For i64 the immediate is 31. 4664 unsigned Opc = 4665 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4666 unsigned BitWidth = Op.getValueSizeInBits(); 4667 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4668 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4669 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4670 } 4671 case Intrinsic::riscv_shfl: 4672 case Intrinsic::riscv_unshfl: { 4673 unsigned Opc = 4674 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4675 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4676 } 4677 case Intrinsic::riscv_bcompress: 4678 case Intrinsic::riscv_bdecompress: { 4679 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4680 : RISCVISD::BDECOMPRESS; 4681 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4682 } 4683 case Intrinsic::riscv_bfp: 4684 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4685 Op.getOperand(2)); 4686 case Intrinsic::riscv_fsl: 4687 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4688 Op.getOperand(2), Op.getOperand(3)); 4689 case Intrinsic::riscv_fsr: 4690 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4691 Op.getOperand(2), Op.getOperand(3)); 4692 case Intrinsic::riscv_vmv_x_s: 4693 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4694 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4695 Op.getOperand(1)); 4696 case Intrinsic::riscv_vmv_v_x: 4697 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4698 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4699 Subtarget); 4700 case Intrinsic::riscv_vfmv_v_f: 4701 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4702 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4703 case Intrinsic::riscv_vmv_s_x: { 4704 SDValue Scalar = Op.getOperand(2); 4705 4706 if (Scalar.getValueType().bitsLE(XLenVT)) { 4707 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4708 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4709 Op.getOperand(1), Scalar, Op.getOperand(3)); 4710 } 4711 4712 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4713 4714 // This is an i64 value that lives in two scalar registers. We have to 4715 // insert this in a convoluted way. First we build vXi64 splat containing 4716 // the/ two values that we assemble using some bit math. Next we'll use 4717 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4718 // to merge element 0 from our splat into the source vector. 4719 // FIXME: This is probably not the best way to do this, but it is 4720 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4721 // point. 4722 // sw lo, (a0) 4723 // sw hi, 4(a0) 4724 // vlse vX, (a0) 4725 // 4726 // vid.v vVid 4727 // vmseq.vx mMask, vVid, 0 4728 // vmerge.vvm vDest, vSrc, vVal, mMask 4729 MVT VT = Op.getSimpleValueType(); 4730 SDValue Vec = Op.getOperand(1); 4731 SDValue VL = getVLOperand(Op); 4732 4733 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4734 if (Op.getOperand(1).isUndef()) 4735 return SplattedVal; 4736 SDValue SplattedIdx = 4737 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4738 DAG.getConstant(0, DL, MVT::i32), VL); 4739 4740 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4741 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4742 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4743 SDValue SelectCond = 4744 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4745 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4746 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4747 Vec, VL); 4748 } 4749 case Intrinsic::riscv_vslide1up: 4750 case Intrinsic::riscv_vslide1down: 4751 case Intrinsic::riscv_vslide1up_mask: 4752 case Intrinsic::riscv_vslide1down_mask: { 4753 // We need to special case these when the scalar is larger than XLen. 4754 unsigned NumOps = Op.getNumOperands(); 4755 bool IsMasked = NumOps == 7; 4756 SDValue Scalar = Op.getOperand(3); 4757 if (Scalar.getValueType().bitsLE(XLenVT)) 4758 break; 4759 4760 // Splatting a sign extended constant is fine. 4761 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4762 if (isInt<32>(CVal->getSExtValue())) 4763 break; 4764 4765 MVT VT = Op.getSimpleValueType(); 4766 assert(VT.getVectorElementType() == MVT::i64 && 4767 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4768 4769 // Convert the vector source to the equivalent nxvXi32 vector. 4770 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4771 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2)); 4772 4773 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4774 DAG.getConstant(0, DL, XLenVT)); 4775 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4776 DAG.getConstant(1, DL, XLenVT)); 4777 4778 // Double the VL since we halved SEW. 4779 SDValue VL = getVLOperand(Op); 4780 SDValue I32VL = 4781 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4782 4783 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4784 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4785 4786 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4787 // instructions. 4788 SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1)); 4789 if (!IsMasked) { 4790 if (IntNo == Intrinsic::riscv_vslide1up) { 4791 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4792 ScalarHi, I32Mask, I32VL); 4793 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4794 ScalarLo, I32Mask, I32VL); 4795 } else { 4796 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4797 ScalarLo, I32Mask, I32VL); 4798 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4799 ScalarHi, I32Mask, I32VL); 4800 } 4801 } else { 4802 // TODO Those VSLIDE1 could be TAMA because we use vmerge to select 4803 // maskedoff 4804 SDValue Undef = DAG.getUNDEF(I32VT); 4805 if (IntNo == Intrinsic::riscv_vslide1up_mask) { 4806 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4807 ScalarHi, I32Mask, I32VL); 4808 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec, 4809 ScalarLo, I32Mask, I32VL); 4810 } else { 4811 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4812 ScalarLo, I32Mask, I32VL); 4813 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec, 4814 ScalarHi, I32Mask, I32VL); 4815 } 4816 } 4817 4818 // Convert back to nxvXi64. 4819 Vec = DAG.getBitcast(VT, Vec); 4820 4821 if (!IsMasked) 4822 return Vec; 4823 // Apply mask after the operation. 4824 SDValue Mask = Op.getOperand(NumOps - 3); 4825 SDValue MaskedOff = Op.getOperand(1); 4826 // Assume Policy operand is the last operand. 4827 uint64_t Policy = Op.getConstantOperandVal(NumOps - 1); 4828 // We don't need to select maskedoff if it's undef. 4829 if (MaskedOff.isUndef()) 4830 return Vec; 4831 // TAMU 4832 if (Policy == RISCVII::TAIL_AGNOSTIC) 4833 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4834 VL); 4835 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4836 // It's fine because vmerge does not care mask policy. 4837 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4838 } 4839 } 4840 4841 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4842 } 4843 4844 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4845 SelectionDAG &DAG) const { 4846 unsigned IntNo = Op.getConstantOperandVal(1); 4847 switch (IntNo) { 4848 default: 4849 break; 4850 case Intrinsic::riscv_masked_strided_load: { 4851 SDLoc DL(Op); 4852 MVT XLenVT = Subtarget.getXLenVT(); 4853 4854 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4855 // the selection of the masked intrinsics doesn't do this for us. 4856 SDValue Mask = Op.getOperand(5); 4857 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4858 4859 MVT VT = Op->getSimpleValueType(0); 4860 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4861 4862 SDValue PassThru = Op.getOperand(2); 4863 if (!IsUnmasked) { 4864 MVT MaskVT = 4865 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4866 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4867 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4868 } 4869 4870 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4871 4872 SDValue IntID = DAG.getTargetConstant( 4873 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4874 XLenVT); 4875 4876 auto *Load = cast<MemIntrinsicSDNode>(Op); 4877 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4878 if (IsUnmasked) 4879 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4880 else 4881 Ops.push_back(PassThru); 4882 Ops.push_back(Op.getOperand(3)); // Ptr 4883 Ops.push_back(Op.getOperand(4)); // Stride 4884 if (!IsUnmasked) 4885 Ops.push_back(Mask); 4886 Ops.push_back(VL); 4887 if (!IsUnmasked) { 4888 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4889 Ops.push_back(Policy); 4890 } 4891 4892 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4893 SDValue Result = 4894 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4895 Load->getMemoryVT(), Load->getMemOperand()); 4896 SDValue Chain = Result.getValue(1); 4897 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4898 return DAG.getMergeValues({Result, Chain}, DL); 4899 } 4900 } 4901 4902 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4903 } 4904 4905 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4906 SelectionDAG &DAG) const { 4907 unsigned IntNo = Op.getConstantOperandVal(1); 4908 switch (IntNo) { 4909 default: 4910 break; 4911 case Intrinsic::riscv_masked_strided_store: { 4912 SDLoc DL(Op); 4913 MVT XLenVT = Subtarget.getXLenVT(); 4914 4915 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4916 // the selection of the masked intrinsics doesn't do this for us. 4917 SDValue Mask = Op.getOperand(5); 4918 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4919 4920 SDValue Val = Op.getOperand(2); 4921 MVT VT = Val.getSimpleValueType(); 4922 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4923 4924 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4925 if (!IsUnmasked) { 4926 MVT MaskVT = 4927 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4928 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4929 } 4930 4931 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4932 4933 SDValue IntID = DAG.getTargetConstant( 4934 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4935 XLenVT); 4936 4937 auto *Store = cast<MemIntrinsicSDNode>(Op); 4938 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4939 Ops.push_back(Val); 4940 Ops.push_back(Op.getOperand(3)); // Ptr 4941 Ops.push_back(Op.getOperand(4)); // Stride 4942 if (!IsUnmasked) 4943 Ops.push_back(Mask); 4944 Ops.push_back(VL); 4945 4946 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4947 Ops, Store->getMemoryVT(), 4948 Store->getMemOperand()); 4949 } 4950 } 4951 4952 return SDValue(); 4953 } 4954 4955 static MVT getLMUL1VT(MVT VT) { 4956 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4957 "Unexpected vector MVT"); 4958 return MVT::getScalableVectorVT( 4959 VT.getVectorElementType(), 4960 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4961 } 4962 4963 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4964 switch (ISDOpcode) { 4965 default: 4966 llvm_unreachable("Unhandled reduction"); 4967 case ISD::VECREDUCE_ADD: 4968 return RISCVISD::VECREDUCE_ADD_VL; 4969 case ISD::VECREDUCE_UMAX: 4970 return RISCVISD::VECREDUCE_UMAX_VL; 4971 case ISD::VECREDUCE_SMAX: 4972 return RISCVISD::VECREDUCE_SMAX_VL; 4973 case ISD::VECREDUCE_UMIN: 4974 return RISCVISD::VECREDUCE_UMIN_VL; 4975 case ISD::VECREDUCE_SMIN: 4976 return RISCVISD::VECREDUCE_SMIN_VL; 4977 case ISD::VECREDUCE_AND: 4978 return RISCVISD::VECREDUCE_AND_VL; 4979 case ISD::VECREDUCE_OR: 4980 return RISCVISD::VECREDUCE_OR_VL; 4981 case ISD::VECREDUCE_XOR: 4982 return RISCVISD::VECREDUCE_XOR_VL; 4983 } 4984 } 4985 4986 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4987 SelectionDAG &DAG, 4988 bool IsVP) const { 4989 SDLoc DL(Op); 4990 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4991 MVT VecVT = Vec.getSimpleValueType(); 4992 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4993 Op.getOpcode() == ISD::VECREDUCE_OR || 4994 Op.getOpcode() == ISD::VECREDUCE_XOR || 4995 Op.getOpcode() == ISD::VP_REDUCE_AND || 4996 Op.getOpcode() == ISD::VP_REDUCE_OR || 4997 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4998 "Unexpected reduction lowering"); 4999 5000 MVT XLenVT = Subtarget.getXLenVT(); 5001 assert(Op.getValueType() == XLenVT && 5002 "Expected reduction output to be legalized to XLenVT"); 5003 5004 MVT ContainerVT = VecVT; 5005 if (VecVT.isFixedLengthVector()) { 5006 ContainerVT = getContainerForFixedLengthVector(VecVT); 5007 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5008 } 5009 5010 SDValue Mask, VL; 5011 if (IsVP) { 5012 Mask = Op.getOperand(2); 5013 VL = Op.getOperand(3); 5014 } else { 5015 std::tie(Mask, VL) = 5016 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5017 } 5018 5019 unsigned BaseOpc; 5020 ISD::CondCode CC; 5021 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5022 5023 switch (Op.getOpcode()) { 5024 default: 5025 llvm_unreachable("Unhandled reduction"); 5026 case ISD::VECREDUCE_AND: 5027 case ISD::VP_REDUCE_AND: { 5028 // vcpop ~x == 0 5029 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5030 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5031 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5032 CC = ISD::SETEQ; 5033 BaseOpc = ISD::AND; 5034 break; 5035 } 5036 case ISD::VECREDUCE_OR: 5037 case ISD::VP_REDUCE_OR: 5038 // vcpop x != 0 5039 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5040 CC = ISD::SETNE; 5041 BaseOpc = ISD::OR; 5042 break; 5043 case ISD::VECREDUCE_XOR: 5044 case ISD::VP_REDUCE_XOR: { 5045 // ((vcpop x) & 1) != 0 5046 SDValue One = DAG.getConstant(1, DL, XLenVT); 5047 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5048 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5049 CC = ISD::SETNE; 5050 BaseOpc = ISD::XOR; 5051 break; 5052 } 5053 } 5054 5055 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5056 5057 if (!IsVP) 5058 return SetCC; 5059 5060 // Now include the start value in the operation. 5061 // Note that we must return the start value when no elements are operated 5062 // upon. The vcpop instructions we've emitted in each case above will return 5063 // 0 for an inactive vector, and so we've already received the neutral value: 5064 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5065 // can simply include the start value. 5066 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5067 } 5068 5069 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5070 SelectionDAG &DAG) const { 5071 SDLoc DL(Op); 5072 SDValue Vec = Op.getOperand(0); 5073 EVT VecEVT = Vec.getValueType(); 5074 5075 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5076 5077 // Due to ordering in legalize types we may have a vector type that needs to 5078 // be split. Do that manually so we can get down to a legal type. 5079 while (getTypeAction(*DAG.getContext(), VecEVT) == 5080 TargetLowering::TypeSplitVector) { 5081 SDValue Lo, Hi; 5082 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5083 VecEVT = Lo.getValueType(); 5084 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5085 } 5086 5087 // TODO: The type may need to be widened rather than split. Or widened before 5088 // it can be split. 5089 if (!isTypeLegal(VecEVT)) 5090 return SDValue(); 5091 5092 MVT VecVT = VecEVT.getSimpleVT(); 5093 MVT VecEltVT = VecVT.getVectorElementType(); 5094 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5095 5096 MVT ContainerVT = VecVT; 5097 if (VecVT.isFixedLengthVector()) { 5098 ContainerVT = getContainerForFixedLengthVector(VecVT); 5099 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5100 } 5101 5102 MVT M1VT = getLMUL1VT(ContainerVT); 5103 MVT XLenVT = Subtarget.getXLenVT(); 5104 5105 SDValue Mask, VL; 5106 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5107 5108 SDValue NeutralElem = 5109 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5110 SDValue IdentitySplat = 5111 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5112 M1VT, DL, DAG, Subtarget); 5113 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5114 IdentitySplat, Mask, VL); 5115 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5116 DAG.getConstant(0, DL, XLenVT)); 5117 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5118 } 5119 5120 // Given a reduction op, this function returns the matching reduction opcode, 5121 // the vector SDValue and the scalar SDValue required to lower this to a 5122 // RISCVISD node. 5123 static std::tuple<unsigned, SDValue, SDValue> 5124 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5125 SDLoc DL(Op); 5126 auto Flags = Op->getFlags(); 5127 unsigned Opcode = Op.getOpcode(); 5128 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5129 switch (Opcode) { 5130 default: 5131 llvm_unreachable("Unhandled reduction"); 5132 case ISD::VECREDUCE_FADD: { 5133 // Use positive zero if we can. It is cheaper to materialize. 5134 SDValue Zero = 5135 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5136 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5137 } 5138 case ISD::VECREDUCE_SEQ_FADD: 5139 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5140 Op.getOperand(0)); 5141 case ISD::VECREDUCE_FMIN: 5142 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5143 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5144 case ISD::VECREDUCE_FMAX: 5145 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5146 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5147 } 5148 } 5149 5150 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5151 SelectionDAG &DAG) const { 5152 SDLoc DL(Op); 5153 MVT VecEltVT = Op.getSimpleValueType(); 5154 5155 unsigned RVVOpcode; 5156 SDValue VectorVal, ScalarVal; 5157 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5158 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5159 MVT VecVT = VectorVal.getSimpleValueType(); 5160 5161 MVT ContainerVT = VecVT; 5162 if (VecVT.isFixedLengthVector()) { 5163 ContainerVT = getContainerForFixedLengthVector(VecVT); 5164 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5165 } 5166 5167 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5168 MVT XLenVT = Subtarget.getXLenVT(); 5169 5170 SDValue Mask, VL; 5171 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5172 5173 SDValue ScalarSplat = 5174 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5175 M1VT, DL, DAG, Subtarget); 5176 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5177 VectorVal, ScalarSplat, Mask, VL); 5178 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5179 DAG.getConstant(0, DL, XLenVT)); 5180 } 5181 5182 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5183 switch (ISDOpcode) { 5184 default: 5185 llvm_unreachable("Unhandled reduction"); 5186 case ISD::VP_REDUCE_ADD: 5187 return RISCVISD::VECREDUCE_ADD_VL; 5188 case ISD::VP_REDUCE_UMAX: 5189 return RISCVISD::VECREDUCE_UMAX_VL; 5190 case ISD::VP_REDUCE_SMAX: 5191 return RISCVISD::VECREDUCE_SMAX_VL; 5192 case ISD::VP_REDUCE_UMIN: 5193 return RISCVISD::VECREDUCE_UMIN_VL; 5194 case ISD::VP_REDUCE_SMIN: 5195 return RISCVISD::VECREDUCE_SMIN_VL; 5196 case ISD::VP_REDUCE_AND: 5197 return RISCVISD::VECREDUCE_AND_VL; 5198 case ISD::VP_REDUCE_OR: 5199 return RISCVISD::VECREDUCE_OR_VL; 5200 case ISD::VP_REDUCE_XOR: 5201 return RISCVISD::VECREDUCE_XOR_VL; 5202 case ISD::VP_REDUCE_FADD: 5203 return RISCVISD::VECREDUCE_FADD_VL; 5204 case ISD::VP_REDUCE_SEQ_FADD: 5205 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5206 case ISD::VP_REDUCE_FMAX: 5207 return RISCVISD::VECREDUCE_FMAX_VL; 5208 case ISD::VP_REDUCE_FMIN: 5209 return RISCVISD::VECREDUCE_FMIN_VL; 5210 } 5211 } 5212 5213 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5214 SelectionDAG &DAG) const { 5215 SDLoc DL(Op); 5216 SDValue Vec = Op.getOperand(1); 5217 EVT VecEVT = Vec.getValueType(); 5218 5219 // TODO: The type may need to be widened rather than split. Or widened before 5220 // it can be split. 5221 if (!isTypeLegal(VecEVT)) 5222 return SDValue(); 5223 5224 MVT VecVT = VecEVT.getSimpleVT(); 5225 MVT VecEltVT = VecVT.getVectorElementType(); 5226 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5227 5228 MVT ContainerVT = VecVT; 5229 if (VecVT.isFixedLengthVector()) { 5230 ContainerVT = getContainerForFixedLengthVector(VecVT); 5231 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5232 } 5233 5234 SDValue VL = Op.getOperand(3); 5235 SDValue Mask = Op.getOperand(2); 5236 5237 MVT M1VT = getLMUL1VT(ContainerVT); 5238 MVT XLenVT = Subtarget.getXLenVT(); 5239 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5240 5241 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5242 DAG.getConstant(1, DL, XLenVT), M1VT, 5243 DL, DAG, Subtarget); 5244 SDValue Reduction = 5245 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5246 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5247 DAG.getConstant(0, DL, XLenVT)); 5248 if (!VecVT.isInteger()) 5249 return Elt0; 5250 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5251 } 5252 5253 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5254 SelectionDAG &DAG) const { 5255 SDValue Vec = Op.getOperand(0); 5256 SDValue SubVec = Op.getOperand(1); 5257 MVT VecVT = Vec.getSimpleValueType(); 5258 MVT SubVecVT = SubVec.getSimpleValueType(); 5259 5260 SDLoc DL(Op); 5261 MVT XLenVT = Subtarget.getXLenVT(); 5262 unsigned OrigIdx = Op.getConstantOperandVal(2); 5263 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5264 5265 // We don't have the ability to slide mask vectors up indexed by their i1 5266 // elements; the smallest we can do is i8. Often we are able to bitcast to 5267 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5268 // into a scalable one, we might not necessarily have enough scalable 5269 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5270 if (SubVecVT.getVectorElementType() == MVT::i1 && 5271 (OrigIdx != 0 || !Vec.isUndef())) { 5272 if (VecVT.getVectorMinNumElements() >= 8 && 5273 SubVecVT.getVectorMinNumElements() >= 8) { 5274 assert(OrigIdx % 8 == 0 && "Invalid index"); 5275 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5276 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5277 "Unexpected mask vector lowering"); 5278 OrigIdx /= 8; 5279 SubVecVT = 5280 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5281 SubVecVT.isScalableVector()); 5282 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5283 VecVT.isScalableVector()); 5284 Vec = DAG.getBitcast(VecVT, Vec); 5285 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5286 } else { 5287 // We can't slide this mask vector up indexed by its i1 elements. 5288 // This poses a problem when we wish to insert a scalable vector which 5289 // can't be re-expressed as a larger type. Just choose the slow path and 5290 // extend to a larger type, then truncate back down. 5291 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5292 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5293 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5294 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5295 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5296 Op.getOperand(2)); 5297 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5298 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5299 } 5300 } 5301 5302 // If the subvector vector is a fixed-length type, we cannot use subregister 5303 // manipulation to simplify the codegen; we don't know which register of a 5304 // LMUL group contains the specific subvector as we only know the minimum 5305 // register size. Therefore we must slide the vector group up the full 5306 // amount. 5307 if (SubVecVT.isFixedLengthVector()) { 5308 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5309 return Op; 5310 MVT ContainerVT = VecVT; 5311 if (VecVT.isFixedLengthVector()) { 5312 ContainerVT = getContainerForFixedLengthVector(VecVT); 5313 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5314 } 5315 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5316 DAG.getUNDEF(ContainerVT), SubVec, 5317 DAG.getConstant(0, DL, XLenVT)); 5318 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5319 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5320 return DAG.getBitcast(Op.getValueType(), SubVec); 5321 } 5322 SDValue Mask = 5323 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5324 // Set the vector length to only the number of elements we care about. Note 5325 // that for slideup this includes the offset. 5326 SDValue VL = 5327 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5328 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5329 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5330 SubVec, SlideupAmt, Mask, VL); 5331 if (VecVT.isFixedLengthVector()) 5332 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5333 return DAG.getBitcast(Op.getValueType(), Slideup); 5334 } 5335 5336 unsigned SubRegIdx, RemIdx; 5337 std::tie(SubRegIdx, RemIdx) = 5338 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5339 VecVT, SubVecVT, OrigIdx, TRI); 5340 5341 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5342 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5343 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5344 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5345 5346 // 1. If the Idx has been completely eliminated and this subvector's size is 5347 // a vector register or a multiple thereof, or the surrounding elements are 5348 // undef, then this is a subvector insert which naturally aligns to a vector 5349 // register. These can easily be handled using subregister manipulation. 5350 // 2. If the subvector is smaller than a vector register, then the insertion 5351 // must preserve the undisturbed elements of the register. We do this by 5352 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5353 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5354 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5355 // LMUL=1 type back into the larger vector (resolving to another subregister 5356 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5357 // to avoid allocating a large register group to hold our subvector. 5358 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5359 return Op; 5360 5361 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5362 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5363 // (in our case undisturbed). This means we can set up a subvector insertion 5364 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5365 // size of the subvector. 5366 MVT InterSubVT = VecVT; 5367 SDValue AlignedExtract = Vec; 5368 unsigned AlignedIdx = OrigIdx - RemIdx; 5369 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5370 InterSubVT = getLMUL1VT(VecVT); 5371 // Extract a subvector equal to the nearest full vector register type. This 5372 // should resolve to a EXTRACT_SUBREG instruction. 5373 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5374 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5375 } 5376 5377 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5378 // For scalable vectors this must be further multiplied by vscale. 5379 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5380 5381 SDValue Mask, VL; 5382 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5383 5384 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5385 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5386 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5387 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5388 5389 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5390 DAG.getUNDEF(InterSubVT), SubVec, 5391 DAG.getConstant(0, DL, XLenVT)); 5392 5393 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5394 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5395 5396 // If required, insert this subvector back into the correct vector register. 5397 // This should resolve to an INSERT_SUBREG instruction. 5398 if (VecVT.bitsGT(InterSubVT)) 5399 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5400 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5401 5402 // We might have bitcast from a mask type: cast back to the original type if 5403 // required. 5404 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5405 } 5406 5407 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5408 SelectionDAG &DAG) const { 5409 SDValue Vec = Op.getOperand(0); 5410 MVT SubVecVT = Op.getSimpleValueType(); 5411 MVT VecVT = Vec.getSimpleValueType(); 5412 5413 SDLoc DL(Op); 5414 MVT XLenVT = Subtarget.getXLenVT(); 5415 unsigned OrigIdx = Op.getConstantOperandVal(1); 5416 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5417 5418 // We don't have the ability to slide mask vectors down indexed by their i1 5419 // elements; the smallest we can do is i8. Often we are able to bitcast to 5420 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5421 // from a scalable one, we might not necessarily have enough scalable 5422 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5423 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5424 if (VecVT.getVectorMinNumElements() >= 8 && 5425 SubVecVT.getVectorMinNumElements() >= 8) { 5426 assert(OrigIdx % 8 == 0 && "Invalid index"); 5427 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5428 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5429 "Unexpected mask vector lowering"); 5430 OrigIdx /= 8; 5431 SubVecVT = 5432 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5433 SubVecVT.isScalableVector()); 5434 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5435 VecVT.isScalableVector()); 5436 Vec = DAG.getBitcast(VecVT, Vec); 5437 } else { 5438 // We can't slide this mask vector down, indexed by its i1 elements. 5439 // This poses a problem when we wish to extract a scalable vector which 5440 // can't be re-expressed as a larger type. Just choose the slow path and 5441 // extend to a larger type, then truncate back down. 5442 // TODO: We could probably improve this when extracting certain fixed 5443 // from fixed, where we can extract as i8 and shift the correct element 5444 // right to reach the desired subvector? 5445 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5446 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5447 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5448 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5449 Op.getOperand(1)); 5450 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5451 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5452 } 5453 } 5454 5455 // If the subvector vector is a fixed-length type, we cannot use subregister 5456 // manipulation to simplify the codegen; we don't know which register of a 5457 // LMUL group contains the specific subvector as we only know the minimum 5458 // register size. Therefore we must slide the vector group down the full 5459 // amount. 5460 if (SubVecVT.isFixedLengthVector()) { 5461 // With an index of 0 this is a cast-like subvector, which can be performed 5462 // with subregister operations. 5463 if (OrigIdx == 0) 5464 return Op; 5465 MVT ContainerVT = VecVT; 5466 if (VecVT.isFixedLengthVector()) { 5467 ContainerVT = getContainerForFixedLengthVector(VecVT); 5468 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5469 } 5470 SDValue Mask = 5471 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5472 // Set the vector length to only the number of elements we care about. This 5473 // avoids sliding down elements we're going to discard straight away. 5474 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5475 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5476 SDValue Slidedown = 5477 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5478 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5479 // Now we can use a cast-like subvector extract to get the result. 5480 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5481 DAG.getConstant(0, DL, XLenVT)); 5482 return DAG.getBitcast(Op.getValueType(), Slidedown); 5483 } 5484 5485 unsigned SubRegIdx, RemIdx; 5486 std::tie(SubRegIdx, RemIdx) = 5487 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5488 VecVT, SubVecVT, OrigIdx, TRI); 5489 5490 // If the Idx has been completely eliminated then this is a subvector extract 5491 // which naturally aligns to a vector register. These can easily be handled 5492 // using subregister manipulation. 5493 if (RemIdx == 0) 5494 return Op; 5495 5496 // Else we must shift our vector register directly to extract the subvector. 5497 // Do this using VSLIDEDOWN. 5498 5499 // If the vector type is an LMUL-group type, extract a subvector equal to the 5500 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5501 // instruction. 5502 MVT InterSubVT = VecVT; 5503 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5504 InterSubVT = getLMUL1VT(VecVT); 5505 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5506 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5507 } 5508 5509 // Slide this vector register down by the desired number of elements in order 5510 // to place the desired subvector starting at element 0. 5511 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5512 // For scalable vectors this must be further multiplied by vscale. 5513 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5514 5515 SDValue Mask, VL; 5516 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5517 SDValue Slidedown = 5518 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5519 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5520 5521 // Now the vector is in the right position, extract our final subvector. This 5522 // should resolve to a COPY. 5523 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5524 DAG.getConstant(0, DL, XLenVT)); 5525 5526 // We might have bitcast from a mask type: cast back to the original type if 5527 // required. 5528 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5529 } 5530 5531 // Lower step_vector to the vid instruction. Any non-identity step value must 5532 // be accounted for my manual expansion. 5533 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5534 SelectionDAG &DAG) const { 5535 SDLoc DL(Op); 5536 MVT VT = Op.getSimpleValueType(); 5537 MVT XLenVT = Subtarget.getXLenVT(); 5538 SDValue Mask, VL; 5539 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5540 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5541 uint64_t StepValImm = Op.getConstantOperandVal(0); 5542 if (StepValImm != 1) { 5543 if (isPowerOf2_64(StepValImm)) { 5544 SDValue StepVal = 5545 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5546 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5547 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5548 } else { 5549 SDValue StepVal = lowerScalarSplat( 5550 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5551 VL, VT, DL, DAG, Subtarget); 5552 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5553 } 5554 } 5555 return StepVec; 5556 } 5557 5558 // Implement vector_reverse using vrgather.vv with indices determined by 5559 // subtracting the id of each element from (VLMAX-1). This will convert 5560 // the indices like so: 5561 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5562 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5563 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5564 SelectionDAG &DAG) const { 5565 SDLoc DL(Op); 5566 MVT VecVT = Op.getSimpleValueType(); 5567 unsigned EltSize = VecVT.getScalarSizeInBits(); 5568 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5569 5570 unsigned MaxVLMAX = 0; 5571 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5572 if (VectorBitsMax != 0) 5573 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5574 5575 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5576 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5577 5578 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5579 // to use vrgatherei16.vv. 5580 // TODO: It's also possible to use vrgatherei16.vv for other types to 5581 // decrease register width for the index calculation. 5582 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5583 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5584 // Reverse each half, then reassemble them in reverse order. 5585 // NOTE: It's also possible that after splitting that VLMAX no longer 5586 // requires vrgatherei16.vv. 5587 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5588 SDValue Lo, Hi; 5589 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5590 EVT LoVT, HiVT; 5591 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5592 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5593 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5594 // Reassemble the low and high pieces reversed. 5595 // FIXME: This is a CONCAT_VECTORS. 5596 SDValue Res = 5597 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5598 DAG.getIntPtrConstant(0, DL)); 5599 return DAG.getNode( 5600 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5601 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5602 } 5603 5604 // Just promote the int type to i16 which will double the LMUL. 5605 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5606 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5607 } 5608 5609 MVT XLenVT = Subtarget.getXLenVT(); 5610 SDValue Mask, VL; 5611 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5612 5613 // Calculate VLMAX-1 for the desired SEW. 5614 unsigned MinElts = VecVT.getVectorMinNumElements(); 5615 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5616 DAG.getConstant(MinElts, DL, XLenVT)); 5617 SDValue VLMinus1 = 5618 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5619 5620 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5621 bool IsRV32E64 = 5622 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5623 SDValue SplatVL; 5624 if (!IsRV32E64) 5625 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5626 else 5627 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5628 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5629 5630 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5631 SDValue Indices = 5632 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5633 5634 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5635 } 5636 5637 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5638 SelectionDAG &DAG) const { 5639 SDLoc DL(Op); 5640 SDValue V1 = Op.getOperand(0); 5641 SDValue V2 = Op.getOperand(1); 5642 MVT XLenVT = Subtarget.getXLenVT(); 5643 MVT VecVT = Op.getSimpleValueType(); 5644 5645 unsigned MinElts = VecVT.getVectorMinNumElements(); 5646 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5647 DAG.getConstant(MinElts, DL, XLenVT)); 5648 5649 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5650 SDValue DownOffset, UpOffset; 5651 if (ImmValue >= 0) { 5652 // The operand is a TargetConstant, we need to rebuild it as a regular 5653 // constant. 5654 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5655 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5656 } else { 5657 // The operand is a TargetConstant, we need to rebuild it as a regular 5658 // constant rather than negating the original operand. 5659 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5660 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5661 } 5662 5663 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5664 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5665 5666 SDValue SlideDown = 5667 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5668 DownOffset, TrueMask, UpOffset); 5669 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5670 TrueMask, 5671 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5672 } 5673 5674 SDValue 5675 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5676 SelectionDAG &DAG) const { 5677 SDLoc DL(Op); 5678 auto *Load = cast<LoadSDNode>(Op); 5679 5680 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5681 Load->getMemoryVT(), 5682 *Load->getMemOperand()) && 5683 "Expecting a correctly-aligned load"); 5684 5685 MVT VT = Op.getSimpleValueType(); 5686 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5687 5688 SDValue VL = 5689 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5690 5691 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5692 SDValue NewLoad = DAG.getMemIntrinsicNode( 5693 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5694 Load->getMemoryVT(), Load->getMemOperand()); 5695 5696 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5697 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5698 } 5699 5700 SDValue 5701 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5702 SelectionDAG &DAG) const { 5703 SDLoc DL(Op); 5704 auto *Store = cast<StoreSDNode>(Op); 5705 5706 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5707 Store->getMemoryVT(), 5708 *Store->getMemOperand()) && 5709 "Expecting a correctly-aligned store"); 5710 5711 SDValue StoreVal = Store->getValue(); 5712 MVT VT = StoreVal.getSimpleValueType(); 5713 5714 // If the size less than a byte, we need to pad with zeros to make a byte. 5715 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5716 VT = MVT::v8i1; 5717 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5718 DAG.getConstant(0, DL, VT), StoreVal, 5719 DAG.getIntPtrConstant(0, DL)); 5720 } 5721 5722 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5723 5724 SDValue VL = 5725 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5726 5727 SDValue NewValue = 5728 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5729 return DAG.getMemIntrinsicNode( 5730 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5731 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5732 Store->getMemoryVT(), Store->getMemOperand()); 5733 } 5734 5735 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5736 SelectionDAG &DAG) const { 5737 SDLoc DL(Op); 5738 MVT VT = Op.getSimpleValueType(); 5739 5740 const auto *MemSD = cast<MemSDNode>(Op); 5741 EVT MemVT = MemSD->getMemoryVT(); 5742 MachineMemOperand *MMO = MemSD->getMemOperand(); 5743 SDValue Chain = MemSD->getChain(); 5744 SDValue BasePtr = MemSD->getBasePtr(); 5745 5746 SDValue Mask, PassThru, VL; 5747 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5748 Mask = VPLoad->getMask(); 5749 PassThru = DAG.getUNDEF(VT); 5750 VL = VPLoad->getVectorLength(); 5751 } else { 5752 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5753 Mask = MLoad->getMask(); 5754 PassThru = MLoad->getPassThru(); 5755 } 5756 5757 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5758 5759 MVT XLenVT = Subtarget.getXLenVT(); 5760 5761 MVT ContainerVT = VT; 5762 if (VT.isFixedLengthVector()) { 5763 ContainerVT = getContainerForFixedLengthVector(VT); 5764 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5765 if (!IsUnmasked) { 5766 MVT MaskVT = 5767 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5768 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5769 } 5770 } 5771 5772 if (!VL) 5773 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5774 5775 unsigned IntID = 5776 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5777 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5778 if (IsUnmasked) 5779 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5780 else 5781 Ops.push_back(PassThru); 5782 Ops.push_back(BasePtr); 5783 if (!IsUnmasked) 5784 Ops.push_back(Mask); 5785 Ops.push_back(VL); 5786 if (!IsUnmasked) 5787 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5788 5789 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5790 5791 SDValue Result = 5792 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5793 Chain = Result.getValue(1); 5794 5795 if (VT.isFixedLengthVector()) 5796 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5797 5798 return DAG.getMergeValues({Result, Chain}, DL); 5799 } 5800 5801 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5802 SelectionDAG &DAG) const { 5803 SDLoc DL(Op); 5804 5805 const auto *MemSD = cast<MemSDNode>(Op); 5806 EVT MemVT = MemSD->getMemoryVT(); 5807 MachineMemOperand *MMO = MemSD->getMemOperand(); 5808 SDValue Chain = MemSD->getChain(); 5809 SDValue BasePtr = MemSD->getBasePtr(); 5810 SDValue Val, Mask, VL; 5811 5812 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5813 Val = VPStore->getValue(); 5814 Mask = VPStore->getMask(); 5815 VL = VPStore->getVectorLength(); 5816 } else { 5817 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5818 Val = MStore->getValue(); 5819 Mask = MStore->getMask(); 5820 } 5821 5822 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5823 5824 MVT VT = Val.getSimpleValueType(); 5825 MVT XLenVT = Subtarget.getXLenVT(); 5826 5827 MVT ContainerVT = VT; 5828 if (VT.isFixedLengthVector()) { 5829 ContainerVT = getContainerForFixedLengthVector(VT); 5830 5831 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5832 if (!IsUnmasked) { 5833 MVT MaskVT = 5834 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5835 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5836 } 5837 } 5838 5839 if (!VL) 5840 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5841 5842 unsigned IntID = 5843 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5844 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5845 Ops.push_back(Val); 5846 Ops.push_back(BasePtr); 5847 if (!IsUnmasked) 5848 Ops.push_back(Mask); 5849 Ops.push_back(VL); 5850 5851 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5852 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5853 } 5854 5855 SDValue 5856 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5857 SelectionDAG &DAG) const { 5858 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5859 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5860 5861 MVT VT = Op.getSimpleValueType(); 5862 5863 SDValue Op1 = 5864 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5865 SDValue Op2 = 5866 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5867 5868 SDLoc DL(Op); 5869 SDValue VL = 5870 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5871 5872 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5873 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5874 5875 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5876 Op.getOperand(2), Mask, VL); 5877 5878 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5879 } 5880 5881 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5882 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5883 MVT VT = Op.getSimpleValueType(); 5884 5885 if (VT.getVectorElementType() == MVT::i1) 5886 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5887 5888 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5889 } 5890 5891 SDValue 5892 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5893 SelectionDAG &DAG) const { 5894 unsigned Opc; 5895 switch (Op.getOpcode()) { 5896 default: llvm_unreachable("Unexpected opcode!"); 5897 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5898 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5899 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5900 } 5901 5902 return lowerToScalableOp(Op, DAG, Opc); 5903 } 5904 5905 // Lower vector ABS to smax(X, sub(0, X)). 5906 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5907 SDLoc DL(Op); 5908 MVT VT = Op.getSimpleValueType(); 5909 SDValue X = Op.getOperand(0); 5910 5911 assert(VT.isFixedLengthVector() && "Unexpected type"); 5912 5913 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5914 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5915 5916 SDValue Mask, VL; 5917 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5918 5919 SDValue SplatZero = DAG.getNode( 5920 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5921 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5922 SDValue NegX = 5923 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5924 SDValue Max = 5925 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5926 5927 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5928 } 5929 5930 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5931 SDValue Op, SelectionDAG &DAG) const { 5932 SDLoc DL(Op); 5933 MVT VT = Op.getSimpleValueType(); 5934 SDValue Mag = Op.getOperand(0); 5935 SDValue Sign = Op.getOperand(1); 5936 assert(Mag.getValueType() == Sign.getValueType() && 5937 "Can only handle COPYSIGN with matching types."); 5938 5939 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5940 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5941 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5942 5943 SDValue Mask, VL; 5944 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5945 5946 SDValue CopySign = 5947 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5948 5949 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5950 } 5951 5952 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5953 SDValue Op, SelectionDAG &DAG) const { 5954 MVT VT = Op.getSimpleValueType(); 5955 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5956 5957 MVT I1ContainerVT = 5958 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5959 5960 SDValue CC = 5961 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5962 SDValue Op1 = 5963 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5964 SDValue Op2 = 5965 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5966 5967 SDLoc DL(Op); 5968 SDValue Mask, VL; 5969 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5970 5971 SDValue Select = 5972 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5973 5974 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5975 } 5976 5977 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5978 unsigned NewOpc, 5979 bool HasMask) const { 5980 MVT VT = Op.getSimpleValueType(); 5981 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5982 5983 // Create list of operands by converting existing ones to scalable types. 5984 SmallVector<SDValue, 6> Ops; 5985 for (const SDValue &V : Op->op_values()) { 5986 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5987 5988 // Pass through non-vector operands. 5989 if (!V.getValueType().isVector()) { 5990 Ops.push_back(V); 5991 continue; 5992 } 5993 5994 // "cast" fixed length vector to a scalable vector. 5995 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5996 "Only fixed length vectors are supported!"); 5997 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5998 } 5999 6000 SDLoc DL(Op); 6001 SDValue Mask, VL; 6002 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6003 if (HasMask) 6004 Ops.push_back(Mask); 6005 Ops.push_back(VL); 6006 6007 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6008 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6009 } 6010 6011 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6012 // * Operands of each node are assumed to be in the same order. 6013 // * The EVL operand is promoted from i32 to i64 on RV64. 6014 // * Fixed-length vectors are converted to their scalable-vector container 6015 // types. 6016 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6017 unsigned RISCVISDOpc) const { 6018 SDLoc DL(Op); 6019 MVT VT = Op.getSimpleValueType(); 6020 SmallVector<SDValue, 4> Ops; 6021 6022 for (const auto &OpIdx : enumerate(Op->ops())) { 6023 SDValue V = OpIdx.value(); 6024 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6025 // Pass through operands which aren't fixed-length vectors. 6026 if (!V.getValueType().isFixedLengthVector()) { 6027 Ops.push_back(V); 6028 continue; 6029 } 6030 // "cast" fixed length vector to a scalable vector. 6031 MVT OpVT = V.getSimpleValueType(); 6032 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6033 assert(useRVVForFixedLengthVectorVT(OpVT) && 6034 "Only fixed length vectors are supported!"); 6035 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6036 } 6037 6038 if (!VT.isFixedLengthVector()) 6039 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6040 6041 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6042 6043 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6044 6045 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6046 } 6047 6048 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6049 unsigned MaskOpc, 6050 unsigned VecOpc) const { 6051 MVT VT = Op.getSimpleValueType(); 6052 if (VT.getVectorElementType() != MVT::i1) 6053 return lowerVPOp(Op, DAG, VecOpc); 6054 6055 // It is safe to drop mask parameter as masked-off elements are undef. 6056 SDValue Op1 = Op->getOperand(0); 6057 SDValue Op2 = Op->getOperand(1); 6058 SDValue VL = Op->getOperand(3); 6059 6060 MVT ContainerVT = VT; 6061 const bool IsFixed = VT.isFixedLengthVector(); 6062 if (IsFixed) { 6063 ContainerVT = getContainerForFixedLengthVector(VT); 6064 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6065 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6066 } 6067 6068 SDLoc DL(Op); 6069 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6070 if (!IsFixed) 6071 return Val; 6072 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6073 } 6074 6075 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6076 // matched to a RVV indexed load. The RVV indexed load instructions only 6077 // support the "unsigned unscaled" addressing mode; indices are implicitly 6078 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6079 // signed or scaled indexing is extended to the XLEN value type and scaled 6080 // accordingly. 6081 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6082 SelectionDAG &DAG) const { 6083 SDLoc DL(Op); 6084 MVT VT = Op.getSimpleValueType(); 6085 6086 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6087 EVT MemVT = MemSD->getMemoryVT(); 6088 MachineMemOperand *MMO = MemSD->getMemOperand(); 6089 SDValue Chain = MemSD->getChain(); 6090 SDValue BasePtr = MemSD->getBasePtr(); 6091 6092 ISD::LoadExtType LoadExtType; 6093 SDValue Index, Mask, PassThru, VL; 6094 6095 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6096 Index = VPGN->getIndex(); 6097 Mask = VPGN->getMask(); 6098 PassThru = DAG.getUNDEF(VT); 6099 VL = VPGN->getVectorLength(); 6100 // VP doesn't support extending loads. 6101 LoadExtType = ISD::NON_EXTLOAD; 6102 } else { 6103 // Else it must be a MGATHER. 6104 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6105 Index = MGN->getIndex(); 6106 Mask = MGN->getMask(); 6107 PassThru = MGN->getPassThru(); 6108 LoadExtType = MGN->getExtensionType(); 6109 } 6110 6111 MVT IndexVT = Index.getSimpleValueType(); 6112 MVT XLenVT = Subtarget.getXLenVT(); 6113 6114 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6115 "Unexpected VTs!"); 6116 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6117 // Targets have to explicitly opt-in for extending vector loads. 6118 assert(LoadExtType == ISD::NON_EXTLOAD && 6119 "Unexpected extending MGATHER/VP_GATHER"); 6120 (void)LoadExtType; 6121 6122 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6123 // the selection of the masked intrinsics doesn't do this for us. 6124 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6125 6126 MVT ContainerVT = VT; 6127 if (VT.isFixedLengthVector()) { 6128 // We need to use the larger of the result and index type to determine the 6129 // scalable type to use so we don't increase LMUL for any operand/result. 6130 if (VT.bitsGE(IndexVT)) { 6131 ContainerVT = getContainerForFixedLengthVector(VT); 6132 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6133 ContainerVT.getVectorElementCount()); 6134 } else { 6135 IndexVT = getContainerForFixedLengthVector(IndexVT); 6136 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6137 IndexVT.getVectorElementCount()); 6138 } 6139 6140 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6141 6142 if (!IsUnmasked) { 6143 MVT MaskVT = 6144 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6145 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6146 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6147 } 6148 } 6149 6150 if (!VL) 6151 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6152 6153 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6154 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6155 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6156 VL); 6157 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6158 TrueMask, VL); 6159 } 6160 6161 unsigned IntID = 6162 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6163 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6164 if (IsUnmasked) 6165 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6166 else 6167 Ops.push_back(PassThru); 6168 Ops.push_back(BasePtr); 6169 Ops.push_back(Index); 6170 if (!IsUnmasked) 6171 Ops.push_back(Mask); 6172 Ops.push_back(VL); 6173 if (!IsUnmasked) 6174 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6175 6176 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6177 SDValue Result = 6178 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6179 Chain = Result.getValue(1); 6180 6181 if (VT.isFixedLengthVector()) 6182 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6183 6184 return DAG.getMergeValues({Result, Chain}, DL); 6185 } 6186 6187 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6188 // matched to a RVV indexed store. The RVV indexed store instructions only 6189 // support the "unsigned unscaled" addressing mode; indices are implicitly 6190 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6191 // signed or scaled indexing is extended to the XLEN value type and scaled 6192 // accordingly. 6193 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6194 SelectionDAG &DAG) const { 6195 SDLoc DL(Op); 6196 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6197 EVT MemVT = MemSD->getMemoryVT(); 6198 MachineMemOperand *MMO = MemSD->getMemOperand(); 6199 SDValue Chain = MemSD->getChain(); 6200 SDValue BasePtr = MemSD->getBasePtr(); 6201 6202 bool IsTruncatingStore = false; 6203 SDValue Index, Mask, Val, VL; 6204 6205 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6206 Index = VPSN->getIndex(); 6207 Mask = VPSN->getMask(); 6208 Val = VPSN->getValue(); 6209 VL = VPSN->getVectorLength(); 6210 // VP doesn't support truncating stores. 6211 IsTruncatingStore = false; 6212 } else { 6213 // Else it must be a MSCATTER. 6214 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6215 Index = MSN->getIndex(); 6216 Mask = MSN->getMask(); 6217 Val = MSN->getValue(); 6218 IsTruncatingStore = MSN->isTruncatingStore(); 6219 } 6220 6221 MVT VT = Val.getSimpleValueType(); 6222 MVT IndexVT = Index.getSimpleValueType(); 6223 MVT XLenVT = Subtarget.getXLenVT(); 6224 6225 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6226 "Unexpected VTs!"); 6227 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6228 // Targets have to explicitly opt-in for extending vector loads and 6229 // truncating vector stores. 6230 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6231 (void)IsTruncatingStore; 6232 6233 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6234 // the selection of the masked intrinsics doesn't do this for us. 6235 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6236 6237 MVT ContainerVT = VT; 6238 if (VT.isFixedLengthVector()) { 6239 // We need to use the larger of the value and index type to determine the 6240 // scalable type to use so we don't increase LMUL for any operand/result. 6241 if (VT.bitsGE(IndexVT)) { 6242 ContainerVT = getContainerForFixedLengthVector(VT); 6243 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6244 ContainerVT.getVectorElementCount()); 6245 } else { 6246 IndexVT = getContainerForFixedLengthVector(IndexVT); 6247 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6248 IndexVT.getVectorElementCount()); 6249 } 6250 6251 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6252 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6253 6254 if (!IsUnmasked) { 6255 MVT MaskVT = 6256 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6257 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6258 } 6259 } 6260 6261 if (!VL) 6262 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6263 6264 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6265 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6266 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6267 VL); 6268 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6269 TrueMask, VL); 6270 } 6271 6272 unsigned IntID = 6273 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6274 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6275 Ops.push_back(Val); 6276 Ops.push_back(BasePtr); 6277 Ops.push_back(Index); 6278 if (!IsUnmasked) 6279 Ops.push_back(Mask); 6280 Ops.push_back(VL); 6281 6282 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6283 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6284 } 6285 6286 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6287 SelectionDAG &DAG) const { 6288 const MVT XLenVT = Subtarget.getXLenVT(); 6289 SDLoc DL(Op); 6290 SDValue Chain = Op->getOperand(0); 6291 SDValue SysRegNo = DAG.getTargetConstant( 6292 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6293 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6294 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6295 6296 // Encoding used for rounding mode in RISCV differs from that used in 6297 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6298 // table, which consists of a sequence of 4-bit fields, each representing 6299 // corresponding FLT_ROUNDS mode. 6300 static const int Table = 6301 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6302 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6303 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6304 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6305 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6306 6307 SDValue Shift = 6308 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6309 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6310 DAG.getConstant(Table, DL, XLenVT), Shift); 6311 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6312 DAG.getConstant(7, DL, XLenVT)); 6313 6314 return DAG.getMergeValues({Masked, Chain}, DL); 6315 } 6316 6317 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6318 SelectionDAG &DAG) const { 6319 const MVT XLenVT = Subtarget.getXLenVT(); 6320 SDLoc DL(Op); 6321 SDValue Chain = Op->getOperand(0); 6322 SDValue RMValue = Op->getOperand(1); 6323 SDValue SysRegNo = DAG.getTargetConstant( 6324 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6325 6326 // Encoding used for rounding mode in RISCV differs from that used in 6327 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6328 // a table, which consists of a sequence of 4-bit fields, each representing 6329 // corresponding RISCV mode. 6330 static const unsigned Table = 6331 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6332 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6333 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6334 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6335 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6336 6337 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6338 DAG.getConstant(2, DL, XLenVT)); 6339 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6340 DAG.getConstant(Table, DL, XLenVT), Shift); 6341 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6342 DAG.getConstant(0x7, DL, XLenVT)); 6343 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6344 RMValue); 6345 } 6346 6347 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6348 switch (IntNo) { 6349 default: 6350 llvm_unreachable("Unexpected Intrinsic"); 6351 case Intrinsic::riscv_grev: 6352 return RISCVISD::GREVW; 6353 case Intrinsic::riscv_gorc: 6354 return RISCVISD::GORCW; 6355 case Intrinsic::riscv_bcompress: 6356 return RISCVISD::BCOMPRESSW; 6357 case Intrinsic::riscv_bdecompress: 6358 return RISCVISD::BDECOMPRESSW; 6359 case Intrinsic::riscv_bfp: 6360 return RISCVISD::BFPW; 6361 case Intrinsic::riscv_fsl: 6362 return RISCVISD::FSLW; 6363 case Intrinsic::riscv_fsr: 6364 return RISCVISD::FSRW; 6365 } 6366 } 6367 6368 // Converts the given intrinsic to a i64 operation with any extension. 6369 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6370 unsigned IntNo) { 6371 SDLoc DL(N); 6372 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6373 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6374 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6375 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6376 // ReplaceNodeResults requires we maintain the same type for the return value. 6377 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6378 } 6379 6380 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6381 // form of the given Opcode. 6382 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6383 switch (Opcode) { 6384 default: 6385 llvm_unreachable("Unexpected opcode"); 6386 case ISD::SHL: 6387 return RISCVISD::SLLW; 6388 case ISD::SRA: 6389 return RISCVISD::SRAW; 6390 case ISD::SRL: 6391 return RISCVISD::SRLW; 6392 case ISD::SDIV: 6393 return RISCVISD::DIVW; 6394 case ISD::UDIV: 6395 return RISCVISD::DIVUW; 6396 case ISD::UREM: 6397 return RISCVISD::REMUW; 6398 case ISD::ROTL: 6399 return RISCVISD::ROLW; 6400 case ISD::ROTR: 6401 return RISCVISD::RORW; 6402 case RISCVISD::GREV: 6403 return RISCVISD::GREVW; 6404 case RISCVISD::GORC: 6405 return RISCVISD::GORCW; 6406 } 6407 } 6408 6409 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6410 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6411 // otherwise be promoted to i64, making it difficult to select the 6412 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6413 // type i8/i16/i32 is lost. 6414 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6415 unsigned ExtOpc = ISD::ANY_EXTEND) { 6416 SDLoc DL(N); 6417 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6418 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6419 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6420 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6421 // ReplaceNodeResults requires we maintain the same type for the return value. 6422 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6423 } 6424 6425 // Converts the given 32-bit operation to a i64 operation with signed extension 6426 // semantic to reduce the signed extension instructions. 6427 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6428 SDLoc DL(N); 6429 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6430 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6431 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6432 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6433 DAG.getValueType(MVT::i32)); 6434 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6435 } 6436 6437 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6438 SmallVectorImpl<SDValue> &Results, 6439 SelectionDAG &DAG) const { 6440 SDLoc DL(N); 6441 switch (N->getOpcode()) { 6442 default: 6443 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6444 case ISD::STRICT_FP_TO_SINT: 6445 case ISD::STRICT_FP_TO_UINT: 6446 case ISD::FP_TO_SINT: 6447 case ISD::FP_TO_UINT: { 6448 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6449 "Unexpected custom legalisation"); 6450 bool IsStrict = N->isStrictFPOpcode(); 6451 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6452 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6453 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6454 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6455 TargetLowering::TypeSoftenFloat) { 6456 if (!isTypeLegal(Op0.getValueType())) 6457 return; 6458 if (IsStrict) { 6459 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6460 : RISCVISD::STRICT_FCVT_WU_RV64; 6461 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6462 SDValue Res = DAG.getNode( 6463 Opc, DL, VTs, N->getOperand(0), Op0, 6464 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6465 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6466 Results.push_back(Res.getValue(1)); 6467 return; 6468 } 6469 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6470 SDValue Res = 6471 DAG.getNode(Opc, DL, MVT::i64, Op0, 6472 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6473 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6474 return; 6475 } 6476 // If the FP type needs to be softened, emit a library call using the 'si' 6477 // version. If we left it to default legalization we'd end up with 'di'. If 6478 // the FP type doesn't need to be softened just let generic type 6479 // legalization promote the result type. 6480 RTLIB::Libcall LC; 6481 if (IsSigned) 6482 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6483 else 6484 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6485 MakeLibCallOptions CallOptions; 6486 EVT OpVT = Op0.getValueType(); 6487 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6488 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6489 SDValue Result; 6490 std::tie(Result, Chain) = 6491 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6492 Results.push_back(Result); 6493 if (IsStrict) 6494 Results.push_back(Chain); 6495 break; 6496 } 6497 case ISD::READCYCLECOUNTER: { 6498 assert(!Subtarget.is64Bit() && 6499 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6500 6501 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6502 SDValue RCW = 6503 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6504 6505 Results.push_back( 6506 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6507 Results.push_back(RCW.getValue(2)); 6508 break; 6509 } 6510 case ISD::MUL: { 6511 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6512 unsigned XLen = Subtarget.getXLen(); 6513 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6514 if (Size > XLen) { 6515 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6516 SDValue LHS = N->getOperand(0); 6517 SDValue RHS = N->getOperand(1); 6518 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6519 6520 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6521 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6522 // We need exactly one side to be unsigned. 6523 if (LHSIsU == RHSIsU) 6524 return; 6525 6526 auto MakeMULPair = [&](SDValue S, SDValue U) { 6527 MVT XLenVT = Subtarget.getXLenVT(); 6528 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6529 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6530 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6531 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6532 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6533 }; 6534 6535 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6536 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6537 6538 // The other operand should be signed, but still prefer MULH when 6539 // possible. 6540 if (RHSIsU && LHSIsS && !RHSIsS) 6541 Results.push_back(MakeMULPair(LHS, RHS)); 6542 else if (LHSIsU && RHSIsS && !LHSIsS) 6543 Results.push_back(MakeMULPair(RHS, LHS)); 6544 6545 return; 6546 } 6547 LLVM_FALLTHROUGH; 6548 } 6549 case ISD::ADD: 6550 case ISD::SUB: 6551 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6552 "Unexpected custom legalisation"); 6553 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6554 break; 6555 case ISD::SHL: 6556 case ISD::SRA: 6557 case ISD::SRL: 6558 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6559 "Unexpected custom legalisation"); 6560 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6561 Results.push_back(customLegalizeToWOp(N, DAG)); 6562 break; 6563 } 6564 6565 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6566 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6567 // shift amount. 6568 if (N->getOpcode() == ISD::SHL) { 6569 SDLoc DL(N); 6570 SDValue NewOp0 = 6571 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6572 SDValue NewOp1 = 6573 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6574 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6575 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6576 DAG.getValueType(MVT::i32)); 6577 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6578 } 6579 6580 break; 6581 case ISD::ROTL: 6582 case ISD::ROTR: 6583 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6584 "Unexpected custom legalisation"); 6585 Results.push_back(customLegalizeToWOp(N, DAG)); 6586 break; 6587 case ISD::CTTZ: 6588 case ISD::CTTZ_ZERO_UNDEF: 6589 case ISD::CTLZ: 6590 case ISD::CTLZ_ZERO_UNDEF: { 6591 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6592 "Unexpected custom legalisation"); 6593 6594 SDValue NewOp0 = 6595 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6596 bool IsCTZ = 6597 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6598 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6599 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6600 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6601 return; 6602 } 6603 case ISD::SDIV: 6604 case ISD::UDIV: 6605 case ISD::UREM: { 6606 MVT VT = N->getSimpleValueType(0); 6607 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6608 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6609 "Unexpected custom legalisation"); 6610 // Don't promote division/remainder by constant since we should expand those 6611 // to multiply by magic constant. 6612 // FIXME: What if the expansion is disabled for minsize. 6613 if (N->getOperand(1).getOpcode() == ISD::Constant) 6614 return; 6615 6616 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6617 // the upper 32 bits. For other types we need to sign or zero extend 6618 // based on the opcode. 6619 unsigned ExtOpc = ISD::ANY_EXTEND; 6620 if (VT != MVT::i32) 6621 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6622 : ISD::ZERO_EXTEND; 6623 6624 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6625 break; 6626 } 6627 case ISD::UADDO: 6628 case ISD::USUBO: { 6629 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6630 "Unexpected custom legalisation"); 6631 bool IsAdd = N->getOpcode() == ISD::UADDO; 6632 // Create an ADDW or SUBW. 6633 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6634 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6635 SDValue Res = 6636 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6637 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6638 DAG.getValueType(MVT::i32)); 6639 6640 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6641 // Since the inputs are sign extended from i32, this is equivalent to 6642 // comparing the lower 32 bits. 6643 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6644 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6645 IsAdd ? ISD::SETULT : ISD::SETUGT); 6646 6647 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6648 Results.push_back(Overflow); 6649 return; 6650 } 6651 case ISD::UADDSAT: 6652 case ISD::USUBSAT: { 6653 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6654 "Unexpected custom legalisation"); 6655 if (Subtarget.hasStdExtZbb()) { 6656 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6657 // sign extend allows overflow of the lower 32 bits to be detected on 6658 // the promoted size. 6659 SDValue LHS = 6660 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6661 SDValue RHS = 6662 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6663 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6664 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6665 return; 6666 } 6667 6668 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6669 // promotion for UADDO/USUBO. 6670 Results.push_back(expandAddSubSat(N, DAG)); 6671 return; 6672 } 6673 case ISD::ABS: { 6674 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6675 "Unexpected custom legalisation"); 6676 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6677 6678 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6679 6680 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6681 6682 // Freeze the source so we can increase it's use count. 6683 Src = DAG.getFreeze(Src); 6684 6685 // Copy sign bit to all bits using the sraiw pattern. 6686 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6687 DAG.getValueType(MVT::i32)); 6688 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6689 DAG.getConstant(31, DL, MVT::i64)); 6690 6691 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6692 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6693 6694 // NOTE: The result is only required to be anyextended, but sext is 6695 // consistent with type legalization of sub. 6696 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6697 DAG.getValueType(MVT::i32)); 6698 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6699 return; 6700 } 6701 case ISD::BITCAST: { 6702 EVT VT = N->getValueType(0); 6703 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6704 SDValue Op0 = N->getOperand(0); 6705 EVT Op0VT = Op0.getValueType(); 6706 MVT XLenVT = Subtarget.getXLenVT(); 6707 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6708 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6709 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6710 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6711 Subtarget.hasStdExtF()) { 6712 SDValue FPConv = 6713 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6714 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6715 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6716 isTypeLegal(Op0VT)) { 6717 // Custom-legalize bitcasts from fixed-length vector types to illegal 6718 // scalar types in order to improve codegen. Bitcast the vector to a 6719 // one-element vector type whose element type is the same as the result 6720 // type, and extract the first element. 6721 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6722 if (isTypeLegal(BVT)) { 6723 SDValue BVec = DAG.getBitcast(BVT, Op0); 6724 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6725 DAG.getConstant(0, DL, XLenVT))); 6726 } 6727 } 6728 break; 6729 } 6730 case RISCVISD::GREV: 6731 case RISCVISD::GORC: { 6732 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6733 "Unexpected custom legalisation"); 6734 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6735 // This is similar to customLegalizeToWOp, except that we pass the second 6736 // operand (a TargetConstant) straight through: it is already of type 6737 // XLenVT. 6738 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6739 SDValue NewOp0 = 6740 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6741 SDValue NewOp1 = 6742 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6743 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6744 // ReplaceNodeResults requires we maintain the same type for the return 6745 // value. 6746 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6747 break; 6748 } 6749 case RISCVISD::SHFL: { 6750 // There is no SHFLIW instruction, but we can just promote the operation. 6751 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6752 "Unexpected custom legalisation"); 6753 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6754 SDValue NewOp0 = 6755 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6756 SDValue NewOp1 = 6757 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6758 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6759 // ReplaceNodeResults requires we maintain the same type for the return 6760 // value. 6761 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6762 break; 6763 } 6764 case ISD::BSWAP: 6765 case ISD::BITREVERSE: { 6766 MVT VT = N->getSimpleValueType(0); 6767 MVT XLenVT = Subtarget.getXLenVT(); 6768 assert((VT == MVT::i8 || VT == MVT::i16 || 6769 (VT == MVT::i32 && Subtarget.is64Bit())) && 6770 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6771 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6772 unsigned Imm = VT.getSizeInBits() - 1; 6773 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6774 if (N->getOpcode() == ISD::BSWAP) 6775 Imm &= ~0x7U; 6776 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6777 SDValue GREVI = 6778 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6779 // ReplaceNodeResults requires we maintain the same type for the return 6780 // value. 6781 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6782 break; 6783 } 6784 case ISD::FSHL: 6785 case ISD::FSHR: { 6786 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6787 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6788 SDValue NewOp0 = 6789 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6790 SDValue NewOp1 = 6791 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6792 SDValue NewShAmt = 6793 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6794 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6795 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6796 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6797 DAG.getConstant(0x1f, DL, MVT::i64)); 6798 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6799 // instruction use different orders. fshl will return its first operand for 6800 // shift of zero, fshr will return its second operand. fsl and fsr both 6801 // return rs1 so the ISD nodes need to have different operand orders. 6802 // Shift amount is in rs2. 6803 unsigned Opc = RISCVISD::FSLW; 6804 if (N->getOpcode() == ISD::FSHR) { 6805 std::swap(NewOp0, NewOp1); 6806 Opc = RISCVISD::FSRW; 6807 } 6808 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6809 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6810 break; 6811 } 6812 case ISD::EXTRACT_VECTOR_ELT: { 6813 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6814 // type is illegal (currently only vXi64 RV32). 6815 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6816 // transferred to the destination register. We issue two of these from the 6817 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6818 // first element. 6819 SDValue Vec = N->getOperand(0); 6820 SDValue Idx = N->getOperand(1); 6821 6822 // The vector type hasn't been legalized yet so we can't issue target 6823 // specific nodes if it needs legalization. 6824 // FIXME: We would manually legalize if it's important. 6825 if (!isTypeLegal(Vec.getValueType())) 6826 return; 6827 6828 MVT VecVT = Vec.getSimpleValueType(); 6829 6830 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6831 VecVT.getVectorElementType() == MVT::i64 && 6832 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6833 6834 // If this is a fixed vector, we need to convert it to a scalable vector. 6835 MVT ContainerVT = VecVT; 6836 if (VecVT.isFixedLengthVector()) { 6837 ContainerVT = getContainerForFixedLengthVector(VecVT); 6838 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6839 } 6840 6841 MVT XLenVT = Subtarget.getXLenVT(); 6842 6843 // Use a VL of 1 to avoid processing more elements than we need. 6844 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6845 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6846 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6847 6848 // Unless the index is known to be 0, we must slide the vector down to get 6849 // the desired element into index 0. 6850 if (!isNullConstant(Idx)) { 6851 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6852 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6853 } 6854 6855 // Extract the lower XLEN bits of the correct vector element. 6856 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6857 6858 // To extract the upper XLEN bits of the vector element, shift the first 6859 // element right by 32 bits and re-extract the lower XLEN bits. 6860 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6861 DAG.getUNDEF(ContainerVT), 6862 DAG.getConstant(32, DL, XLenVT), VL); 6863 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6864 ThirtyTwoV, Mask, VL); 6865 6866 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6867 6868 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6869 break; 6870 } 6871 case ISD::INTRINSIC_WO_CHAIN: { 6872 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6873 switch (IntNo) { 6874 default: 6875 llvm_unreachable( 6876 "Don't know how to custom type legalize this intrinsic!"); 6877 case Intrinsic::riscv_grev: 6878 case Intrinsic::riscv_gorc: 6879 case Intrinsic::riscv_bcompress: 6880 case Intrinsic::riscv_bdecompress: 6881 case Intrinsic::riscv_bfp: { 6882 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6883 "Unexpected custom legalisation"); 6884 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6885 break; 6886 } 6887 case Intrinsic::riscv_fsl: 6888 case Intrinsic::riscv_fsr: { 6889 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6890 "Unexpected custom legalisation"); 6891 SDValue NewOp1 = 6892 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6893 SDValue NewOp2 = 6894 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6895 SDValue NewOp3 = 6896 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6897 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6898 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6899 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6900 break; 6901 } 6902 case Intrinsic::riscv_orc_b: { 6903 // Lower to the GORCI encoding for orc.b with the operand extended. 6904 SDValue NewOp = 6905 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6906 // If Zbp is enabled, use GORCIW which will sign extend the result. 6907 unsigned Opc = 6908 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6909 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6910 DAG.getConstant(7, DL, MVT::i64)); 6911 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6912 return; 6913 } 6914 case Intrinsic::riscv_shfl: 6915 case Intrinsic::riscv_unshfl: { 6916 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6917 "Unexpected custom legalisation"); 6918 SDValue NewOp1 = 6919 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6920 SDValue NewOp2 = 6921 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6922 unsigned Opc = 6923 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6924 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6925 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6926 // will be shuffled the same way as the lower 32 bit half, but the two 6927 // halves won't cross. 6928 if (isa<ConstantSDNode>(NewOp2)) { 6929 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6930 DAG.getConstant(0xf, DL, MVT::i64)); 6931 Opc = 6932 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6933 } 6934 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6935 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6936 break; 6937 } 6938 case Intrinsic::riscv_vmv_x_s: { 6939 EVT VT = N->getValueType(0); 6940 MVT XLenVT = Subtarget.getXLenVT(); 6941 if (VT.bitsLT(XLenVT)) { 6942 // Simple case just extract using vmv.x.s and truncate. 6943 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6944 Subtarget.getXLenVT(), N->getOperand(1)); 6945 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6946 return; 6947 } 6948 6949 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6950 "Unexpected custom legalization"); 6951 6952 // We need to do the move in two steps. 6953 SDValue Vec = N->getOperand(1); 6954 MVT VecVT = Vec.getSimpleValueType(); 6955 6956 // First extract the lower XLEN bits of the element. 6957 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6958 6959 // To extract the upper XLEN bits of the vector element, shift the first 6960 // element right by 32 bits and re-extract the lower XLEN bits. 6961 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6962 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6963 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6964 SDValue ThirtyTwoV = 6965 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 6966 DAG.getConstant(32, DL, XLenVT), VL); 6967 SDValue LShr32 = 6968 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6969 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6970 6971 Results.push_back( 6972 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6973 break; 6974 } 6975 } 6976 break; 6977 } 6978 case ISD::VECREDUCE_ADD: 6979 case ISD::VECREDUCE_AND: 6980 case ISD::VECREDUCE_OR: 6981 case ISD::VECREDUCE_XOR: 6982 case ISD::VECREDUCE_SMAX: 6983 case ISD::VECREDUCE_UMAX: 6984 case ISD::VECREDUCE_SMIN: 6985 case ISD::VECREDUCE_UMIN: 6986 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6987 Results.push_back(V); 6988 break; 6989 case ISD::VP_REDUCE_ADD: 6990 case ISD::VP_REDUCE_AND: 6991 case ISD::VP_REDUCE_OR: 6992 case ISD::VP_REDUCE_XOR: 6993 case ISD::VP_REDUCE_SMAX: 6994 case ISD::VP_REDUCE_UMAX: 6995 case ISD::VP_REDUCE_SMIN: 6996 case ISD::VP_REDUCE_UMIN: 6997 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6998 Results.push_back(V); 6999 break; 7000 case ISD::FLT_ROUNDS_: { 7001 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7002 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7003 Results.push_back(Res.getValue(0)); 7004 Results.push_back(Res.getValue(1)); 7005 break; 7006 } 7007 } 7008 } 7009 7010 // A structure to hold one of the bit-manipulation patterns below. Together, a 7011 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7012 // (or (and (shl x, 1), 0xAAAAAAAA), 7013 // (and (srl x, 1), 0x55555555)) 7014 struct RISCVBitmanipPat { 7015 SDValue Op; 7016 unsigned ShAmt; 7017 bool IsSHL; 7018 7019 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7020 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7021 } 7022 }; 7023 7024 // Matches patterns of the form 7025 // (and (shl x, C2), (C1 << C2)) 7026 // (and (srl x, C2), C1) 7027 // (shl (and x, C1), C2) 7028 // (srl (and x, (C1 << C2)), C2) 7029 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7030 // The expected masks for each shift amount are specified in BitmanipMasks where 7031 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7032 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7033 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7034 // XLen is 64. 7035 static Optional<RISCVBitmanipPat> 7036 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7037 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7038 "Unexpected number of masks"); 7039 Optional<uint64_t> Mask; 7040 // Optionally consume a mask around the shift operation. 7041 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7042 Mask = Op.getConstantOperandVal(1); 7043 Op = Op.getOperand(0); 7044 } 7045 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7046 return None; 7047 bool IsSHL = Op.getOpcode() == ISD::SHL; 7048 7049 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7050 return None; 7051 uint64_t ShAmt = Op.getConstantOperandVal(1); 7052 7053 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7054 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7055 return None; 7056 // If we don't have enough masks for 64 bit, then we must be trying to 7057 // match SHFL so we're only allowed to shift 1/4 of the width. 7058 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7059 return None; 7060 7061 SDValue Src = Op.getOperand(0); 7062 7063 // The expected mask is shifted left when the AND is found around SHL 7064 // patterns. 7065 // ((x >> 1) & 0x55555555) 7066 // ((x << 1) & 0xAAAAAAAA) 7067 bool SHLExpMask = IsSHL; 7068 7069 if (!Mask) { 7070 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7071 // the mask is all ones: consume that now. 7072 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7073 Mask = Src.getConstantOperandVal(1); 7074 Src = Src.getOperand(0); 7075 // The expected mask is now in fact shifted left for SRL, so reverse the 7076 // decision. 7077 // ((x & 0xAAAAAAAA) >> 1) 7078 // ((x & 0x55555555) << 1) 7079 SHLExpMask = !SHLExpMask; 7080 } else { 7081 // Use a default shifted mask of all-ones if there's no AND, truncated 7082 // down to the expected width. This simplifies the logic later on. 7083 Mask = maskTrailingOnes<uint64_t>(Width); 7084 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7085 } 7086 } 7087 7088 unsigned MaskIdx = Log2_32(ShAmt); 7089 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7090 7091 if (SHLExpMask) 7092 ExpMask <<= ShAmt; 7093 7094 if (Mask != ExpMask) 7095 return None; 7096 7097 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7098 } 7099 7100 // Matches any of the following bit-manipulation patterns: 7101 // (and (shl x, 1), (0x55555555 << 1)) 7102 // (and (srl x, 1), 0x55555555) 7103 // (shl (and x, 0x55555555), 1) 7104 // (srl (and x, (0x55555555 << 1)), 1) 7105 // where the shift amount and mask may vary thus: 7106 // [1] = 0x55555555 / 0xAAAAAAAA 7107 // [2] = 0x33333333 / 0xCCCCCCCC 7108 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7109 // [8] = 0x00FF00FF / 0xFF00FF00 7110 // [16] = 0x0000FFFF / 0xFFFFFFFF 7111 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7112 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7113 // These are the unshifted masks which we use to match bit-manipulation 7114 // patterns. They may be shifted left in certain circumstances. 7115 static const uint64_t BitmanipMasks[] = { 7116 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7117 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7118 7119 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7120 } 7121 7122 // Match the following pattern as a GREVI(W) operation 7123 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7124 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7125 const RISCVSubtarget &Subtarget) { 7126 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7127 EVT VT = Op.getValueType(); 7128 7129 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7130 auto LHS = matchGREVIPat(Op.getOperand(0)); 7131 auto RHS = matchGREVIPat(Op.getOperand(1)); 7132 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7133 SDLoc DL(Op); 7134 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7135 DAG.getConstant(LHS->ShAmt, DL, VT)); 7136 } 7137 } 7138 return SDValue(); 7139 } 7140 7141 // Matches any the following pattern as a GORCI(W) operation 7142 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7143 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7144 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7145 // Note that with the variant of 3., 7146 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7147 // the inner pattern will first be matched as GREVI and then the outer 7148 // pattern will be matched to GORC via the first rule above. 7149 // 4. (or (rotl/rotr x, bitwidth/2), x) 7150 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7151 const RISCVSubtarget &Subtarget) { 7152 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7153 EVT VT = Op.getValueType(); 7154 7155 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7156 SDLoc DL(Op); 7157 SDValue Op0 = Op.getOperand(0); 7158 SDValue Op1 = Op.getOperand(1); 7159 7160 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7161 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7162 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7163 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7164 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7165 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7166 if ((Reverse.getOpcode() == ISD::ROTL || 7167 Reverse.getOpcode() == ISD::ROTR) && 7168 Reverse.getOperand(0) == X && 7169 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7170 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7171 if (RotAmt == (VT.getSizeInBits() / 2)) 7172 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7173 DAG.getConstant(RotAmt, DL, VT)); 7174 } 7175 return SDValue(); 7176 }; 7177 7178 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7179 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7180 return V; 7181 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7182 return V; 7183 7184 // OR is commutable so canonicalize its OR operand to the left 7185 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7186 std::swap(Op0, Op1); 7187 if (Op0.getOpcode() != ISD::OR) 7188 return SDValue(); 7189 SDValue OrOp0 = Op0.getOperand(0); 7190 SDValue OrOp1 = Op0.getOperand(1); 7191 auto LHS = matchGREVIPat(OrOp0); 7192 // OR is commutable so swap the operands and try again: x might have been 7193 // on the left 7194 if (!LHS) { 7195 std::swap(OrOp0, OrOp1); 7196 LHS = matchGREVIPat(OrOp0); 7197 } 7198 auto RHS = matchGREVIPat(Op1); 7199 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7200 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7201 DAG.getConstant(LHS->ShAmt, DL, VT)); 7202 } 7203 } 7204 return SDValue(); 7205 } 7206 7207 // Matches any of the following bit-manipulation patterns: 7208 // (and (shl x, 1), (0x22222222 << 1)) 7209 // (and (srl x, 1), 0x22222222) 7210 // (shl (and x, 0x22222222), 1) 7211 // (srl (and x, (0x22222222 << 1)), 1) 7212 // where the shift amount and mask may vary thus: 7213 // [1] = 0x22222222 / 0x44444444 7214 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7215 // [4] = 0x00F000F0 / 0x0F000F00 7216 // [8] = 0x0000FF00 / 0x00FF0000 7217 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7218 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7219 // These are the unshifted masks which we use to match bit-manipulation 7220 // patterns. They may be shifted left in certain circumstances. 7221 static const uint64_t BitmanipMasks[] = { 7222 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7223 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7224 7225 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7226 } 7227 7228 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7229 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7230 const RISCVSubtarget &Subtarget) { 7231 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7232 EVT VT = Op.getValueType(); 7233 7234 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7235 return SDValue(); 7236 7237 SDValue Op0 = Op.getOperand(0); 7238 SDValue Op1 = Op.getOperand(1); 7239 7240 // Or is commutable so canonicalize the second OR to the LHS. 7241 if (Op0.getOpcode() != ISD::OR) 7242 std::swap(Op0, Op1); 7243 if (Op0.getOpcode() != ISD::OR) 7244 return SDValue(); 7245 7246 // We found an inner OR, so our operands are the operands of the inner OR 7247 // and the other operand of the outer OR. 7248 SDValue A = Op0.getOperand(0); 7249 SDValue B = Op0.getOperand(1); 7250 SDValue C = Op1; 7251 7252 auto Match1 = matchSHFLPat(A); 7253 auto Match2 = matchSHFLPat(B); 7254 7255 // If neither matched, we failed. 7256 if (!Match1 && !Match2) 7257 return SDValue(); 7258 7259 // We had at least one match. if one failed, try the remaining C operand. 7260 if (!Match1) { 7261 std::swap(A, C); 7262 Match1 = matchSHFLPat(A); 7263 if (!Match1) 7264 return SDValue(); 7265 } else if (!Match2) { 7266 std::swap(B, C); 7267 Match2 = matchSHFLPat(B); 7268 if (!Match2) 7269 return SDValue(); 7270 } 7271 assert(Match1 && Match2); 7272 7273 // Make sure our matches pair up. 7274 if (!Match1->formsPairWith(*Match2)) 7275 return SDValue(); 7276 7277 // All the remains is to make sure C is an AND with the same input, that masks 7278 // out the bits that are being shuffled. 7279 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7280 C.getOperand(0) != Match1->Op) 7281 return SDValue(); 7282 7283 uint64_t Mask = C.getConstantOperandVal(1); 7284 7285 static const uint64_t BitmanipMasks[] = { 7286 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7287 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7288 }; 7289 7290 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7291 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7292 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7293 7294 if (Mask != ExpMask) 7295 return SDValue(); 7296 7297 SDLoc DL(Op); 7298 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7299 DAG.getConstant(Match1->ShAmt, DL, VT)); 7300 } 7301 7302 // Optimize (add (shl x, c0), (shl y, c1)) -> 7303 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7304 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7305 const RISCVSubtarget &Subtarget) { 7306 // Perform this optimization only in the zba extension. 7307 if (!Subtarget.hasStdExtZba()) 7308 return SDValue(); 7309 7310 // Skip for vector types and larger types. 7311 EVT VT = N->getValueType(0); 7312 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7313 return SDValue(); 7314 7315 // The two operand nodes must be SHL and have no other use. 7316 SDValue N0 = N->getOperand(0); 7317 SDValue N1 = N->getOperand(1); 7318 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7319 !N0->hasOneUse() || !N1->hasOneUse()) 7320 return SDValue(); 7321 7322 // Check c0 and c1. 7323 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7324 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7325 if (!N0C || !N1C) 7326 return SDValue(); 7327 int64_t C0 = N0C->getSExtValue(); 7328 int64_t C1 = N1C->getSExtValue(); 7329 if (C0 <= 0 || C1 <= 0) 7330 return SDValue(); 7331 7332 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7333 int64_t Bits = std::min(C0, C1); 7334 int64_t Diff = std::abs(C0 - C1); 7335 if (Diff != 1 && Diff != 2 && Diff != 3) 7336 return SDValue(); 7337 7338 // Build nodes. 7339 SDLoc DL(N); 7340 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7341 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7342 SDValue NA0 = 7343 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7344 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7345 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7346 } 7347 7348 // Combine 7349 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) for RV32 7350 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) for RV32 7351 // ROTR ((GREV x, 56), 32) -> (GREVI x, 24) for RV64 7352 // ROTL ((GREV x, 56), 32) -> (GREVI x, 24) for RV64 7353 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64 7354 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64 7355 // The grev patterns represents BSWAP. 7356 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7357 // off the grev. 7358 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7359 const RISCVSubtarget &Subtarget) { 7360 bool IsWInstruction = 7361 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7362 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7363 IsWInstruction) && 7364 "Unexpected opcode!"); 7365 SDValue Src = N->getOperand(0); 7366 EVT VT = N->getValueType(0); 7367 SDLoc DL(N); 7368 7369 if (!Subtarget.hasStdExtZbp()) 7370 return SDValue(); 7371 7372 unsigned GrevOpc = IsWInstruction ? RISCVISD::GREVW : RISCVISD::GREV; 7373 if (Src.getOpcode() != GrevOpc) 7374 return SDValue(); 7375 7376 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7377 !isa<ConstantSDNode>(Src.getOperand(1))) 7378 return SDValue(); 7379 7380 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7381 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7382 7383 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7384 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7385 unsigned ShAmt1 = N->getConstantOperandVal(1); 7386 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7387 if (BitWidth < 16 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7388 return SDValue(); 7389 7390 Src = Src.getOperand(0); 7391 7392 // Toggle bit the MSB of the shift. 7393 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7394 if (CombinedShAmt == 0) 7395 return Src; 7396 7397 return DAG.getNode( 7398 GrevOpc, DL, VT, Src, 7399 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7400 } 7401 7402 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7403 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7404 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7405 // not undo itself, but they are redundant. 7406 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7407 SDValue Src = N->getOperand(0); 7408 7409 if (Src.getOpcode() != N->getOpcode()) 7410 return SDValue(); 7411 7412 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7413 !isa<ConstantSDNode>(Src.getOperand(1))) 7414 return SDValue(); 7415 7416 unsigned ShAmt1 = N->getConstantOperandVal(1); 7417 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7418 Src = Src.getOperand(0); 7419 7420 unsigned CombinedShAmt; 7421 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7422 CombinedShAmt = ShAmt1 | ShAmt2; 7423 else 7424 CombinedShAmt = ShAmt1 ^ ShAmt2; 7425 7426 if (CombinedShAmt == 0) 7427 return Src; 7428 7429 SDLoc DL(N); 7430 return DAG.getNode( 7431 N->getOpcode(), DL, N->getValueType(0), Src, 7432 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7433 } 7434 7435 // Combine a constant select operand into its use: 7436 // 7437 // (and (select cond, -1, c), x) 7438 // -> (select cond, x, (and x, c)) [AllOnes=1] 7439 // (or (select cond, 0, c), x) 7440 // -> (select cond, x, (or x, c)) [AllOnes=0] 7441 // (xor (select cond, 0, c), x) 7442 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7443 // (add (select cond, 0, c), x) 7444 // -> (select cond, x, (add x, c)) [AllOnes=0] 7445 // (sub x, (select cond, 0, c)) 7446 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7447 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7448 SelectionDAG &DAG, bool AllOnes) { 7449 EVT VT = N->getValueType(0); 7450 7451 // Skip vectors. 7452 if (VT.isVector()) 7453 return SDValue(); 7454 7455 if ((Slct.getOpcode() != ISD::SELECT && 7456 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7457 !Slct.hasOneUse()) 7458 return SDValue(); 7459 7460 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7461 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7462 }; 7463 7464 bool SwapSelectOps; 7465 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7466 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7467 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7468 SDValue NonConstantVal; 7469 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7470 SwapSelectOps = false; 7471 NonConstantVal = FalseVal; 7472 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7473 SwapSelectOps = true; 7474 NonConstantVal = TrueVal; 7475 } else 7476 return SDValue(); 7477 7478 // Slct is now know to be the desired identity constant when CC is true. 7479 TrueVal = OtherOp; 7480 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7481 // Unless SwapSelectOps says the condition should be false. 7482 if (SwapSelectOps) 7483 std::swap(TrueVal, FalseVal); 7484 7485 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7486 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7487 {Slct.getOperand(0), Slct.getOperand(1), 7488 Slct.getOperand(2), TrueVal, FalseVal}); 7489 7490 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7491 {Slct.getOperand(0), TrueVal, FalseVal}); 7492 } 7493 7494 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7495 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7496 bool AllOnes) { 7497 SDValue N0 = N->getOperand(0); 7498 SDValue N1 = N->getOperand(1); 7499 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7500 return Result; 7501 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7502 return Result; 7503 return SDValue(); 7504 } 7505 7506 // Transform (add (mul x, c0), c1) -> 7507 // (add (mul (add x, c1/c0), c0), c1%c0). 7508 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7509 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7510 // to an infinite loop in DAGCombine if transformed. 7511 // Or transform (add (mul x, c0), c1) -> 7512 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7513 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7514 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7515 // lead to an infinite loop in DAGCombine if transformed. 7516 // Or transform (add (mul x, c0), c1) -> 7517 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7518 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7519 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7520 // lead to an infinite loop in DAGCombine if transformed. 7521 // Or transform (add (mul x, c0), c1) -> 7522 // (mul (add x, c1/c0), c0). 7523 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7524 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7525 const RISCVSubtarget &Subtarget) { 7526 // Skip for vector types and larger types. 7527 EVT VT = N->getValueType(0); 7528 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7529 return SDValue(); 7530 // The first operand node must be a MUL and has no other use. 7531 SDValue N0 = N->getOperand(0); 7532 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7533 return SDValue(); 7534 // Check if c0 and c1 match above conditions. 7535 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7536 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7537 if (!N0C || !N1C) 7538 return SDValue(); 7539 // If N0C has multiple uses it's possible one of the cases in 7540 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7541 // in an infinite loop. 7542 if (!N0C->hasOneUse()) 7543 return SDValue(); 7544 int64_t C0 = N0C->getSExtValue(); 7545 int64_t C1 = N1C->getSExtValue(); 7546 int64_t CA, CB; 7547 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7548 return SDValue(); 7549 // Search for proper CA (non-zero) and CB that both are simm12. 7550 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7551 !isInt<12>(C0 * (C1 / C0))) { 7552 CA = C1 / C0; 7553 CB = C1 % C0; 7554 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7555 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7556 CA = C1 / C0 + 1; 7557 CB = C1 % C0 - C0; 7558 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7559 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7560 CA = C1 / C0 - 1; 7561 CB = C1 % C0 + C0; 7562 } else 7563 return SDValue(); 7564 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7565 SDLoc DL(N); 7566 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7567 DAG.getConstant(CA, DL, VT)); 7568 SDValue New1 = 7569 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7570 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7571 } 7572 7573 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7574 const RISCVSubtarget &Subtarget) { 7575 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7576 return V; 7577 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7578 return V; 7579 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7580 // (select lhs, rhs, cc, x, (add x, y)) 7581 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7582 } 7583 7584 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7585 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7586 // (select lhs, rhs, cc, x, (sub x, y)) 7587 SDValue N0 = N->getOperand(0); 7588 SDValue N1 = N->getOperand(1); 7589 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7590 } 7591 7592 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7593 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7594 // (select lhs, rhs, cc, x, (and x, y)) 7595 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7596 } 7597 7598 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7599 const RISCVSubtarget &Subtarget) { 7600 if (Subtarget.hasStdExtZbp()) { 7601 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7602 return GREV; 7603 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7604 return GORC; 7605 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7606 return SHFL; 7607 } 7608 7609 // fold (or (select cond, 0, y), x) -> 7610 // (select cond, x, (or x, y)) 7611 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7612 } 7613 7614 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7615 // fold (xor (select cond, 0, y), x) -> 7616 // (select cond, x, (xor x, y)) 7617 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7618 } 7619 7620 static SDValue performSIGN_EXTEND_INREG(SDNode *N, SelectionDAG &DAG) { 7621 SDValue Src = N->getOperand(0); 7622 7623 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7624 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7625 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7626 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), N->getValueType(0), 7627 Src.getOperand(0)); 7628 7629 return SDValue(); 7630 } 7631 7632 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7633 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7634 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7635 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7636 // ADDW/SUBW/MULW. 7637 static SDValue performANY_EXTENDCombine(SDNode *N, 7638 TargetLowering::DAGCombinerInfo &DCI, 7639 const RISCVSubtarget &Subtarget) { 7640 if (!Subtarget.is64Bit()) 7641 return SDValue(); 7642 7643 SelectionDAG &DAG = DCI.DAG; 7644 7645 SDValue Src = N->getOperand(0); 7646 EVT VT = N->getValueType(0); 7647 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7648 return SDValue(); 7649 7650 // The opcode must be one that can implicitly sign_extend. 7651 // FIXME: Additional opcodes. 7652 switch (Src.getOpcode()) { 7653 default: 7654 return SDValue(); 7655 case ISD::MUL: 7656 if (!Subtarget.hasStdExtM()) 7657 return SDValue(); 7658 LLVM_FALLTHROUGH; 7659 case ISD::ADD: 7660 case ISD::SUB: 7661 break; 7662 } 7663 7664 // Only handle cases where the result is used by a CopyToReg. That likely 7665 // means the value is a liveout of the basic block. This helps prevent 7666 // infinite combine loops like PR51206. 7667 if (none_of(N->uses(), 7668 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7669 return SDValue(); 7670 7671 SmallVector<SDNode *, 4> SetCCs; 7672 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7673 UE = Src.getNode()->use_end(); 7674 UI != UE; ++UI) { 7675 SDNode *User = *UI; 7676 if (User == N) 7677 continue; 7678 if (UI.getUse().getResNo() != Src.getResNo()) 7679 continue; 7680 // All i32 setccs are legalized by sign extending operands. 7681 if (User->getOpcode() == ISD::SETCC) { 7682 SetCCs.push_back(User); 7683 continue; 7684 } 7685 // We don't know if we can extend this user. 7686 break; 7687 } 7688 7689 // If we don't have any SetCCs, this isn't worthwhile. 7690 if (SetCCs.empty()) 7691 return SDValue(); 7692 7693 SDLoc DL(N); 7694 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7695 DCI.CombineTo(N, SExt); 7696 7697 // Promote all the setccs. 7698 for (SDNode *SetCC : SetCCs) { 7699 SmallVector<SDValue, 4> Ops; 7700 7701 for (unsigned j = 0; j != 2; ++j) { 7702 SDValue SOp = SetCC->getOperand(j); 7703 if (SOp == Src) 7704 Ops.push_back(SExt); 7705 else 7706 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7707 } 7708 7709 Ops.push_back(SetCC->getOperand(2)); 7710 DCI.CombineTo(SetCC, 7711 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7712 } 7713 return SDValue(N, 0); 7714 } 7715 7716 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7717 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7718 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7719 bool Commute = false) { 7720 assert((N->getOpcode() == RISCVISD::ADD_VL || 7721 N->getOpcode() == RISCVISD::SUB_VL) && 7722 "Unexpected opcode"); 7723 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7724 SDValue Op0 = N->getOperand(0); 7725 SDValue Op1 = N->getOperand(1); 7726 if (Commute) 7727 std::swap(Op0, Op1); 7728 7729 MVT VT = N->getSimpleValueType(0); 7730 7731 // Determine the narrow size for a widening add/sub. 7732 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7733 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7734 VT.getVectorElementCount()); 7735 7736 SDValue Mask = N->getOperand(2); 7737 SDValue VL = N->getOperand(3); 7738 7739 SDLoc DL(N); 7740 7741 // If the RHS is a sext or zext, we can form a widening op. 7742 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7743 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7744 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7745 unsigned ExtOpc = Op1.getOpcode(); 7746 Op1 = Op1.getOperand(0); 7747 // Re-introduce narrower extends if needed. 7748 if (Op1.getValueType() != NarrowVT) 7749 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7750 7751 unsigned WOpc; 7752 if (ExtOpc == RISCVISD::VSEXT_VL) 7753 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7754 else 7755 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7756 7757 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7758 } 7759 7760 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7761 // sext/zext? 7762 7763 return SDValue(); 7764 } 7765 7766 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7767 // vwsub(u).vv/vx. 7768 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7769 SDValue Op0 = N->getOperand(0); 7770 SDValue Op1 = N->getOperand(1); 7771 SDValue Mask = N->getOperand(2); 7772 SDValue VL = N->getOperand(3); 7773 7774 MVT VT = N->getSimpleValueType(0); 7775 MVT NarrowVT = Op1.getSimpleValueType(); 7776 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7777 7778 unsigned VOpc; 7779 switch (N->getOpcode()) { 7780 default: llvm_unreachable("Unexpected opcode"); 7781 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7782 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7783 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7784 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7785 } 7786 7787 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7788 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7789 7790 SDLoc DL(N); 7791 7792 // If the LHS is a sext or zext, we can narrow this op to the same size as 7793 // the RHS. 7794 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7795 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7796 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7797 unsigned ExtOpc = Op0.getOpcode(); 7798 Op0 = Op0.getOperand(0); 7799 // Re-introduce narrower extends if needed. 7800 if (Op0.getValueType() != NarrowVT) 7801 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7802 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7803 } 7804 7805 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7806 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7807 7808 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7809 // to commute and use a vwadd(u).vx instead. 7810 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7811 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7812 Op0 = Op0.getOperand(1); 7813 7814 // See if have enough sign bits or zero bits in the scalar to use a 7815 // widening add/sub by splatting to smaller element size. 7816 unsigned EltBits = VT.getScalarSizeInBits(); 7817 unsigned ScalarBits = Op0.getValueSizeInBits(); 7818 // Make sure we're getting all element bits from the scalar register. 7819 // FIXME: Support implicit sign extension of vmv.v.x? 7820 if (ScalarBits < EltBits) 7821 return SDValue(); 7822 7823 if (IsSigned) { 7824 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7825 return SDValue(); 7826 } else { 7827 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7828 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7829 return SDValue(); 7830 } 7831 7832 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7833 DAG.getUNDEF(NarrowVT), Op0, VL); 7834 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7835 } 7836 7837 return SDValue(); 7838 } 7839 7840 // Try to form VWMUL, VWMULU or VWMULSU. 7841 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7842 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7843 bool Commute) { 7844 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7845 SDValue Op0 = N->getOperand(0); 7846 SDValue Op1 = N->getOperand(1); 7847 if (Commute) 7848 std::swap(Op0, Op1); 7849 7850 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7851 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7852 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7853 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7854 return SDValue(); 7855 7856 SDValue Mask = N->getOperand(2); 7857 SDValue VL = N->getOperand(3); 7858 7859 // Make sure the mask and VL match. 7860 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7861 return SDValue(); 7862 7863 MVT VT = N->getSimpleValueType(0); 7864 7865 // Determine the narrow size for a widening multiply. 7866 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7867 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7868 VT.getVectorElementCount()); 7869 7870 SDLoc DL(N); 7871 7872 // See if the other operand is the same opcode. 7873 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7874 if (!Op1.hasOneUse()) 7875 return SDValue(); 7876 7877 // Make sure the mask and VL match. 7878 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7879 return SDValue(); 7880 7881 Op1 = Op1.getOperand(0); 7882 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7883 // The operand is a splat of a scalar. 7884 7885 // The pasthru must be undef for tail agnostic 7886 if (!Op1.getOperand(0).isUndef()) 7887 return SDValue(); 7888 // The VL must be the same. 7889 if (Op1.getOperand(2) != VL) 7890 return SDValue(); 7891 7892 // Get the scalar value. 7893 Op1 = Op1.getOperand(1); 7894 7895 // See if have enough sign bits or zero bits in the scalar to use a 7896 // widening multiply by splatting to smaller element size. 7897 unsigned EltBits = VT.getScalarSizeInBits(); 7898 unsigned ScalarBits = Op1.getValueSizeInBits(); 7899 // Make sure we're getting all element bits from the scalar register. 7900 // FIXME: Support implicit sign extension of vmv.v.x? 7901 if (ScalarBits < EltBits) 7902 return SDValue(); 7903 7904 // If the LHS is a sign extend, try to use vwmul. 7905 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7906 // Can use vwmul. 7907 } else { 7908 // Otherwise try to use vwmulu or vwmulsu. 7909 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7910 if (DAG.MaskedValueIsZero(Op1, Mask)) 7911 IsVWMULSU = IsSignExt; 7912 else 7913 return SDValue(); 7914 } 7915 7916 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7917 DAG.getUNDEF(NarrowVT), Op1, VL); 7918 } else 7919 return SDValue(); 7920 7921 Op0 = Op0.getOperand(0); 7922 7923 // Re-introduce narrower extends if needed. 7924 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7925 if (Op0.getValueType() != NarrowVT) 7926 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7927 // vwmulsu requires second operand to be zero extended. 7928 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7929 if (Op1.getValueType() != NarrowVT) 7930 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7931 7932 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7933 if (!IsVWMULSU) 7934 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7935 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7936 } 7937 7938 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7939 switch (Op.getOpcode()) { 7940 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7941 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7942 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7943 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7944 case ISD::FROUND: return RISCVFPRndMode::RMM; 7945 } 7946 7947 return RISCVFPRndMode::Invalid; 7948 } 7949 7950 // Fold 7951 // (fp_to_int (froundeven X)) -> fcvt X, rne 7952 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7953 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7954 // (fp_to_int (fceil X)) -> fcvt X, rup 7955 // (fp_to_int (fround X)) -> fcvt X, rmm 7956 static SDValue performFP_TO_INTCombine(SDNode *N, 7957 TargetLowering::DAGCombinerInfo &DCI, 7958 const RISCVSubtarget &Subtarget) { 7959 SelectionDAG &DAG = DCI.DAG; 7960 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7961 MVT XLenVT = Subtarget.getXLenVT(); 7962 7963 // Only handle XLen or i32 types. Other types narrower than XLen will 7964 // eventually be legalized to XLenVT. 7965 EVT VT = N->getValueType(0); 7966 if (VT != MVT::i32 && VT != XLenVT) 7967 return SDValue(); 7968 7969 SDValue Src = N->getOperand(0); 7970 7971 // Ensure the FP type is also legal. 7972 if (!TLI.isTypeLegal(Src.getValueType())) 7973 return SDValue(); 7974 7975 // Don't do this for f16 with Zfhmin and not Zfh. 7976 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7977 return SDValue(); 7978 7979 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7980 if (FRM == RISCVFPRndMode::Invalid) 7981 return SDValue(); 7982 7983 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7984 7985 unsigned Opc; 7986 if (VT == XLenVT) 7987 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7988 else 7989 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7990 7991 SDLoc DL(N); 7992 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7993 DAG.getTargetConstant(FRM, DL, XLenVT)); 7994 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7995 } 7996 7997 // Fold 7998 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7999 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8000 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8001 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8002 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8003 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8004 TargetLowering::DAGCombinerInfo &DCI, 8005 const RISCVSubtarget &Subtarget) { 8006 SelectionDAG &DAG = DCI.DAG; 8007 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8008 MVT XLenVT = Subtarget.getXLenVT(); 8009 8010 // Only handle XLen types. Other types narrower than XLen will eventually be 8011 // legalized to XLenVT. 8012 EVT DstVT = N->getValueType(0); 8013 if (DstVT != XLenVT) 8014 return SDValue(); 8015 8016 SDValue Src = N->getOperand(0); 8017 8018 // Ensure the FP type is also legal. 8019 if (!TLI.isTypeLegal(Src.getValueType())) 8020 return SDValue(); 8021 8022 // Don't do this for f16 with Zfhmin and not Zfh. 8023 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8024 return SDValue(); 8025 8026 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8027 8028 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8029 if (FRM == RISCVFPRndMode::Invalid) 8030 return SDValue(); 8031 8032 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8033 8034 unsigned Opc; 8035 if (SatVT == DstVT) 8036 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8037 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8038 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8039 else 8040 return SDValue(); 8041 // FIXME: Support other SatVTs by clamping before or after the conversion. 8042 8043 Src = Src.getOperand(0); 8044 8045 SDLoc DL(N); 8046 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8047 DAG.getTargetConstant(FRM, DL, XLenVT)); 8048 8049 // RISCV FP-to-int conversions saturate to the destination register size, but 8050 // don't produce 0 for nan. 8051 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8052 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8053 } 8054 8055 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8056 DAGCombinerInfo &DCI) const { 8057 SelectionDAG &DAG = DCI.DAG; 8058 8059 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8060 // bits are demanded. N will be added to the Worklist if it was not deleted. 8061 // Caller should return SDValue(N, 0) if this returns true. 8062 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8063 SDValue Op = N->getOperand(OpNo); 8064 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8065 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8066 return false; 8067 8068 if (N->getOpcode() != ISD::DELETED_NODE) 8069 DCI.AddToWorklist(N); 8070 return true; 8071 }; 8072 8073 switch (N->getOpcode()) { 8074 default: 8075 break; 8076 case RISCVISD::SplitF64: { 8077 SDValue Op0 = N->getOperand(0); 8078 // If the input to SplitF64 is just BuildPairF64 then the operation is 8079 // redundant. Instead, use BuildPairF64's operands directly. 8080 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8081 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8082 8083 if (Op0->isUndef()) { 8084 SDValue Lo = DAG.getUNDEF(MVT::i32); 8085 SDValue Hi = DAG.getUNDEF(MVT::i32); 8086 return DCI.CombineTo(N, Lo, Hi); 8087 } 8088 8089 SDLoc DL(N); 8090 8091 // It's cheaper to materialise two 32-bit integers than to load a double 8092 // from the constant pool and transfer it to integer registers through the 8093 // stack. 8094 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8095 APInt V = C->getValueAPF().bitcastToAPInt(); 8096 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8097 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8098 return DCI.CombineTo(N, Lo, Hi); 8099 } 8100 8101 // This is a target-specific version of a DAGCombine performed in 8102 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8103 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8104 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8105 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8106 !Op0.getNode()->hasOneUse()) 8107 break; 8108 SDValue NewSplitF64 = 8109 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8110 Op0.getOperand(0)); 8111 SDValue Lo = NewSplitF64.getValue(0); 8112 SDValue Hi = NewSplitF64.getValue(1); 8113 APInt SignBit = APInt::getSignMask(32); 8114 if (Op0.getOpcode() == ISD::FNEG) { 8115 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8116 DAG.getConstant(SignBit, DL, MVT::i32)); 8117 return DCI.CombineTo(N, Lo, NewHi); 8118 } 8119 assert(Op0.getOpcode() == ISD::FABS); 8120 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8121 DAG.getConstant(~SignBit, DL, MVT::i32)); 8122 return DCI.CombineTo(N, Lo, NewHi); 8123 } 8124 case RISCVISD::SLLW: 8125 case RISCVISD::SRAW: 8126 case RISCVISD::SRLW: { 8127 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8128 if (SimplifyDemandedLowBitsHelper(0, 32) || 8129 SimplifyDemandedLowBitsHelper(1, 5)) 8130 return SDValue(N, 0); 8131 8132 break; 8133 } 8134 case ISD::ROTR: 8135 case ISD::ROTL: 8136 case RISCVISD::RORW: 8137 case RISCVISD::ROLW: { 8138 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8139 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8140 if (SimplifyDemandedLowBitsHelper(0, 32) || 8141 SimplifyDemandedLowBitsHelper(1, 5)) 8142 return SDValue(N, 0); 8143 } 8144 8145 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8146 } 8147 case RISCVISD::CLZW: 8148 case RISCVISD::CTZW: { 8149 // Only the lower 32 bits of the first operand are read 8150 if (SimplifyDemandedLowBitsHelper(0, 32)) 8151 return SDValue(N, 0); 8152 break; 8153 } 8154 case RISCVISD::GREV: 8155 case RISCVISD::GORC: { 8156 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8157 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8158 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8159 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8160 return SDValue(N, 0); 8161 8162 return combineGREVI_GORCI(N, DAG); 8163 } 8164 case RISCVISD::GREVW: 8165 case RISCVISD::GORCW: { 8166 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8167 if (SimplifyDemandedLowBitsHelper(0, 32) || 8168 SimplifyDemandedLowBitsHelper(1, 5)) 8169 return SDValue(N, 0); 8170 8171 return combineGREVI_GORCI(N, DAG); 8172 } 8173 case RISCVISD::SHFL: 8174 case RISCVISD::UNSHFL: { 8175 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8176 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8177 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8178 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8179 return SDValue(N, 0); 8180 8181 break; 8182 } 8183 case RISCVISD::SHFLW: 8184 case RISCVISD::UNSHFLW: { 8185 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8186 if (SimplifyDemandedLowBitsHelper(0, 32) || 8187 SimplifyDemandedLowBitsHelper(1, 4)) 8188 return SDValue(N, 0); 8189 8190 break; 8191 } 8192 case RISCVISD::BCOMPRESSW: 8193 case RISCVISD::BDECOMPRESSW: { 8194 // Only the lower 32 bits of LHS and RHS are read. 8195 if (SimplifyDemandedLowBitsHelper(0, 32) || 8196 SimplifyDemandedLowBitsHelper(1, 32)) 8197 return SDValue(N, 0); 8198 8199 break; 8200 } 8201 case RISCVISD::FMV_X_ANYEXTH: 8202 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8203 SDLoc DL(N); 8204 SDValue Op0 = N->getOperand(0); 8205 MVT VT = N->getSimpleValueType(0); 8206 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8207 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8208 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8209 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8210 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8211 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8212 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8213 assert(Op0.getOperand(0).getValueType() == VT && 8214 "Unexpected value type!"); 8215 return Op0.getOperand(0); 8216 } 8217 8218 // This is a target-specific version of a DAGCombine performed in 8219 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8220 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8221 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8222 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8223 !Op0.getNode()->hasOneUse()) 8224 break; 8225 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8226 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8227 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8228 if (Op0.getOpcode() == ISD::FNEG) 8229 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8230 DAG.getConstant(SignBit, DL, VT)); 8231 8232 assert(Op0.getOpcode() == ISD::FABS); 8233 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8234 DAG.getConstant(~SignBit, DL, VT)); 8235 } 8236 case ISD::ADD: 8237 return performADDCombine(N, DAG, Subtarget); 8238 case ISD::SUB: 8239 return performSUBCombine(N, DAG); 8240 case ISD::AND: 8241 return performANDCombine(N, DAG); 8242 case ISD::OR: 8243 return performORCombine(N, DAG, Subtarget); 8244 case ISD::XOR: 8245 return performXORCombine(N, DAG); 8246 case ISD::SIGN_EXTEND_INREG: 8247 return performSIGN_EXTEND_INREG(N, DAG); 8248 case ISD::ANY_EXTEND: 8249 return performANY_EXTENDCombine(N, DCI, Subtarget); 8250 case ISD::ZERO_EXTEND: 8251 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8252 // type legalization. This is safe because fp_to_uint produces poison if 8253 // it overflows. 8254 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8255 SDValue Src = N->getOperand(0); 8256 if (Src.getOpcode() == ISD::FP_TO_UINT && 8257 isTypeLegal(Src.getOperand(0).getValueType())) 8258 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8259 Src.getOperand(0)); 8260 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8261 isTypeLegal(Src.getOperand(1).getValueType())) { 8262 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8263 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8264 Src.getOperand(0), Src.getOperand(1)); 8265 DCI.CombineTo(N, Res); 8266 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8267 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8268 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8269 } 8270 } 8271 return SDValue(); 8272 case RISCVISD::SELECT_CC: { 8273 // Transform 8274 SDValue LHS = N->getOperand(0); 8275 SDValue RHS = N->getOperand(1); 8276 SDValue TrueV = N->getOperand(3); 8277 SDValue FalseV = N->getOperand(4); 8278 8279 // If the True and False values are the same, we don't need a select_cc. 8280 if (TrueV == FalseV) 8281 return TrueV; 8282 8283 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8284 if (!ISD::isIntEqualitySetCC(CCVal)) 8285 break; 8286 8287 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8288 // (select_cc X, Y, lt, trueV, falseV) 8289 // Sometimes the setcc is introduced after select_cc has been formed. 8290 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8291 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8292 // If we're looking for eq 0 instead of ne 0, we need to invert the 8293 // condition. 8294 bool Invert = CCVal == ISD::SETEQ; 8295 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8296 if (Invert) 8297 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8298 8299 SDLoc DL(N); 8300 RHS = LHS.getOperand(1); 8301 LHS = LHS.getOperand(0); 8302 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8303 8304 SDValue TargetCC = DAG.getCondCode(CCVal); 8305 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8306 {LHS, RHS, TargetCC, TrueV, FalseV}); 8307 } 8308 8309 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8310 // (select_cc X, Y, eq/ne, trueV, falseV) 8311 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8312 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8313 {LHS.getOperand(0), LHS.getOperand(1), 8314 N->getOperand(2), TrueV, FalseV}); 8315 // (select_cc X, 1, setne, trueV, falseV) -> 8316 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8317 // This can occur when legalizing some floating point comparisons. 8318 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8319 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8320 SDLoc DL(N); 8321 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8322 SDValue TargetCC = DAG.getCondCode(CCVal); 8323 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8324 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8325 {LHS, RHS, TargetCC, TrueV, FalseV}); 8326 } 8327 8328 break; 8329 } 8330 case RISCVISD::BR_CC: { 8331 SDValue LHS = N->getOperand(1); 8332 SDValue RHS = N->getOperand(2); 8333 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8334 if (!ISD::isIntEqualitySetCC(CCVal)) 8335 break; 8336 8337 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8338 // (br_cc X, Y, lt, dest) 8339 // Sometimes the setcc is introduced after br_cc has been formed. 8340 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8341 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8342 // If we're looking for eq 0 instead of ne 0, we need to invert the 8343 // condition. 8344 bool Invert = CCVal == ISD::SETEQ; 8345 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8346 if (Invert) 8347 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8348 8349 SDLoc DL(N); 8350 RHS = LHS.getOperand(1); 8351 LHS = LHS.getOperand(0); 8352 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8353 8354 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8355 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8356 N->getOperand(4)); 8357 } 8358 8359 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8360 // (br_cc X, Y, eq/ne, trueV, falseV) 8361 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8362 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8363 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8364 N->getOperand(3), N->getOperand(4)); 8365 8366 // (br_cc X, 1, setne, br_cc) -> 8367 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8368 // This can occur when legalizing some floating point comparisons. 8369 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8370 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8371 SDLoc DL(N); 8372 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8373 SDValue TargetCC = DAG.getCondCode(CCVal); 8374 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8375 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8376 N->getOperand(0), LHS, RHS, TargetCC, 8377 N->getOperand(4)); 8378 } 8379 break; 8380 } 8381 case ISD::FP_TO_SINT: 8382 case ISD::FP_TO_UINT: 8383 return performFP_TO_INTCombine(N, DCI, Subtarget); 8384 case ISD::FP_TO_SINT_SAT: 8385 case ISD::FP_TO_UINT_SAT: 8386 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8387 case ISD::FCOPYSIGN: { 8388 EVT VT = N->getValueType(0); 8389 if (!VT.isVector()) 8390 break; 8391 // There is a form of VFSGNJ which injects the negated sign of its second 8392 // operand. Try and bubble any FNEG up after the extend/round to produce 8393 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8394 // TRUNC=1. 8395 SDValue In2 = N->getOperand(1); 8396 // Avoid cases where the extend/round has multiple uses, as duplicating 8397 // those is typically more expensive than removing a fneg. 8398 if (!In2.hasOneUse()) 8399 break; 8400 if (In2.getOpcode() != ISD::FP_EXTEND && 8401 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8402 break; 8403 In2 = In2.getOperand(0); 8404 if (In2.getOpcode() != ISD::FNEG) 8405 break; 8406 SDLoc DL(N); 8407 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8408 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8409 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8410 } 8411 case ISD::MGATHER: 8412 case ISD::MSCATTER: 8413 case ISD::VP_GATHER: 8414 case ISD::VP_SCATTER: { 8415 if (!DCI.isBeforeLegalize()) 8416 break; 8417 SDValue Index, ScaleOp; 8418 bool IsIndexScaled = false; 8419 bool IsIndexSigned = false; 8420 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8421 Index = VPGSN->getIndex(); 8422 ScaleOp = VPGSN->getScale(); 8423 IsIndexScaled = VPGSN->isIndexScaled(); 8424 IsIndexSigned = VPGSN->isIndexSigned(); 8425 } else { 8426 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8427 Index = MGSN->getIndex(); 8428 ScaleOp = MGSN->getScale(); 8429 IsIndexScaled = MGSN->isIndexScaled(); 8430 IsIndexSigned = MGSN->isIndexSigned(); 8431 } 8432 EVT IndexVT = Index.getValueType(); 8433 MVT XLenVT = Subtarget.getXLenVT(); 8434 // RISCV indexed loads only support the "unsigned unscaled" addressing 8435 // mode, so anything else must be manually legalized. 8436 bool NeedsIdxLegalization = 8437 IsIndexScaled || 8438 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8439 if (!NeedsIdxLegalization) 8440 break; 8441 8442 SDLoc DL(N); 8443 8444 // Any index legalization should first promote to XLenVT, so we don't lose 8445 // bits when scaling. This may create an illegal index type so we let 8446 // LLVM's legalization take care of the splitting. 8447 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8448 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8449 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8450 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8451 DL, IndexVT, Index); 8452 } 8453 8454 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8455 if (IsIndexScaled && Scale != 1) { 8456 // Manually scale the indices by the element size. 8457 // TODO: Sanitize the scale operand here? 8458 // TODO: For VP nodes, should we use VP_SHL here? 8459 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8460 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8461 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8462 } 8463 8464 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8465 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8466 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8467 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8468 VPGN->getScale(), VPGN->getMask(), 8469 VPGN->getVectorLength()}, 8470 VPGN->getMemOperand(), NewIndexTy); 8471 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8472 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8473 {VPSN->getChain(), VPSN->getValue(), 8474 VPSN->getBasePtr(), Index, VPSN->getScale(), 8475 VPSN->getMask(), VPSN->getVectorLength()}, 8476 VPSN->getMemOperand(), NewIndexTy); 8477 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8478 return DAG.getMaskedGather( 8479 N->getVTList(), MGN->getMemoryVT(), DL, 8480 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8481 MGN->getBasePtr(), Index, MGN->getScale()}, 8482 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8483 const auto *MSN = cast<MaskedScatterSDNode>(N); 8484 return DAG.getMaskedScatter( 8485 N->getVTList(), MSN->getMemoryVT(), DL, 8486 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8487 Index, MSN->getScale()}, 8488 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8489 } 8490 case RISCVISD::SRA_VL: 8491 case RISCVISD::SRL_VL: 8492 case RISCVISD::SHL_VL: { 8493 SDValue ShAmt = N->getOperand(1); 8494 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8495 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8496 SDLoc DL(N); 8497 SDValue VL = N->getOperand(3); 8498 EVT VT = N->getValueType(0); 8499 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8500 ShAmt.getOperand(1), VL); 8501 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8502 N->getOperand(2), N->getOperand(3)); 8503 } 8504 break; 8505 } 8506 case ISD::SRA: 8507 case ISD::SRL: 8508 case ISD::SHL: { 8509 SDValue ShAmt = N->getOperand(1); 8510 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8511 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8512 SDLoc DL(N); 8513 EVT VT = N->getValueType(0); 8514 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8515 ShAmt.getOperand(1), 8516 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8517 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8518 } 8519 break; 8520 } 8521 case RISCVISD::ADD_VL: 8522 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8523 return V; 8524 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8525 case RISCVISD::SUB_VL: 8526 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8527 case RISCVISD::VWADD_W_VL: 8528 case RISCVISD::VWADDU_W_VL: 8529 case RISCVISD::VWSUB_W_VL: 8530 case RISCVISD::VWSUBU_W_VL: 8531 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8532 case RISCVISD::MUL_VL: 8533 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8534 return V; 8535 // Mul is commutative. 8536 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8537 case ISD::STORE: { 8538 auto *Store = cast<StoreSDNode>(N); 8539 SDValue Val = Store->getValue(); 8540 // Combine store of vmv.x.s to vse with VL of 1. 8541 // FIXME: Support FP. 8542 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8543 SDValue Src = Val.getOperand(0); 8544 EVT VecVT = Src.getValueType(); 8545 EVT MemVT = Store->getMemoryVT(); 8546 // The memory VT and the element type must match. 8547 if (VecVT.getVectorElementType() == MemVT) { 8548 SDLoc DL(N); 8549 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8550 return DAG.getStoreVP( 8551 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8552 DAG.getConstant(1, DL, MaskVT), 8553 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8554 Store->getMemOperand(), Store->getAddressingMode(), 8555 Store->isTruncatingStore(), /*IsCompress*/ false); 8556 } 8557 } 8558 8559 break; 8560 } 8561 case ISD::SPLAT_VECTOR: { 8562 EVT VT = N->getValueType(0); 8563 // Only perform this combine on legal MVT types. 8564 if (!isTypeLegal(VT)) 8565 break; 8566 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8567 DAG, Subtarget)) 8568 return Gather; 8569 break; 8570 } 8571 case RISCVISD::VMV_V_X_VL: { 8572 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8573 // scalar input. 8574 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8575 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8576 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8577 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8578 return SDValue(N, 0); 8579 8580 break; 8581 } 8582 case ISD::INTRINSIC_WO_CHAIN: { 8583 unsigned IntNo = N->getConstantOperandVal(0); 8584 switch (IntNo) { 8585 // By default we do not combine any intrinsic. 8586 default: 8587 return SDValue(); 8588 case Intrinsic::riscv_vcpop: 8589 case Intrinsic::riscv_vcpop_mask: 8590 case Intrinsic::riscv_vfirst: 8591 case Intrinsic::riscv_vfirst_mask: { 8592 SDValue VL = N->getOperand(2); 8593 if (IntNo == Intrinsic::riscv_vcpop_mask || 8594 IntNo == Intrinsic::riscv_vfirst_mask) 8595 VL = N->getOperand(3); 8596 if (!isNullConstant(VL)) 8597 return SDValue(); 8598 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8599 SDLoc DL(N); 8600 EVT VT = N->getValueType(0); 8601 if (IntNo == Intrinsic::riscv_vfirst || 8602 IntNo == Intrinsic::riscv_vfirst_mask) 8603 return DAG.getConstant(-1, DL, VT); 8604 return DAG.getConstant(0, DL, VT); 8605 } 8606 } 8607 } 8608 } 8609 8610 return SDValue(); 8611 } 8612 8613 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8614 const SDNode *N, CombineLevel Level) const { 8615 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8616 // materialised in fewer instructions than `(OP _, c1)`: 8617 // 8618 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8619 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8620 SDValue N0 = N->getOperand(0); 8621 EVT Ty = N0.getValueType(); 8622 if (Ty.isScalarInteger() && 8623 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8624 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8625 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8626 if (C1 && C2) { 8627 const APInt &C1Int = C1->getAPIntValue(); 8628 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8629 8630 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8631 // and the combine should happen, to potentially allow further combines 8632 // later. 8633 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8634 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8635 return true; 8636 8637 // We can materialise `c1` in an add immediate, so it's "free", and the 8638 // combine should be prevented. 8639 if (C1Int.getMinSignedBits() <= 64 && 8640 isLegalAddImmediate(C1Int.getSExtValue())) 8641 return false; 8642 8643 // Neither constant will fit into an immediate, so find materialisation 8644 // costs. 8645 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8646 Subtarget.getFeatureBits(), 8647 /*CompressionCost*/true); 8648 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8649 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8650 /*CompressionCost*/true); 8651 8652 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8653 // combine should be prevented. 8654 if (C1Cost < ShiftedC1Cost) 8655 return false; 8656 } 8657 } 8658 return true; 8659 } 8660 8661 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8662 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8663 TargetLoweringOpt &TLO) const { 8664 // Delay this optimization as late as possible. 8665 if (!TLO.LegalOps) 8666 return false; 8667 8668 EVT VT = Op.getValueType(); 8669 if (VT.isVector()) 8670 return false; 8671 8672 // Only handle AND for now. 8673 if (Op.getOpcode() != ISD::AND) 8674 return false; 8675 8676 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8677 if (!C) 8678 return false; 8679 8680 const APInt &Mask = C->getAPIntValue(); 8681 8682 // Clear all non-demanded bits initially. 8683 APInt ShrunkMask = Mask & DemandedBits; 8684 8685 // Try to make a smaller immediate by setting undemanded bits. 8686 8687 APInt ExpandedMask = Mask | ~DemandedBits; 8688 8689 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8690 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8691 }; 8692 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8693 if (NewMask == Mask) 8694 return true; 8695 SDLoc DL(Op); 8696 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8697 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8698 return TLO.CombineTo(Op, NewOp); 8699 }; 8700 8701 // If the shrunk mask fits in sign extended 12 bits, let the target 8702 // independent code apply it. 8703 if (ShrunkMask.isSignedIntN(12)) 8704 return false; 8705 8706 // Preserve (and X, 0xffff) when zext.h is supported. 8707 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8708 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8709 if (IsLegalMask(NewMask)) 8710 return UseMask(NewMask); 8711 } 8712 8713 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8714 if (VT == MVT::i64) { 8715 APInt NewMask = APInt(64, 0xffffffff); 8716 if (IsLegalMask(NewMask)) 8717 return UseMask(NewMask); 8718 } 8719 8720 // For the remaining optimizations, we need to be able to make a negative 8721 // number through a combination of mask and undemanded bits. 8722 if (!ExpandedMask.isNegative()) 8723 return false; 8724 8725 // What is the fewest number of bits we need to represent the negative number. 8726 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8727 8728 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8729 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8730 APInt NewMask = ShrunkMask; 8731 if (MinSignedBits <= 12) 8732 NewMask.setBitsFrom(11); 8733 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8734 NewMask.setBitsFrom(31); 8735 else 8736 return false; 8737 8738 // Check that our new mask is a subset of the demanded mask. 8739 assert(IsLegalMask(NewMask)); 8740 return UseMask(NewMask); 8741 } 8742 8743 static void computeGREV(APInt &Src, unsigned ShAmt) { 8744 ShAmt &= Src.getBitWidth() - 1; 8745 uint64_t x = Src.getZExtValue(); 8746 if (ShAmt & 1) 8747 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8748 if (ShAmt & 2) 8749 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8750 if (ShAmt & 4) 8751 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8752 if (ShAmt & 8) 8753 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8754 if (ShAmt & 16) 8755 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8756 if (ShAmt & 32) 8757 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8758 Src = x; 8759 } 8760 8761 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8762 KnownBits &Known, 8763 const APInt &DemandedElts, 8764 const SelectionDAG &DAG, 8765 unsigned Depth) const { 8766 unsigned BitWidth = Known.getBitWidth(); 8767 unsigned Opc = Op.getOpcode(); 8768 assert((Opc >= ISD::BUILTIN_OP_END || 8769 Opc == ISD::INTRINSIC_WO_CHAIN || 8770 Opc == ISD::INTRINSIC_W_CHAIN || 8771 Opc == ISD::INTRINSIC_VOID) && 8772 "Should use MaskedValueIsZero if you don't know whether Op" 8773 " is a target node!"); 8774 8775 Known.resetAll(); 8776 switch (Opc) { 8777 default: break; 8778 case RISCVISD::SELECT_CC: { 8779 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8780 // If we don't know any bits, early out. 8781 if (Known.isUnknown()) 8782 break; 8783 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8784 8785 // Only known if known in both the LHS and RHS. 8786 Known = KnownBits::commonBits(Known, Known2); 8787 break; 8788 } 8789 case RISCVISD::REMUW: { 8790 KnownBits Known2; 8791 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8792 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8793 // We only care about the lower 32 bits. 8794 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8795 // Restore the original width by sign extending. 8796 Known = Known.sext(BitWidth); 8797 break; 8798 } 8799 case RISCVISD::DIVUW: { 8800 KnownBits Known2; 8801 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8802 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8803 // We only care about the lower 32 bits. 8804 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8805 // Restore the original width by sign extending. 8806 Known = Known.sext(BitWidth); 8807 break; 8808 } 8809 case RISCVISD::CTZW: { 8810 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8811 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8812 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8813 Known.Zero.setBitsFrom(LowBits); 8814 break; 8815 } 8816 case RISCVISD::CLZW: { 8817 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8818 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8819 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8820 Known.Zero.setBitsFrom(LowBits); 8821 break; 8822 } 8823 case RISCVISD::GREV: 8824 case RISCVISD::GREVW: { 8825 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8826 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8827 if (Opc == RISCVISD::GREVW) 8828 Known = Known.trunc(32); 8829 unsigned ShAmt = C->getZExtValue(); 8830 computeGREV(Known.Zero, ShAmt); 8831 computeGREV(Known.One, ShAmt); 8832 if (Opc == RISCVISD::GREVW) 8833 Known = Known.sext(BitWidth); 8834 } 8835 break; 8836 } 8837 case RISCVISD::READ_VLENB: { 8838 // If we know the minimum VLen from Zvl extensions, we can use that to 8839 // determine the trailing zeros of VLENB. 8840 // FIXME: Limit to 128 bit vectors until we have more testing. 8841 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8842 if (MinVLenB > 0) 8843 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8844 // We assume VLENB is no more than 65536 / 8 bytes. 8845 Known.Zero.setBitsFrom(14); 8846 break; 8847 } 8848 case ISD::INTRINSIC_W_CHAIN: 8849 case ISD::INTRINSIC_WO_CHAIN: { 8850 unsigned IntNo = 8851 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8852 switch (IntNo) { 8853 default: 8854 // We can't do anything for most intrinsics. 8855 break; 8856 case Intrinsic::riscv_vsetvli: 8857 case Intrinsic::riscv_vsetvlimax: 8858 case Intrinsic::riscv_vsetvli_opt: 8859 case Intrinsic::riscv_vsetvlimax_opt: 8860 // Assume that VL output is positive and would fit in an int32_t. 8861 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8862 if (BitWidth >= 32) 8863 Known.Zero.setBitsFrom(31); 8864 break; 8865 } 8866 break; 8867 } 8868 } 8869 } 8870 8871 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8872 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8873 unsigned Depth) const { 8874 switch (Op.getOpcode()) { 8875 default: 8876 break; 8877 case RISCVISD::SELECT_CC: { 8878 unsigned Tmp = 8879 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8880 if (Tmp == 1) return 1; // Early out. 8881 unsigned Tmp2 = 8882 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8883 return std::min(Tmp, Tmp2); 8884 } 8885 case RISCVISD::SLLW: 8886 case RISCVISD::SRAW: 8887 case RISCVISD::SRLW: 8888 case RISCVISD::DIVW: 8889 case RISCVISD::DIVUW: 8890 case RISCVISD::REMUW: 8891 case RISCVISD::ROLW: 8892 case RISCVISD::RORW: 8893 case RISCVISD::GREVW: 8894 case RISCVISD::GORCW: 8895 case RISCVISD::FSLW: 8896 case RISCVISD::FSRW: 8897 case RISCVISD::SHFLW: 8898 case RISCVISD::UNSHFLW: 8899 case RISCVISD::BCOMPRESSW: 8900 case RISCVISD::BDECOMPRESSW: 8901 case RISCVISD::BFPW: 8902 case RISCVISD::FCVT_W_RV64: 8903 case RISCVISD::FCVT_WU_RV64: 8904 case RISCVISD::STRICT_FCVT_W_RV64: 8905 case RISCVISD::STRICT_FCVT_WU_RV64: 8906 // TODO: As the result is sign-extended, this is conservatively correct. A 8907 // more precise answer could be calculated for SRAW depending on known 8908 // bits in the shift amount. 8909 return 33; 8910 case RISCVISD::SHFL: 8911 case RISCVISD::UNSHFL: { 8912 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8913 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8914 // will stay within the upper 32 bits. If there were more than 32 sign bits 8915 // before there will be at least 33 sign bits after. 8916 if (Op.getValueType() == MVT::i64 && 8917 isa<ConstantSDNode>(Op.getOperand(1)) && 8918 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8919 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8920 if (Tmp > 32) 8921 return 33; 8922 } 8923 break; 8924 } 8925 case RISCVISD::VMV_X_S: { 8926 // The number of sign bits of the scalar result is computed by obtaining the 8927 // element type of the input vector operand, subtracting its width from the 8928 // XLEN, and then adding one (sign bit within the element type). If the 8929 // element type is wider than XLen, the least-significant XLEN bits are 8930 // taken. 8931 unsigned XLen = Subtarget.getXLen(); 8932 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8933 if (EltBits <= XLen) 8934 return XLen - EltBits + 1; 8935 break; 8936 } 8937 } 8938 8939 return 1; 8940 } 8941 8942 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8943 MachineBasicBlock *BB) { 8944 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8945 8946 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8947 // Should the count have wrapped while it was being read, we need to try 8948 // again. 8949 // ... 8950 // read: 8951 // rdcycleh x3 # load high word of cycle 8952 // rdcycle x2 # load low word of cycle 8953 // rdcycleh x4 # load high word of cycle 8954 // bne x3, x4, read # check if high word reads match, otherwise try again 8955 // ... 8956 8957 MachineFunction &MF = *BB->getParent(); 8958 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8959 MachineFunction::iterator It = ++BB->getIterator(); 8960 8961 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8962 MF.insert(It, LoopMBB); 8963 8964 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8965 MF.insert(It, DoneMBB); 8966 8967 // Transfer the remainder of BB and its successor edges to DoneMBB. 8968 DoneMBB->splice(DoneMBB->begin(), BB, 8969 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8970 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8971 8972 BB->addSuccessor(LoopMBB); 8973 8974 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8975 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8976 Register LoReg = MI.getOperand(0).getReg(); 8977 Register HiReg = MI.getOperand(1).getReg(); 8978 DebugLoc DL = MI.getDebugLoc(); 8979 8980 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8981 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8982 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8983 .addReg(RISCV::X0); 8984 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8985 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8986 .addReg(RISCV::X0); 8987 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8988 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8989 .addReg(RISCV::X0); 8990 8991 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8992 .addReg(HiReg) 8993 .addReg(ReadAgainReg) 8994 .addMBB(LoopMBB); 8995 8996 LoopMBB->addSuccessor(LoopMBB); 8997 LoopMBB->addSuccessor(DoneMBB); 8998 8999 MI.eraseFromParent(); 9000 9001 return DoneMBB; 9002 } 9003 9004 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9005 MachineBasicBlock *BB) { 9006 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9007 9008 MachineFunction &MF = *BB->getParent(); 9009 DebugLoc DL = MI.getDebugLoc(); 9010 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9011 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9012 Register LoReg = MI.getOperand(0).getReg(); 9013 Register HiReg = MI.getOperand(1).getReg(); 9014 Register SrcReg = MI.getOperand(2).getReg(); 9015 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9016 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9017 9018 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9019 RI); 9020 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9021 MachineMemOperand *MMOLo = 9022 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9023 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9024 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9025 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9026 .addFrameIndex(FI) 9027 .addImm(0) 9028 .addMemOperand(MMOLo); 9029 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9030 .addFrameIndex(FI) 9031 .addImm(4) 9032 .addMemOperand(MMOHi); 9033 MI.eraseFromParent(); // The pseudo instruction is gone now. 9034 return BB; 9035 } 9036 9037 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9038 MachineBasicBlock *BB) { 9039 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9040 "Unexpected instruction"); 9041 9042 MachineFunction &MF = *BB->getParent(); 9043 DebugLoc DL = MI.getDebugLoc(); 9044 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9045 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9046 Register DstReg = MI.getOperand(0).getReg(); 9047 Register LoReg = MI.getOperand(1).getReg(); 9048 Register HiReg = MI.getOperand(2).getReg(); 9049 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9050 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9051 9052 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9053 MachineMemOperand *MMOLo = 9054 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9055 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9056 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9057 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9058 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9059 .addFrameIndex(FI) 9060 .addImm(0) 9061 .addMemOperand(MMOLo); 9062 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9063 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9064 .addFrameIndex(FI) 9065 .addImm(4) 9066 .addMemOperand(MMOHi); 9067 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9068 MI.eraseFromParent(); // The pseudo instruction is gone now. 9069 return BB; 9070 } 9071 9072 static bool isSelectPseudo(MachineInstr &MI) { 9073 switch (MI.getOpcode()) { 9074 default: 9075 return false; 9076 case RISCV::Select_GPR_Using_CC_GPR: 9077 case RISCV::Select_FPR16_Using_CC_GPR: 9078 case RISCV::Select_FPR32_Using_CC_GPR: 9079 case RISCV::Select_FPR64_Using_CC_GPR: 9080 return true; 9081 } 9082 } 9083 9084 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9085 unsigned RelOpcode, unsigned EqOpcode, 9086 const RISCVSubtarget &Subtarget) { 9087 DebugLoc DL = MI.getDebugLoc(); 9088 Register DstReg = MI.getOperand(0).getReg(); 9089 Register Src1Reg = MI.getOperand(1).getReg(); 9090 Register Src2Reg = MI.getOperand(2).getReg(); 9091 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9092 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9093 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9094 9095 // Save the current FFLAGS. 9096 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9097 9098 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9099 .addReg(Src1Reg) 9100 .addReg(Src2Reg); 9101 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9102 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9103 9104 // Restore the FFLAGS. 9105 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9106 .addReg(SavedFFlags, RegState::Kill); 9107 9108 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9109 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9110 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9111 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9112 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9113 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9114 9115 // Erase the pseudoinstruction. 9116 MI.eraseFromParent(); 9117 return BB; 9118 } 9119 9120 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9121 MachineBasicBlock *BB, 9122 const RISCVSubtarget &Subtarget) { 9123 // To "insert" Select_* instructions, we actually have to insert the triangle 9124 // control-flow pattern. The incoming instructions know the destination vreg 9125 // to set, the condition code register to branch on, the true/false values to 9126 // select between, and the condcode to use to select the appropriate branch. 9127 // 9128 // We produce the following control flow: 9129 // HeadMBB 9130 // | \ 9131 // | IfFalseMBB 9132 // | / 9133 // TailMBB 9134 // 9135 // When we find a sequence of selects we attempt to optimize their emission 9136 // by sharing the control flow. Currently we only handle cases where we have 9137 // multiple selects with the exact same condition (same LHS, RHS and CC). 9138 // The selects may be interleaved with other instructions if the other 9139 // instructions meet some requirements we deem safe: 9140 // - They are debug instructions. Otherwise, 9141 // - They do not have side-effects, do not access memory and their inputs do 9142 // not depend on the results of the select pseudo-instructions. 9143 // The TrueV/FalseV operands of the selects cannot depend on the result of 9144 // previous selects in the sequence. 9145 // These conditions could be further relaxed. See the X86 target for a 9146 // related approach and more information. 9147 Register LHS = MI.getOperand(1).getReg(); 9148 Register RHS = MI.getOperand(2).getReg(); 9149 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9150 9151 SmallVector<MachineInstr *, 4> SelectDebugValues; 9152 SmallSet<Register, 4> SelectDests; 9153 SelectDests.insert(MI.getOperand(0).getReg()); 9154 9155 MachineInstr *LastSelectPseudo = &MI; 9156 9157 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9158 SequenceMBBI != E; ++SequenceMBBI) { 9159 if (SequenceMBBI->isDebugInstr()) 9160 continue; 9161 else if (isSelectPseudo(*SequenceMBBI)) { 9162 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9163 SequenceMBBI->getOperand(2).getReg() != RHS || 9164 SequenceMBBI->getOperand(3).getImm() != CC || 9165 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9166 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9167 break; 9168 LastSelectPseudo = &*SequenceMBBI; 9169 SequenceMBBI->collectDebugValues(SelectDebugValues); 9170 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9171 } else { 9172 if (SequenceMBBI->hasUnmodeledSideEffects() || 9173 SequenceMBBI->mayLoadOrStore()) 9174 break; 9175 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9176 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9177 })) 9178 break; 9179 } 9180 } 9181 9182 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9183 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9184 DebugLoc DL = MI.getDebugLoc(); 9185 MachineFunction::iterator I = ++BB->getIterator(); 9186 9187 MachineBasicBlock *HeadMBB = BB; 9188 MachineFunction *F = BB->getParent(); 9189 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9190 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9191 9192 F->insert(I, IfFalseMBB); 9193 F->insert(I, TailMBB); 9194 9195 // Transfer debug instructions associated with the selects to TailMBB. 9196 for (MachineInstr *DebugInstr : SelectDebugValues) { 9197 TailMBB->push_back(DebugInstr->removeFromParent()); 9198 } 9199 9200 // Move all instructions after the sequence to TailMBB. 9201 TailMBB->splice(TailMBB->end(), HeadMBB, 9202 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9203 // Update machine-CFG edges by transferring all successors of the current 9204 // block to the new block which will contain the Phi nodes for the selects. 9205 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9206 // Set the successors for HeadMBB. 9207 HeadMBB->addSuccessor(IfFalseMBB); 9208 HeadMBB->addSuccessor(TailMBB); 9209 9210 // Insert appropriate branch. 9211 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9212 .addReg(LHS) 9213 .addReg(RHS) 9214 .addMBB(TailMBB); 9215 9216 // IfFalseMBB just falls through to TailMBB. 9217 IfFalseMBB->addSuccessor(TailMBB); 9218 9219 // Create PHIs for all of the select pseudo-instructions. 9220 auto SelectMBBI = MI.getIterator(); 9221 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9222 auto InsertionPoint = TailMBB->begin(); 9223 while (SelectMBBI != SelectEnd) { 9224 auto Next = std::next(SelectMBBI); 9225 if (isSelectPseudo(*SelectMBBI)) { 9226 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9227 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9228 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9229 .addReg(SelectMBBI->getOperand(4).getReg()) 9230 .addMBB(HeadMBB) 9231 .addReg(SelectMBBI->getOperand(5).getReg()) 9232 .addMBB(IfFalseMBB); 9233 SelectMBBI->eraseFromParent(); 9234 } 9235 SelectMBBI = Next; 9236 } 9237 9238 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9239 return TailMBB; 9240 } 9241 9242 MachineBasicBlock * 9243 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9244 MachineBasicBlock *BB) const { 9245 switch (MI.getOpcode()) { 9246 default: 9247 llvm_unreachable("Unexpected instr type to insert"); 9248 case RISCV::ReadCycleWide: 9249 assert(!Subtarget.is64Bit() && 9250 "ReadCycleWrite is only to be used on riscv32"); 9251 return emitReadCycleWidePseudo(MI, BB); 9252 case RISCV::Select_GPR_Using_CC_GPR: 9253 case RISCV::Select_FPR16_Using_CC_GPR: 9254 case RISCV::Select_FPR32_Using_CC_GPR: 9255 case RISCV::Select_FPR64_Using_CC_GPR: 9256 return emitSelectPseudo(MI, BB, Subtarget); 9257 case RISCV::BuildPairF64Pseudo: 9258 return emitBuildPairF64Pseudo(MI, BB); 9259 case RISCV::SplitF64Pseudo: 9260 return emitSplitF64Pseudo(MI, BB); 9261 case RISCV::PseudoQuietFLE_H: 9262 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9263 case RISCV::PseudoQuietFLT_H: 9264 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9265 case RISCV::PseudoQuietFLE_S: 9266 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9267 case RISCV::PseudoQuietFLT_S: 9268 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9269 case RISCV::PseudoQuietFLE_D: 9270 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9271 case RISCV::PseudoQuietFLT_D: 9272 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9273 } 9274 } 9275 9276 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9277 SDNode *Node) const { 9278 // Add FRM dependency to any instructions with dynamic rounding mode. 9279 unsigned Opc = MI.getOpcode(); 9280 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9281 if (Idx < 0) 9282 return; 9283 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9284 return; 9285 // If the instruction already reads FRM, don't add another read. 9286 if (MI.readsRegister(RISCV::FRM)) 9287 return; 9288 MI.addOperand( 9289 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9290 } 9291 9292 // Calling Convention Implementation. 9293 // The expectations for frontend ABI lowering vary from target to target. 9294 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9295 // details, but this is a longer term goal. For now, we simply try to keep the 9296 // role of the frontend as simple and well-defined as possible. The rules can 9297 // be summarised as: 9298 // * Never split up large scalar arguments. We handle them here. 9299 // * If a hardfloat calling convention is being used, and the struct may be 9300 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9301 // available, then pass as two separate arguments. If either the GPRs or FPRs 9302 // are exhausted, then pass according to the rule below. 9303 // * If a struct could never be passed in registers or directly in a stack 9304 // slot (as it is larger than 2*XLEN and the floating point rules don't 9305 // apply), then pass it using a pointer with the byval attribute. 9306 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9307 // word-sized array or a 2*XLEN scalar (depending on alignment). 9308 // * The frontend can determine whether a struct is returned by reference or 9309 // not based on its size and fields. If it will be returned by reference, the 9310 // frontend must modify the prototype so a pointer with the sret annotation is 9311 // passed as the first argument. This is not necessary for large scalar 9312 // returns. 9313 // * Struct return values and varargs should be coerced to structs containing 9314 // register-size fields in the same situations they would be for fixed 9315 // arguments. 9316 9317 static const MCPhysReg ArgGPRs[] = { 9318 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9319 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9320 }; 9321 static const MCPhysReg ArgFPR16s[] = { 9322 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9323 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9324 }; 9325 static const MCPhysReg ArgFPR32s[] = { 9326 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9327 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9328 }; 9329 static const MCPhysReg ArgFPR64s[] = { 9330 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9331 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9332 }; 9333 // This is an interim calling convention and it may be changed in the future. 9334 static const MCPhysReg ArgVRs[] = { 9335 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9336 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9337 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9338 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9339 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9340 RISCV::V20M2, RISCV::V22M2}; 9341 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9342 RISCV::V20M4}; 9343 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9344 9345 // Pass a 2*XLEN argument that has been split into two XLEN values through 9346 // registers or the stack as necessary. 9347 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9348 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9349 MVT ValVT2, MVT LocVT2, 9350 ISD::ArgFlagsTy ArgFlags2) { 9351 unsigned XLenInBytes = XLen / 8; 9352 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9353 // At least one half can be passed via register. 9354 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9355 VA1.getLocVT(), CCValAssign::Full)); 9356 } else { 9357 // Both halves must be passed on the stack, with proper alignment. 9358 Align StackAlign = 9359 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9360 State.addLoc( 9361 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9362 State.AllocateStack(XLenInBytes, StackAlign), 9363 VA1.getLocVT(), CCValAssign::Full)); 9364 State.addLoc(CCValAssign::getMem( 9365 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9366 LocVT2, CCValAssign::Full)); 9367 return false; 9368 } 9369 9370 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9371 // The second half can also be passed via register. 9372 State.addLoc( 9373 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9374 } else { 9375 // The second half is passed via the stack, without additional alignment. 9376 State.addLoc(CCValAssign::getMem( 9377 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9378 LocVT2, CCValAssign::Full)); 9379 } 9380 9381 return false; 9382 } 9383 9384 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9385 Optional<unsigned> FirstMaskArgument, 9386 CCState &State, const RISCVTargetLowering &TLI) { 9387 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9388 if (RC == &RISCV::VRRegClass) { 9389 // Assign the first mask argument to V0. 9390 // This is an interim calling convention and it may be changed in the 9391 // future. 9392 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9393 return State.AllocateReg(RISCV::V0); 9394 return State.AllocateReg(ArgVRs); 9395 } 9396 if (RC == &RISCV::VRM2RegClass) 9397 return State.AllocateReg(ArgVRM2s); 9398 if (RC == &RISCV::VRM4RegClass) 9399 return State.AllocateReg(ArgVRM4s); 9400 if (RC == &RISCV::VRM8RegClass) 9401 return State.AllocateReg(ArgVRM8s); 9402 llvm_unreachable("Unhandled register class for ValueType"); 9403 } 9404 9405 // Implements the RISC-V calling convention. Returns true upon failure. 9406 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9407 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9408 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9409 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9410 Optional<unsigned> FirstMaskArgument) { 9411 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9412 assert(XLen == 32 || XLen == 64); 9413 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9414 9415 // Any return value split in to more than two values can't be returned 9416 // directly. Vectors are returned via the available vector registers. 9417 if (!LocVT.isVector() && IsRet && ValNo > 1) 9418 return true; 9419 9420 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9421 // variadic argument, or if no F16/F32 argument registers are available. 9422 bool UseGPRForF16_F32 = true; 9423 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9424 // variadic argument, or if no F64 argument registers are available. 9425 bool UseGPRForF64 = true; 9426 9427 switch (ABI) { 9428 default: 9429 llvm_unreachable("Unexpected ABI"); 9430 case RISCVABI::ABI_ILP32: 9431 case RISCVABI::ABI_LP64: 9432 break; 9433 case RISCVABI::ABI_ILP32F: 9434 case RISCVABI::ABI_LP64F: 9435 UseGPRForF16_F32 = !IsFixed; 9436 break; 9437 case RISCVABI::ABI_ILP32D: 9438 case RISCVABI::ABI_LP64D: 9439 UseGPRForF16_F32 = !IsFixed; 9440 UseGPRForF64 = !IsFixed; 9441 break; 9442 } 9443 9444 // FPR16, FPR32, and FPR64 alias each other. 9445 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9446 UseGPRForF16_F32 = true; 9447 UseGPRForF64 = true; 9448 } 9449 9450 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9451 // similar local variables rather than directly checking against the target 9452 // ABI. 9453 9454 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9455 LocVT = XLenVT; 9456 LocInfo = CCValAssign::BCvt; 9457 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9458 LocVT = MVT::i64; 9459 LocInfo = CCValAssign::BCvt; 9460 } 9461 9462 // If this is a variadic argument, the RISC-V calling convention requires 9463 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9464 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9465 // be used regardless of whether the original argument was split during 9466 // legalisation or not. The argument will not be passed by registers if the 9467 // original type is larger than 2*XLEN, so the register alignment rule does 9468 // not apply. 9469 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9470 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9471 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9472 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9473 // Skip 'odd' register if necessary. 9474 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9475 State.AllocateReg(ArgGPRs); 9476 } 9477 9478 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9479 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9480 State.getPendingArgFlags(); 9481 9482 assert(PendingLocs.size() == PendingArgFlags.size() && 9483 "PendingLocs and PendingArgFlags out of sync"); 9484 9485 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9486 // registers are exhausted. 9487 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9488 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9489 "Can't lower f64 if it is split"); 9490 // Depending on available argument GPRS, f64 may be passed in a pair of 9491 // GPRs, split between a GPR and the stack, or passed completely on the 9492 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9493 // cases. 9494 Register Reg = State.AllocateReg(ArgGPRs); 9495 LocVT = MVT::i32; 9496 if (!Reg) { 9497 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9498 State.addLoc( 9499 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9500 return false; 9501 } 9502 if (!State.AllocateReg(ArgGPRs)) 9503 State.AllocateStack(4, Align(4)); 9504 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9505 return false; 9506 } 9507 9508 // Fixed-length vectors are located in the corresponding scalable-vector 9509 // container types. 9510 if (ValVT.isFixedLengthVector()) 9511 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9512 9513 // Split arguments might be passed indirectly, so keep track of the pending 9514 // values. Split vectors are passed via a mix of registers and indirectly, so 9515 // treat them as we would any other argument. 9516 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9517 LocVT = XLenVT; 9518 LocInfo = CCValAssign::Indirect; 9519 PendingLocs.push_back( 9520 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9521 PendingArgFlags.push_back(ArgFlags); 9522 if (!ArgFlags.isSplitEnd()) { 9523 return false; 9524 } 9525 } 9526 9527 // If the split argument only had two elements, it should be passed directly 9528 // in registers or on the stack. 9529 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9530 PendingLocs.size() <= 2) { 9531 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9532 // Apply the normal calling convention rules to the first half of the 9533 // split argument. 9534 CCValAssign VA = PendingLocs[0]; 9535 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9536 PendingLocs.clear(); 9537 PendingArgFlags.clear(); 9538 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9539 ArgFlags); 9540 } 9541 9542 // Allocate to a register if possible, or else a stack slot. 9543 Register Reg; 9544 unsigned StoreSizeBytes = XLen / 8; 9545 Align StackAlign = Align(XLen / 8); 9546 9547 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9548 Reg = State.AllocateReg(ArgFPR16s); 9549 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9550 Reg = State.AllocateReg(ArgFPR32s); 9551 else if (ValVT == MVT::f64 && !UseGPRForF64) 9552 Reg = State.AllocateReg(ArgFPR64s); 9553 else if (ValVT.isVector()) { 9554 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9555 if (!Reg) { 9556 // For return values, the vector must be passed fully via registers or 9557 // via the stack. 9558 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9559 // but we're using all of them. 9560 if (IsRet) 9561 return true; 9562 // Try using a GPR to pass the address 9563 if ((Reg = State.AllocateReg(ArgGPRs))) { 9564 LocVT = XLenVT; 9565 LocInfo = CCValAssign::Indirect; 9566 } else if (ValVT.isScalableVector()) { 9567 LocVT = XLenVT; 9568 LocInfo = CCValAssign::Indirect; 9569 } else { 9570 // Pass fixed-length vectors on the stack. 9571 LocVT = ValVT; 9572 StoreSizeBytes = ValVT.getStoreSize(); 9573 // Align vectors to their element sizes, being careful for vXi1 9574 // vectors. 9575 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9576 } 9577 } 9578 } else { 9579 Reg = State.AllocateReg(ArgGPRs); 9580 } 9581 9582 unsigned StackOffset = 9583 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9584 9585 // If we reach this point and PendingLocs is non-empty, we must be at the 9586 // end of a split argument that must be passed indirectly. 9587 if (!PendingLocs.empty()) { 9588 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9589 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9590 9591 for (auto &It : PendingLocs) { 9592 if (Reg) 9593 It.convertToReg(Reg); 9594 else 9595 It.convertToMem(StackOffset); 9596 State.addLoc(It); 9597 } 9598 PendingLocs.clear(); 9599 PendingArgFlags.clear(); 9600 return false; 9601 } 9602 9603 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9604 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9605 "Expected an XLenVT or vector types at this stage"); 9606 9607 if (Reg) { 9608 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9609 return false; 9610 } 9611 9612 // When a floating-point value is passed on the stack, no bit-conversion is 9613 // needed. 9614 if (ValVT.isFloatingPoint()) { 9615 LocVT = ValVT; 9616 LocInfo = CCValAssign::Full; 9617 } 9618 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9619 return false; 9620 } 9621 9622 template <typename ArgTy> 9623 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9624 for (const auto &ArgIdx : enumerate(Args)) { 9625 MVT ArgVT = ArgIdx.value().VT; 9626 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9627 return ArgIdx.index(); 9628 } 9629 return None; 9630 } 9631 9632 void RISCVTargetLowering::analyzeInputArgs( 9633 MachineFunction &MF, CCState &CCInfo, 9634 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9635 RISCVCCAssignFn Fn) const { 9636 unsigned NumArgs = Ins.size(); 9637 FunctionType *FType = MF.getFunction().getFunctionType(); 9638 9639 Optional<unsigned> FirstMaskArgument; 9640 if (Subtarget.hasVInstructions()) 9641 FirstMaskArgument = preAssignMask(Ins); 9642 9643 for (unsigned i = 0; i != NumArgs; ++i) { 9644 MVT ArgVT = Ins[i].VT; 9645 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9646 9647 Type *ArgTy = nullptr; 9648 if (IsRet) 9649 ArgTy = FType->getReturnType(); 9650 else if (Ins[i].isOrigArg()) 9651 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9652 9653 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9654 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9655 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9656 FirstMaskArgument)) { 9657 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9658 << EVT(ArgVT).getEVTString() << '\n'); 9659 llvm_unreachable(nullptr); 9660 } 9661 } 9662 } 9663 9664 void RISCVTargetLowering::analyzeOutputArgs( 9665 MachineFunction &MF, CCState &CCInfo, 9666 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9667 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9668 unsigned NumArgs = Outs.size(); 9669 9670 Optional<unsigned> FirstMaskArgument; 9671 if (Subtarget.hasVInstructions()) 9672 FirstMaskArgument = preAssignMask(Outs); 9673 9674 for (unsigned i = 0; i != NumArgs; i++) { 9675 MVT ArgVT = Outs[i].VT; 9676 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9677 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9678 9679 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9680 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9681 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9682 FirstMaskArgument)) { 9683 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9684 << EVT(ArgVT).getEVTString() << "\n"); 9685 llvm_unreachable(nullptr); 9686 } 9687 } 9688 } 9689 9690 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9691 // values. 9692 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9693 const CCValAssign &VA, const SDLoc &DL, 9694 const RISCVSubtarget &Subtarget) { 9695 switch (VA.getLocInfo()) { 9696 default: 9697 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9698 case CCValAssign::Full: 9699 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9700 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9701 break; 9702 case CCValAssign::BCvt: 9703 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9704 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9705 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9706 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9707 else 9708 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9709 break; 9710 } 9711 return Val; 9712 } 9713 9714 // The caller is responsible for loading the full value if the argument is 9715 // passed with CCValAssign::Indirect. 9716 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9717 const CCValAssign &VA, const SDLoc &DL, 9718 const RISCVTargetLowering &TLI) { 9719 MachineFunction &MF = DAG.getMachineFunction(); 9720 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9721 EVT LocVT = VA.getLocVT(); 9722 SDValue Val; 9723 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9724 Register VReg = RegInfo.createVirtualRegister(RC); 9725 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9726 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9727 9728 if (VA.getLocInfo() == CCValAssign::Indirect) 9729 return Val; 9730 9731 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9732 } 9733 9734 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9735 const CCValAssign &VA, const SDLoc &DL, 9736 const RISCVSubtarget &Subtarget) { 9737 EVT LocVT = VA.getLocVT(); 9738 9739 switch (VA.getLocInfo()) { 9740 default: 9741 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9742 case CCValAssign::Full: 9743 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9744 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9745 break; 9746 case CCValAssign::BCvt: 9747 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9748 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9749 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9750 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9751 else 9752 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9753 break; 9754 } 9755 return Val; 9756 } 9757 9758 // The caller is responsible for loading the full value if the argument is 9759 // passed with CCValAssign::Indirect. 9760 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9761 const CCValAssign &VA, const SDLoc &DL) { 9762 MachineFunction &MF = DAG.getMachineFunction(); 9763 MachineFrameInfo &MFI = MF.getFrameInfo(); 9764 EVT LocVT = VA.getLocVT(); 9765 EVT ValVT = VA.getValVT(); 9766 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9767 if (ValVT.isScalableVector()) { 9768 // When the value is a scalable vector, we save the pointer which points to 9769 // the scalable vector value in the stack. The ValVT will be the pointer 9770 // type, instead of the scalable vector type. 9771 ValVT = LocVT; 9772 } 9773 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9774 /*IsImmutable=*/true); 9775 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9776 SDValue Val; 9777 9778 ISD::LoadExtType ExtType; 9779 switch (VA.getLocInfo()) { 9780 default: 9781 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9782 case CCValAssign::Full: 9783 case CCValAssign::Indirect: 9784 case CCValAssign::BCvt: 9785 ExtType = ISD::NON_EXTLOAD; 9786 break; 9787 } 9788 Val = DAG.getExtLoad( 9789 ExtType, DL, LocVT, Chain, FIN, 9790 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9791 return Val; 9792 } 9793 9794 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9795 const CCValAssign &VA, const SDLoc &DL) { 9796 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9797 "Unexpected VA"); 9798 MachineFunction &MF = DAG.getMachineFunction(); 9799 MachineFrameInfo &MFI = MF.getFrameInfo(); 9800 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9801 9802 if (VA.isMemLoc()) { 9803 // f64 is passed on the stack. 9804 int FI = 9805 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9806 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9807 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9808 MachinePointerInfo::getFixedStack(MF, FI)); 9809 } 9810 9811 assert(VA.isRegLoc() && "Expected register VA assignment"); 9812 9813 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9814 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9815 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9816 SDValue Hi; 9817 if (VA.getLocReg() == RISCV::X17) { 9818 // Second half of f64 is passed on the stack. 9819 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9820 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9821 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9822 MachinePointerInfo::getFixedStack(MF, FI)); 9823 } else { 9824 // Second half of f64 is passed in another GPR. 9825 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9826 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9827 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9828 } 9829 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9830 } 9831 9832 // FastCC has less than 1% performance improvement for some particular 9833 // benchmark. But theoretically, it may has benenfit for some cases. 9834 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9835 unsigned ValNo, MVT ValVT, MVT LocVT, 9836 CCValAssign::LocInfo LocInfo, 9837 ISD::ArgFlagsTy ArgFlags, CCState &State, 9838 bool IsFixed, bool IsRet, Type *OrigTy, 9839 const RISCVTargetLowering &TLI, 9840 Optional<unsigned> FirstMaskArgument) { 9841 9842 // X5 and X6 might be used for save-restore libcall. 9843 static const MCPhysReg GPRList[] = { 9844 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9845 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9846 RISCV::X29, RISCV::X30, RISCV::X31}; 9847 9848 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9849 if (unsigned Reg = State.AllocateReg(GPRList)) { 9850 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9851 return false; 9852 } 9853 } 9854 9855 if (LocVT == MVT::f16) { 9856 static const MCPhysReg FPR16List[] = { 9857 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9858 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9859 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9860 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9861 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9862 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9863 return false; 9864 } 9865 } 9866 9867 if (LocVT == MVT::f32) { 9868 static const MCPhysReg FPR32List[] = { 9869 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9870 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9871 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9872 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9873 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9874 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9875 return false; 9876 } 9877 } 9878 9879 if (LocVT == MVT::f64) { 9880 static const MCPhysReg FPR64List[] = { 9881 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9882 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9883 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9884 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9885 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9886 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9887 return false; 9888 } 9889 } 9890 9891 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9892 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9893 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9894 return false; 9895 } 9896 9897 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9898 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9899 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9900 return false; 9901 } 9902 9903 if (LocVT.isVector()) { 9904 if (unsigned Reg = 9905 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9906 // Fixed-length vectors are located in the corresponding scalable-vector 9907 // container types. 9908 if (ValVT.isFixedLengthVector()) 9909 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9910 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9911 } else { 9912 // Try and pass the address via a "fast" GPR. 9913 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9914 LocInfo = CCValAssign::Indirect; 9915 LocVT = TLI.getSubtarget().getXLenVT(); 9916 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9917 } else if (ValVT.isFixedLengthVector()) { 9918 auto StackAlign = 9919 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9920 unsigned StackOffset = 9921 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9922 State.addLoc( 9923 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9924 } else { 9925 // Can't pass scalable vectors on the stack. 9926 return true; 9927 } 9928 } 9929 9930 return false; 9931 } 9932 9933 return true; // CC didn't match. 9934 } 9935 9936 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9937 CCValAssign::LocInfo LocInfo, 9938 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9939 9940 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9941 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9942 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9943 static const MCPhysReg GPRList[] = { 9944 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9945 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9946 if (unsigned Reg = State.AllocateReg(GPRList)) { 9947 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9948 return false; 9949 } 9950 } 9951 9952 if (LocVT == MVT::f32) { 9953 // Pass in STG registers: F1, ..., F6 9954 // fs0 ... fs5 9955 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9956 RISCV::F18_F, RISCV::F19_F, 9957 RISCV::F20_F, RISCV::F21_F}; 9958 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9959 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9960 return false; 9961 } 9962 } 9963 9964 if (LocVT == MVT::f64) { 9965 // Pass in STG registers: D1, ..., D6 9966 // fs6 ... fs11 9967 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9968 RISCV::F24_D, RISCV::F25_D, 9969 RISCV::F26_D, RISCV::F27_D}; 9970 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9971 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9972 return false; 9973 } 9974 } 9975 9976 report_fatal_error("No registers left in GHC calling convention"); 9977 return true; 9978 } 9979 9980 // Transform physical registers into virtual registers. 9981 SDValue RISCVTargetLowering::LowerFormalArguments( 9982 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9983 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9984 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9985 9986 MachineFunction &MF = DAG.getMachineFunction(); 9987 9988 switch (CallConv) { 9989 default: 9990 report_fatal_error("Unsupported calling convention"); 9991 case CallingConv::C: 9992 case CallingConv::Fast: 9993 break; 9994 case CallingConv::GHC: 9995 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9996 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9997 report_fatal_error( 9998 "GHC calling convention requires the F and D instruction set extensions"); 9999 } 10000 10001 const Function &Func = MF.getFunction(); 10002 if (Func.hasFnAttribute("interrupt")) { 10003 if (!Func.arg_empty()) 10004 report_fatal_error( 10005 "Functions with the interrupt attribute cannot have arguments!"); 10006 10007 StringRef Kind = 10008 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10009 10010 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10011 report_fatal_error( 10012 "Function interrupt attribute argument not supported!"); 10013 } 10014 10015 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10016 MVT XLenVT = Subtarget.getXLenVT(); 10017 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10018 // Used with vargs to acumulate store chains. 10019 std::vector<SDValue> OutChains; 10020 10021 // Assign locations to all of the incoming arguments. 10022 SmallVector<CCValAssign, 16> ArgLocs; 10023 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10024 10025 if (CallConv == CallingConv::GHC) 10026 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10027 else 10028 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10029 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10030 : CC_RISCV); 10031 10032 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10033 CCValAssign &VA = ArgLocs[i]; 10034 SDValue ArgValue; 10035 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10036 // case. 10037 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10038 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10039 else if (VA.isRegLoc()) 10040 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10041 else 10042 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10043 10044 if (VA.getLocInfo() == CCValAssign::Indirect) { 10045 // If the original argument was split and passed by reference (e.g. i128 10046 // on RV32), we need to load all parts of it here (using the same 10047 // address). Vectors may be partly split to registers and partly to the 10048 // stack, in which case the base address is partly offset and subsequent 10049 // stores are relative to that. 10050 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10051 MachinePointerInfo())); 10052 unsigned ArgIndex = Ins[i].OrigArgIndex; 10053 unsigned ArgPartOffset = Ins[i].PartOffset; 10054 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10055 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10056 CCValAssign &PartVA = ArgLocs[i + 1]; 10057 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10058 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10059 if (PartVA.getValVT().isScalableVector()) 10060 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10061 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10062 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10063 MachinePointerInfo())); 10064 ++i; 10065 } 10066 continue; 10067 } 10068 InVals.push_back(ArgValue); 10069 } 10070 10071 if (IsVarArg) { 10072 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10073 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10074 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10075 MachineFrameInfo &MFI = MF.getFrameInfo(); 10076 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10077 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10078 10079 // Offset of the first variable argument from stack pointer, and size of 10080 // the vararg save area. For now, the varargs save area is either zero or 10081 // large enough to hold a0-a7. 10082 int VaArgOffset, VarArgsSaveSize; 10083 10084 // If all registers are allocated, then all varargs must be passed on the 10085 // stack and we don't need to save any argregs. 10086 if (ArgRegs.size() == Idx) { 10087 VaArgOffset = CCInfo.getNextStackOffset(); 10088 VarArgsSaveSize = 0; 10089 } else { 10090 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10091 VaArgOffset = -VarArgsSaveSize; 10092 } 10093 10094 // Record the frame index of the first variable argument 10095 // which is a value necessary to VASTART. 10096 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10097 RVFI->setVarArgsFrameIndex(FI); 10098 10099 // If saving an odd number of registers then create an extra stack slot to 10100 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10101 // offsets to even-numbered registered remain 2*XLEN-aligned. 10102 if (Idx % 2) { 10103 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10104 VarArgsSaveSize += XLenInBytes; 10105 } 10106 10107 // Copy the integer registers that may have been used for passing varargs 10108 // to the vararg save area. 10109 for (unsigned I = Idx; I < ArgRegs.size(); 10110 ++I, VaArgOffset += XLenInBytes) { 10111 const Register Reg = RegInfo.createVirtualRegister(RC); 10112 RegInfo.addLiveIn(ArgRegs[I], Reg); 10113 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10114 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10115 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10116 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10117 MachinePointerInfo::getFixedStack(MF, FI)); 10118 cast<StoreSDNode>(Store.getNode()) 10119 ->getMemOperand() 10120 ->setValue((Value *)nullptr); 10121 OutChains.push_back(Store); 10122 } 10123 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10124 } 10125 10126 // All stores are grouped in one node to allow the matching between 10127 // the size of Ins and InVals. This only happens for vararg functions. 10128 if (!OutChains.empty()) { 10129 OutChains.push_back(Chain); 10130 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10131 } 10132 10133 return Chain; 10134 } 10135 10136 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10137 /// for tail call optimization. 10138 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10139 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10140 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10141 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10142 10143 auto &Callee = CLI.Callee; 10144 auto CalleeCC = CLI.CallConv; 10145 auto &Outs = CLI.Outs; 10146 auto &Caller = MF.getFunction(); 10147 auto CallerCC = Caller.getCallingConv(); 10148 10149 // Exception-handling functions need a special set of instructions to 10150 // indicate a return to the hardware. Tail-calling another function would 10151 // probably break this. 10152 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10153 // should be expanded as new function attributes are introduced. 10154 if (Caller.hasFnAttribute("interrupt")) 10155 return false; 10156 10157 // Do not tail call opt if the stack is used to pass parameters. 10158 if (CCInfo.getNextStackOffset() != 0) 10159 return false; 10160 10161 // Do not tail call opt if any parameters need to be passed indirectly. 10162 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10163 // passed indirectly. So the address of the value will be passed in a 10164 // register, or if not available, then the address is put on the stack. In 10165 // order to pass indirectly, space on the stack often needs to be allocated 10166 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10167 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10168 // are passed CCValAssign::Indirect. 10169 for (auto &VA : ArgLocs) 10170 if (VA.getLocInfo() == CCValAssign::Indirect) 10171 return false; 10172 10173 // Do not tail call opt if either caller or callee uses struct return 10174 // semantics. 10175 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10176 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10177 if (IsCallerStructRet || IsCalleeStructRet) 10178 return false; 10179 10180 // Externally-defined functions with weak linkage should not be 10181 // tail-called. The behaviour of branch instructions in this situation (as 10182 // used for tail calls) is implementation-defined, so we cannot rely on the 10183 // linker replacing the tail call with a return. 10184 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10185 const GlobalValue *GV = G->getGlobal(); 10186 if (GV->hasExternalWeakLinkage()) 10187 return false; 10188 } 10189 10190 // The callee has to preserve all registers the caller needs to preserve. 10191 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10192 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10193 if (CalleeCC != CallerCC) { 10194 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10195 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10196 return false; 10197 } 10198 10199 // Byval parameters hand the function a pointer directly into the stack area 10200 // we want to reuse during a tail call. Working around this *is* possible 10201 // but less efficient and uglier in LowerCall. 10202 for (auto &Arg : Outs) 10203 if (Arg.Flags.isByVal()) 10204 return false; 10205 10206 return true; 10207 } 10208 10209 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10210 return DAG.getDataLayout().getPrefTypeAlign( 10211 VT.getTypeForEVT(*DAG.getContext())); 10212 } 10213 10214 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10215 // and output parameter nodes. 10216 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10217 SmallVectorImpl<SDValue> &InVals) const { 10218 SelectionDAG &DAG = CLI.DAG; 10219 SDLoc &DL = CLI.DL; 10220 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10221 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10222 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10223 SDValue Chain = CLI.Chain; 10224 SDValue Callee = CLI.Callee; 10225 bool &IsTailCall = CLI.IsTailCall; 10226 CallingConv::ID CallConv = CLI.CallConv; 10227 bool IsVarArg = CLI.IsVarArg; 10228 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10229 MVT XLenVT = Subtarget.getXLenVT(); 10230 10231 MachineFunction &MF = DAG.getMachineFunction(); 10232 10233 // Analyze the operands of the call, assigning locations to each operand. 10234 SmallVector<CCValAssign, 16> ArgLocs; 10235 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10236 10237 if (CallConv == CallingConv::GHC) 10238 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10239 else 10240 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10241 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10242 : CC_RISCV); 10243 10244 // Check if it's really possible to do a tail call. 10245 if (IsTailCall) 10246 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10247 10248 if (IsTailCall) 10249 ++NumTailCalls; 10250 else if (CLI.CB && CLI.CB->isMustTailCall()) 10251 report_fatal_error("failed to perform tail call elimination on a call " 10252 "site marked musttail"); 10253 10254 // Get a count of how many bytes are to be pushed on the stack. 10255 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10256 10257 // Create local copies for byval args 10258 SmallVector<SDValue, 8> ByValArgs; 10259 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10260 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10261 if (!Flags.isByVal()) 10262 continue; 10263 10264 SDValue Arg = OutVals[i]; 10265 unsigned Size = Flags.getByValSize(); 10266 Align Alignment = Flags.getNonZeroByValAlign(); 10267 10268 int FI = 10269 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10270 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10271 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10272 10273 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10274 /*IsVolatile=*/false, 10275 /*AlwaysInline=*/false, IsTailCall, 10276 MachinePointerInfo(), MachinePointerInfo()); 10277 ByValArgs.push_back(FIPtr); 10278 } 10279 10280 if (!IsTailCall) 10281 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10282 10283 // Copy argument values to their designated locations. 10284 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10285 SmallVector<SDValue, 8> MemOpChains; 10286 SDValue StackPtr; 10287 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10288 CCValAssign &VA = ArgLocs[i]; 10289 SDValue ArgValue = OutVals[i]; 10290 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10291 10292 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10293 bool IsF64OnRV32DSoftABI = 10294 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10295 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10296 SDValue SplitF64 = DAG.getNode( 10297 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10298 SDValue Lo = SplitF64.getValue(0); 10299 SDValue Hi = SplitF64.getValue(1); 10300 10301 Register RegLo = VA.getLocReg(); 10302 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10303 10304 if (RegLo == RISCV::X17) { 10305 // Second half of f64 is passed on the stack. 10306 // Work out the address of the stack slot. 10307 if (!StackPtr.getNode()) 10308 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10309 // Emit the store. 10310 MemOpChains.push_back( 10311 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10312 } else { 10313 // Second half of f64 is passed in another GPR. 10314 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10315 Register RegHigh = RegLo + 1; 10316 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10317 } 10318 continue; 10319 } 10320 10321 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10322 // as any other MemLoc. 10323 10324 // Promote the value if needed. 10325 // For now, only handle fully promoted and indirect arguments. 10326 if (VA.getLocInfo() == CCValAssign::Indirect) { 10327 // Store the argument in a stack slot and pass its address. 10328 Align StackAlign = 10329 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10330 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10331 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10332 // If the original argument was split (e.g. i128), we need 10333 // to store the required parts of it here (and pass just one address). 10334 // Vectors may be partly split to registers and partly to the stack, in 10335 // which case the base address is partly offset and subsequent stores are 10336 // relative to that. 10337 unsigned ArgIndex = Outs[i].OrigArgIndex; 10338 unsigned ArgPartOffset = Outs[i].PartOffset; 10339 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10340 // Calculate the total size to store. We don't have access to what we're 10341 // actually storing other than performing the loop and collecting the 10342 // info. 10343 SmallVector<std::pair<SDValue, SDValue>> Parts; 10344 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10345 SDValue PartValue = OutVals[i + 1]; 10346 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10347 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10348 EVT PartVT = PartValue.getValueType(); 10349 if (PartVT.isScalableVector()) 10350 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10351 StoredSize += PartVT.getStoreSize(); 10352 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10353 Parts.push_back(std::make_pair(PartValue, Offset)); 10354 ++i; 10355 } 10356 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10357 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10358 MemOpChains.push_back( 10359 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10360 MachinePointerInfo::getFixedStack(MF, FI))); 10361 for (const auto &Part : Parts) { 10362 SDValue PartValue = Part.first; 10363 SDValue PartOffset = Part.second; 10364 SDValue Address = 10365 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10366 MemOpChains.push_back( 10367 DAG.getStore(Chain, DL, PartValue, Address, 10368 MachinePointerInfo::getFixedStack(MF, FI))); 10369 } 10370 ArgValue = SpillSlot; 10371 } else { 10372 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10373 } 10374 10375 // Use local copy if it is a byval arg. 10376 if (Flags.isByVal()) 10377 ArgValue = ByValArgs[j++]; 10378 10379 if (VA.isRegLoc()) { 10380 // Queue up the argument copies and emit them at the end. 10381 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10382 } else { 10383 assert(VA.isMemLoc() && "Argument not register or memory"); 10384 assert(!IsTailCall && "Tail call not allowed if stack is used " 10385 "for passing parameters"); 10386 10387 // Work out the address of the stack slot. 10388 if (!StackPtr.getNode()) 10389 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10390 SDValue Address = 10391 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10392 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10393 10394 // Emit the store. 10395 MemOpChains.push_back( 10396 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10397 } 10398 } 10399 10400 // Join the stores, which are independent of one another. 10401 if (!MemOpChains.empty()) 10402 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10403 10404 SDValue Glue; 10405 10406 // Build a sequence of copy-to-reg nodes, chained and glued together. 10407 for (auto &Reg : RegsToPass) { 10408 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10409 Glue = Chain.getValue(1); 10410 } 10411 10412 // Validate that none of the argument registers have been marked as 10413 // reserved, if so report an error. Do the same for the return address if this 10414 // is not a tailcall. 10415 validateCCReservedRegs(RegsToPass, MF); 10416 if (!IsTailCall && 10417 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10418 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10419 MF.getFunction(), 10420 "Return address register required, but has been reserved."}); 10421 10422 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10423 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10424 // split it and then direct call can be matched by PseudoCALL. 10425 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10426 const GlobalValue *GV = S->getGlobal(); 10427 10428 unsigned OpFlags = RISCVII::MO_CALL; 10429 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10430 OpFlags = RISCVII::MO_PLT; 10431 10432 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10433 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10434 unsigned OpFlags = RISCVII::MO_CALL; 10435 10436 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10437 nullptr)) 10438 OpFlags = RISCVII::MO_PLT; 10439 10440 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10441 } 10442 10443 // The first call operand is the chain and the second is the target address. 10444 SmallVector<SDValue, 8> Ops; 10445 Ops.push_back(Chain); 10446 Ops.push_back(Callee); 10447 10448 // Add argument registers to the end of the list so that they are 10449 // known live into the call. 10450 for (auto &Reg : RegsToPass) 10451 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10452 10453 if (!IsTailCall) { 10454 // Add a register mask operand representing the call-preserved registers. 10455 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10456 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10457 assert(Mask && "Missing call preserved mask for calling convention"); 10458 Ops.push_back(DAG.getRegisterMask(Mask)); 10459 } 10460 10461 // Glue the call to the argument copies, if any. 10462 if (Glue.getNode()) 10463 Ops.push_back(Glue); 10464 10465 // Emit the call. 10466 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10467 10468 if (IsTailCall) { 10469 MF.getFrameInfo().setHasTailCall(); 10470 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10471 } 10472 10473 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10474 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10475 Glue = Chain.getValue(1); 10476 10477 // Mark the end of the call, which is glued to the call itself. 10478 Chain = DAG.getCALLSEQ_END(Chain, 10479 DAG.getConstant(NumBytes, DL, PtrVT, true), 10480 DAG.getConstant(0, DL, PtrVT, true), 10481 Glue, DL); 10482 Glue = Chain.getValue(1); 10483 10484 // Assign locations to each value returned by this call. 10485 SmallVector<CCValAssign, 16> RVLocs; 10486 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10487 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10488 10489 // Copy all of the result registers out of their specified physreg. 10490 for (auto &VA : RVLocs) { 10491 // Copy the value out 10492 SDValue RetValue = 10493 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10494 // Glue the RetValue to the end of the call sequence 10495 Chain = RetValue.getValue(1); 10496 Glue = RetValue.getValue(2); 10497 10498 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10499 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10500 SDValue RetValue2 = 10501 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10502 Chain = RetValue2.getValue(1); 10503 Glue = RetValue2.getValue(2); 10504 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10505 RetValue2); 10506 } 10507 10508 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10509 10510 InVals.push_back(RetValue); 10511 } 10512 10513 return Chain; 10514 } 10515 10516 bool RISCVTargetLowering::CanLowerReturn( 10517 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10518 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10519 SmallVector<CCValAssign, 16> RVLocs; 10520 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10521 10522 Optional<unsigned> FirstMaskArgument; 10523 if (Subtarget.hasVInstructions()) 10524 FirstMaskArgument = preAssignMask(Outs); 10525 10526 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10527 MVT VT = Outs[i].VT; 10528 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10529 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10530 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10531 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10532 *this, FirstMaskArgument)) 10533 return false; 10534 } 10535 return true; 10536 } 10537 10538 SDValue 10539 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10540 bool IsVarArg, 10541 const SmallVectorImpl<ISD::OutputArg> &Outs, 10542 const SmallVectorImpl<SDValue> &OutVals, 10543 const SDLoc &DL, SelectionDAG &DAG) const { 10544 const MachineFunction &MF = DAG.getMachineFunction(); 10545 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10546 10547 // Stores the assignment of the return value to a location. 10548 SmallVector<CCValAssign, 16> RVLocs; 10549 10550 // Info about the registers and stack slot. 10551 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10552 *DAG.getContext()); 10553 10554 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10555 nullptr, CC_RISCV); 10556 10557 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10558 report_fatal_error("GHC functions return void only"); 10559 10560 SDValue Glue; 10561 SmallVector<SDValue, 4> RetOps(1, Chain); 10562 10563 // Copy the result values into the output registers. 10564 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10565 SDValue Val = OutVals[i]; 10566 CCValAssign &VA = RVLocs[i]; 10567 assert(VA.isRegLoc() && "Can only return in registers!"); 10568 10569 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10570 // Handle returning f64 on RV32D with a soft float ABI. 10571 assert(VA.isRegLoc() && "Expected return via registers"); 10572 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10573 DAG.getVTList(MVT::i32, MVT::i32), Val); 10574 SDValue Lo = SplitF64.getValue(0); 10575 SDValue Hi = SplitF64.getValue(1); 10576 Register RegLo = VA.getLocReg(); 10577 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10578 Register RegHi = RegLo + 1; 10579 10580 if (STI.isRegisterReservedByUser(RegLo) || 10581 STI.isRegisterReservedByUser(RegHi)) 10582 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10583 MF.getFunction(), 10584 "Return value register required, but has been reserved."}); 10585 10586 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10587 Glue = Chain.getValue(1); 10588 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10589 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10590 Glue = Chain.getValue(1); 10591 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10592 } else { 10593 // Handle a 'normal' return. 10594 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10595 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10596 10597 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10598 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10599 MF.getFunction(), 10600 "Return value register required, but has been reserved."}); 10601 10602 // Guarantee that all emitted copies are stuck together. 10603 Glue = Chain.getValue(1); 10604 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10605 } 10606 } 10607 10608 RetOps[0] = Chain; // Update chain. 10609 10610 // Add the glue node if we have it. 10611 if (Glue.getNode()) { 10612 RetOps.push_back(Glue); 10613 } 10614 10615 unsigned RetOpc = RISCVISD::RET_FLAG; 10616 // Interrupt service routines use different return instructions. 10617 const Function &Func = DAG.getMachineFunction().getFunction(); 10618 if (Func.hasFnAttribute("interrupt")) { 10619 if (!Func.getReturnType()->isVoidTy()) 10620 report_fatal_error( 10621 "Functions with the interrupt attribute must have void return type!"); 10622 10623 MachineFunction &MF = DAG.getMachineFunction(); 10624 StringRef Kind = 10625 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10626 10627 if (Kind == "user") 10628 RetOpc = RISCVISD::URET_FLAG; 10629 else if (Kind == "supervisor") 10630 RetOpc = RISCVISD::SRET_FLAG; 10631 else 10632 RetOpc = RISCVISD::MRET_FLAG; 10633 } 10634 10635 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10636 } 10637 10638 void RISCVTargetLowering::validateCCReservedRegs( 10639 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10640 MachineFunction &MF) const { 10641 const Function &F = MF.getFunction(); 10642 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10643 10644 if (llvm::any_of(Regs, [&STI](auto Reg) { 10645 return STI.isRegisterReservedByUser(Reg.first); 10646 })) 10647 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10648 F, "Argument register required, but has been reserved."}); 10649 } 10650 10651 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10652 return CI->isTailCall(); 10653 } 10654 10655 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10656 #define NODE_NAME_CASE(NODE) \ 10657 case RISCVISD::NODE: \ 10658 return "RISCVISD::" #NODE; 10659 // clang-format off 10660 switch ((RISCVISD::NodeType)Opcode) { 10661 case RISCVISD::FIRST_NUMBER: 10662 break; 10663 NODE_NAME_CASE(RET_FLAG) 10664 NODE_NAME_CASE(URET_FLAG) 10665 NODE_NAME_CASE(SRET_FLAG) 10666 NODE_NAME_CASE(MRET_FLAG) 10667 NODE_NAME_CASE(CALL) 10668 NODE_NAME_CASE(SELECT_CC) 10669 NODE_NAME_CASE(BR_CC) 10670 NODE_NAME_CASE(BuildPairF64) 10671 NODE_NAME_CASE(SplitF64) 10672 NODE_NAME_CASE(TAIL) 10673 NODE_NAME_CASE(MULHSU) 10674 NODE_NAME_CASE(SLLW) 10675 NODE_NAME_CASE(SRAW) 10676 NODE_NAME_CASE(SRLW) 10677 NODE_NAME_CASE(DIVW) 10678 NODE_NAME_CASE(DIVUW) 10679 NODE_NAME_CASE(REMUW) 10680 NODE_NAME_CASE(ROLW) 10681 NODE_NAME_CASE(RORW) 10682 NODE_NAME_CASE(CLZW) 10683 NODE_NAME_CASE(CTZW) 10684 NODE_NAME_CASE(FSLW) 10685 NODE_NAME_CASE(FSRW) 10686 NODE_NAME_CASE(FSL) 10687 NODE_NAME_CASE(FSR) 10688 NODE_NAME_CASE(FMV_H_X) 10689 NODE_NAME_CASE(FMV_X_ANYEXTH) 10690 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10691 NODE_NAME_CASE(FMV_W_X_RV64) 10692 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10693 NODE_NAME_CASE(FCVT_X) 10694 NODE_NAME_CASE(FCVT_XU) 10695 NODE_NAME_CASE(FCVT_W_RV64) 10696 NODE_NAME_CASE(FCVT_WU_RV64) 10697 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10698 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10699 NODE_NAME_CASE(READ_CYCLE_WIDE) 10700 NODE_NAME_CASE(GREV) 10701 NODE_NAME_CASE(GREVW) 10702 NODE_NAME_CASE(GORC) 10703 NODE_NAME_CASE(GORCW) 10704 NODE_NAME_CASE(SHFL) 10705 NODE_NAME_CASE(SHFLW) 10706 NODE_NAME_CASE(UNSHFL) 10707 NODE_NAME_CASE(UNSHFLW) 10708 NODE_NAME_CASE(BFP) 10709 NODE_NAME_CASE(BFPW) 10710 NODE_NAME_CASE(BCOMPRESS) 10711 NODE_NAME_CASE(BCOMPRESSW) 10712 NODE_NAME_CASE(BDECOMPRESS) 10713 NODE_NAME_CASE(BDECOMPRESSW) 10714 NODE_NAME_CASE(VMV_V_X_VL) 10715 NODE_NAME_CASE(VFMV_V_F_VL) 10716 NODE_NAME_CASE(VMV_X_S) 10717 NODE_NAME_CASE(VMV_S_X_VL) 10718 NODE_NAME_CASE(VFMV_S_F_VL) 10719 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10720 NODE_NAME_CASE(READ_VLENB) 10721 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10722 NODE_NAME_CASE(VSLIDEUP_VL) 10723 NODE_NAME_CASE(VSLIDE1UP_VL) 10724 NODE_NAME_CASE(VSLIDEDOWN_VL) 10725 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10726 NODE_NAME_CASE(VID_VL) 10727 NODE_NAME_CASE(VFNCVT_ROD_VL) 10728 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10729 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10730 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10731 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10732 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10733 NODE_NAME_CASE(VECREDUCE_AND_VL) 10734 NODE_NAME_CASE(VECREDUCE_OR_VL) 10735 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10736 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10737 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10738 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10739 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10740 NODE_NAME_CASE(ADD_VL) 10741 NODE_NAME_CASE(AND_VL) 10742 NODE_NAME_CASE(MUL_VL) 10743 NODE_NAME_CASE(OR_VL) 10744 NODE_NAME_CASE(SDIV_VL) 10745 NODE_NAME_CASE(SHL_VL) 10746 NODE_NAME_CASE(SREM_VL) 10747 NODE_NAME_CASE(SRA_VL) 10748 NODE_NAME_CASE(SRL_VL) 10749 NODE_NAME_CASE(SUB_VL) 10750 NODE_NAME_CASE(UDIV_VL) 10751 NODE_NAME_CASE(UREM_VL) 10752 NODE_NAME_CASE(XOR_VL) 10753 NODE_NAME_CASE(SADDSAT_VL) 10754 NODE_NAME_CASE(UADDSAT_VL) 10755 NODE_NAME_CASE(SSUBSAT_VL) 10756 NODE_NAME_CASE(USUBSAT_VL) 10757 NODE_NAME_CASE(FADD_VL) 10758 NODE_NAME_CASE(FSUB_VL) 10759 NODE_NAME_CASE(FMUL_VL) 10760 NODE_NAME_CASE(FDIV_VL) 10761 NODE_NAME_CASE(FNEG_VL) 10762 NODE_NAME_CASE(FABS_VL) 10763 NODE_NAME_CASE(FSQRT_VL) 10764 NODE_NAME_CASE(FMA_VL) 10765 NODE_NAME_CASE(FCOPYSIGN_VL) 10766 NODE_NAME_CASE(SMIN_VL) 10767 NODE_NAME_CASE(SMAX_VL) 10768 NODE_NAME_CASE(UMIN_VL) 10769 NODE_NAME_CASE(UMAX_VL) 10770 NODE_NAME_CASE(FMINNUM_VL) 10771 NODE_NAME_CASE(FMAXNUM_VL) 10772 NODE_NAME_CASE(MULHS_VL) 10773 NODE_NAME_CASE(MULHU_VL) 10774 NODE_NAME_CASE(FP_TO_SINT_VL) 10775 NODE_NAME_CASE(FP_TO_UINT_VL) 10776 NODE_NAME_CASE(SINT_TO_FP_VL) 10777 NODE_NAME_CASE(UINT_TO_FP_VL) 10778 NODE_NAME_CASE(FP_EXTEND_VL) 10779 NODE_NAME_CASE(FP_ROUND_VL) 10780 NODE_NAME_CASE(VWMUL_VL) 10781 NODE_NAME_CASE(VWMULU_VL) 10782 NODE_NAME_CASE(VWMULSU_VL) 10783 NODE_NAME_CASE(VWADD_VL) 10784 NODE_NAME_CASE(VWADDU_VL) 10785 NODE_NAME_CASE(VWSUB_VL) 10786 NODE_NAME_CASE(VWSUBU_VL) 10787 NODE_NAME_CASE(VWADD_W_VL) 10788 NODE_NAME_CASE(VWADDU_W_VL) 10789 NODE_NAME_CASE(VWSUB_W_VL) 10790 NODE_NAME_CASE(VWSUBU_W_VL) 10791 NODE_NAME_CASE(SETCC_VL) 10792 NODE_NAME_CASE(VSELECT_VL) 10793 NODE_NAME_CASE(VP_MERGE_VL) 10794 NODE_NAME_CASE(VMAND_VL) 10795 NODE_NAME_CASE(VMOR_VL) 10796 NODE_NAME_CASE(VMXOR_VL) 10797 NODE_NAME_CASE(VMCLR_VL) 10798 NODE_NAME_CASE(VMSET_VL) 10799 NODE_NAME_CASE(VRGATHER_VX_VL) 10800 NODE_NAME_CASE(VRGATHER_VV_VL) 10801 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10802 NODE_NAME_CASE(VSEXT_VL) 10803 NODE_NAME_CASE(VZEXT_VL) 10804 NODE_NAME_CASE(VCPOP_VL) 10805 NODE_NAME_CASE(VLE_VL) 10806 NODE_NAME_CASE(VSE_VL) 10807 NODE_NAME_CASE(READ_CSR) 10808 NODE_NAME_CASE(WRITE_CSR) 10809 NODE_NAME_CASE(SWAP_CSR) 10810 } 10811 // clang-format on 10812 return nullptr; 10813 #undef NODE_NAME_CASE 10814 } 10815 10816 /// getConstraintType - Given a constraint letter, return the type of 10817 /// constraint it is for this target. 10818 RISCVTargetLowering::ConstraintType 10819 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10820 if (Constraint.size() == 1) { 10821 switch (Constraint[0]) { 10822 default: 10823 break; 10824 case 'f': 10825 return C_RegisterClass; 10826 case 'I': 10827 case 'J': 10828 case 'K': 10829 return C_Immediate; 10830 case 'A': 10831 return C_Memory; 10832 case 'S': // A symbolic address 10833 return C_Other; 10834 } 10835 } else { 10836 if (Constraint == "vr" || Constraint == "vm") 10837 return C_RegisterClass; 10838 } 10839 return TargetLowering::getConstraintType(Constraint); 10840 } 10841 10842 std::pair<unsigned, const TargetRegisterClass *> 10843 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10844 StringRef Constraint, 10845 MVT VT) const { 10846 // First, see if this is a constraint that directly corresponds to a 10847 // RISCV register class. 10848 if (Constraint.size() == 1) { 10849 switch (Constraint[0]) { 10850 case 'r': 10851 // TODO: Support fixed vectors up to XLen for P extension? 10852 if (VT.isVector()) 10853 break; 10854 return std::make_pair(0U, &RISCV::GPRRegClass); 10855 case 'f': 10856 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10857 return std::make_pair(0U, &RISCV::FPR16RegClass); 10858 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10859 return std::make_pair(0U, &RISCV::FPR32RegClass); 10860 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10861 return std::make_pair(0U, &RISCV::FPR64RegClass); 10862 break; 10863 default: 10864 break; 10865 } 10866 } else if (Constraint == "vr") { 10867 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10868 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10869 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10870 return std::make_pair(0U, RC); 10871 } 10872 } else if (Constraint == "vm") { 10873 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10874 return std::make_pair(0U, &RISCV::VMV0RegClass); 10875 } 10876 10877 // Clang will correctly decode the usage of register name aliases into their 10878 // official names. However, other frontends like `rustc` do not. This allows 10879 // users of these frontends to use the ABI names for registers in LLVM-style 10880 // register constraints. 10881 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10882 .Case("{zero}", RISCV::X0) 10883 .Case("{ra}", RISCV::X1) 10884 .Case("{sp}", RISCV::X2) 10885 .Case("{gp}", RISCV::X3) 10886 .Case("{tp}", RISCV::X4) 10887 .Case("{t0}", RISCV::X5) 10888 .Case("{t1}", RISCV::X6) 10889 .Case("{t2}", RISCV::X7) 10890 .Cases("{s0}", "{fp}", RISCV::X8) 10891 .Case("{s1}", RISCV::X9) 10892 .Case("{a0}", RISCV::X10) 10893 .Case("{a1}", RISCV::X11) 10894 .Case("{a2}", RISCV::X12) 10895 .Case("{a3}", RISCV::X13) 10896 .Case("{a4}", RISCV::X14) 10897 .Case("{a5}", RISCV::X15) 10898 .Case("{a6}", RISCV::X16) 10899 .Case("{a7}", RISCV::X17) 10900 .Case("{s2}", RISCV::X18) 10901 .Case("{s3}", RISCV::X19) 10902 .Case("{s4}", RISCV::X20) 10903 .Case("{s5}", RISCV::X21) 10904 .Case("{s6}", RISCV::X22) 10905 .Case("{s7}", RISCV::X23) 10906 .Case("{s8}", RISCV::X24) 10907 .Case("{s9}", RISCV::X25) 10908 .Case("{s10}", RISCV::X26) 10909 .Case("{s11}", RISCV::X27) 10910 .Case("{t3}", RISCV::X28) 10911 .Case("{t4}", RISCV::X29) 10912 .Case("{t5}", RISCV::X30) 10913 .Case("{t6}", RISCV::X31) 10914 .Default(RISCV::NoRegister); 10915 if (XRegFromAlias != RISCV::NoRegister) 10916 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10917 10918 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10919 // TableGen record rather than the AsmName to choose registers for InlineAsm 10920 // constraints, plus we want to match those names to the widest floating point 10921 // register type available, manually select floating point registers here. 10922 // 10923 // The second case is the ABI name of the register, so that frontends can also 10924 // use the ABI names in register constraint lists. 10925 if (Subtarget.hasStdExtF()) { 10926 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10927 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10928 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10929 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10930 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10931 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10932 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10933 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10934 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10935 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10936 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10937 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10938 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10939 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10940 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10941 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10942 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10943 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10944 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10945 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10946 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10947 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10948 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10949 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10950 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10951 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10952 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10953 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10954 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10955 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10956 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10957 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10958 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10959 .Default(RISCV::NoRegister); 10960 if (FReg != RISCV::NoRegister) { 10961 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10962 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10963 unsigned RegNo = FReg - RISCV::F0_F; 10964 unsigned DReg = RISCV::F0_D + RegNo; 10965 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10966 } 10967 if (VT == MVT::f32 || VT == MVT::Other) 10968 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10969 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10970 unsigned RegNo = FReg - RISCV::F0_F; 10971 unsigned HReg = RISCV::F0_H + RegNo; 10972 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10973 } 10974 } 10975 } 10976 10977 if (Subtarget.hasVInstructions()) { 10978 Register VReg = StringSwitch<Register>(Constraint.lower()) 10979 .Case("{v0}", RISCV::V0) 10980 .Case("{v1}", RISCV::V1) 10981 .Case("{v2}", RISCV::V2) 10982 .Case("{v3}", RISCV::V3) 10983 .Case("{v4}", RISCV::V4) 10984 .Case("{v5}", RISCV::V5) 10985 .Case("{v6}", RISCV::V6) 10986 .Case("{v7}", RISCV::V7) 10987 .Case("{v8}", RISCV::V8) 10988 .Case("{v9}", RISCV::V9) 10989 .Case("{v10}", RISCV::V10) 10990 .Case("{v11}", RISCV::V11) 10991 .Case("{v12}", RISCV::V12) 10992 .Case("{v13}", RISCV::V13) 10993 .Case("{v14}", RISCV::V14) 10994 .Case("{v15}", RISCV::V15) 10995 .Case("{v16}", RISCV::V16) 10996 .Case("{v17}", RISCV::V17) 10997 .Case("{v18}", RISCV::V18) 10998 .Case("{v19}", RISCV::V19) 10999 .Case("{v20}", RISCV::V20) 11000 .Case("{v21}", RISCV::V21) 11001 .Case("{v22}", RISCV::V22) 11002 .Case("{v23}", RISCV::V23) 11003 .Case("{v24}", RISCV::V24) 11004 .Case("{v25}", RISCV::V25) 11005 .Case("{v26}", RISCV::V26) 11006 .Case("{v27}", RISCV::V27) 11007 .Case("{v28}", RISCV::V28) 11008 .Case("{v29}", RISCV::V29) 11009 .Case("{v30}", RISCV::V30) 11010 .Case("{v31}", RISCV::V31) 11011 .Default(RISCV::NoRegister); 11012 if (VReg != RISCV::NoRegister) { 11013 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11014 return std::make_pair(VReg, &RISCV::VMRegClass); 11015 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11016 return std::make_pair(VReg, &RISCV::VRRegClass); 11017 for (const auto *RC : 11018 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11019 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11020 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11021 return std::make_pair(VReg, RC); 11022 } 11023 } 11024 } 11025 } 11026 11027 std::pair<Register, const TargetRegisterClass *> Res = 11028 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11029 11030 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11031 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11032 // Subtarget into account. 11033 if (Res.second == &RISCV::GPRF16RegClass || 11034 Res.second == &RISCV::GPRF32RegClass || 11035 Res.second == &RISCV::GPRF64RegClass) 11036 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11037 11038 return Res; 11039 } 11040 11041 unsigned 11042 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11043 // Currently only support length 1 constraints. 11044 if (ConstraintCode.size() == 1) { 11045 switch (ConstraintCode[0]) { 11046 case 'A': 11047 return InlineAsm::Constraint_A; 11048 default: 11049 break; 11050 } 11051 } 11052 11053 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11054 } 11055 11056 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11057 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11058 SelectionDAG &DAG) const { 11059 // Currently only support length 1 constraints. 11060 if (Constraint.length() == 1) { 11061 switch (Constraint[0]) { 11062 case 'I': 11063 // Validate & create a 12-bit signed immediate operand. 11064 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11065 uint64_t CVal = C->getSExtValue(); 11066 if (isInt<12>(CVal)) 11067 Ops.push_back( 11068 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11069 } 11070 return; 11071 case 'J': 11072 // Validate & create an integer zero operand. 11073 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11074 if (C->getZExtValue() == 0) 11075 Ops.push_back( 11076 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11077 return; 11078 case 'K': 11079 // Validate & create a 5-bit unsigned immediate operand. 11080 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11081 uint64_t CVal = C->getZExtValue(); 11082 if (isUInt<5>(CVal)) 11083 Ops.push_back( 11084 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11085 } 11086 return; 11087 case 'S': 11088 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11089 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11090 GA->getValueType(0))); 11091 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11092 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11093 BA->getValueType(0))); 11094 } 11095 return; 11096 default: 11097 break; 11098 } 11099 } 11100 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11101 } 11102 11103 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11104 Instruction *Inst, 11105 AtomicOrdering Ord) const { 11106 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11107 return Builder.CreateFence(Ord); 11108 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11109 return Builder.CreateFence(AtomicOrdering::Release); 11110 return nullptr; 11111 } 11112 11113 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11114 Instruction *Inst, 11115 AtomicOrdering Ord) const { 11116 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11117 return Builder.CreateFence(AtomicOrdering::Acquire); 11118 return nullptr; 11119 } 11120 11121 TargetLowering::AtomicExpansionKind 11122 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11123 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11124 // point operations can't be used in an lr/sc sequence without breaking the 11125 // forward-progress guarantee. 11126 if (AI->isFloatingPointOperation()) 11127 return AtomicExpansionKind::CmpXChg; 11128 11129 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11130 if (Size == 8 || Size == 16) 11131 return AtomicExpansionKind::MaskedIntrinsic; 11132 return AtomicExpansionKind::None; 11133 } 11134 11135 static Intrinsic::ID 11136 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11137 if (XLen == 32) { 11138 switch (BinOp) { 11139 default: 11140 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11141 case AtomicRMWInst::Xchg: 11142 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11143 case AtomicRMWInst::Add: 11144 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11145 case AtomicRMWInst::Sub: 11146 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11147 case AtomicRMWInst::Nand: 11148 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11149 case AtomicRMWInst::Max: 11150 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11151 case AtomicRMWInst::Min: 11152 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11153 case AtomicRMWInst::UMax: 11154 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11155 case AtomicRMWInst::UMin: 11156 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11157 } 11158 } 11159 11160 if (XLen == 64) { 11161 switch (BinOp) { 11162 default: 11163 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11164 case AtomicRMWInst::Xchg: 11165 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11166 case AtomicRMWInst::Add: 11167 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11168 case AtomicRMWInst::Sub: 11169 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11170 case AtomicRMWInst::Nand: 11171 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11172 case AtomicRMWInst::Max: 11173 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11174 case AtomicRMWInst::Min: 11175 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11176 case AtomicRMWInst::UMax: 11177 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11178 case AtomicRMWInst::UMin: 11179 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11180 } 11181 } 11182 11183 llvm_unreachable("Unexpected XLen\n"); 11184 } 11185 11186 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11187 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11188 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11189 unsigned XLen = Subtarget.getXLen(); 11190 Value *Ordering = 11191 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11192 Type *Tys[] = {AlignedAddr->getType()}; 11193 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11194 AI->getModule(), 11195 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11196 11197 if (XLen == 64) { 11198 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11199 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11200 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11201 } 11202 11203 Value *Result; 11204 11205 // Must pass the shift amount needed to sign extend the loaded value prior 11206 // to performing a signed comparison for min/max. ShiftAmt is the number of 11207 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11208 // is the number of bits to left+right shift the value in order to 11209 // sign-extend. 11210 if (AI->getOperation() == AtomicRMWInst::Min || 11211 AI->getOperation() == AtomicRMWInst::Max) { 11212 const DataLayout &DL = AI->getModule()->getDataLayout(); 11213 unsigned ValWidth = 11214 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11215 Value *SextShamt = 11216 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11217 Result = Builder.CreateCall(LrwOpScwLoop, 11218 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11219 } else { 11220 Result = 11221 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11222 } 11223 11224 if (XLen == 64) 11225 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11226 return Result; 11227 } 11228 11229 TargetLowering::AtomicExpansionKind 11230 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11231 AtomicCmpXchgInst *CI) const { 11232 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11233 if (Size == 8 || Size == 16) 11234 return AtomicExpansionKind::MaskedIntrinsic; 11235 return AtomicExpansionKind::None; 11236 } 11237 11238 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11239 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11240 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11241 unsigned XLen = Subtarget.getXLen(); 11242 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11243 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11244 if (XLen == 64) { 11245 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11246 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11247 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11248 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11249 } 11250 Type *Tys[] = {AlignedAddr->getType()}; 11251 Function *MaskedCmpXchg = 11252 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11253 Value *Result = Builder.CreateCall( 11254 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11255 if (XLen == 64) 11256 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11257 return Result; 11258 } 11259 11260 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11261 return false; 11262 } 11263 11264 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11265 EVT VT) const { 11266 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11267 return false; 11268 11269 switch (FPVT.getSimpleVT().SimpleTy) { 11270 case MVT::f16: 11271 return Subtarget.hasStdExtZfh(); 11272 case MVT::f32: 11273 return Subtarget.hasStdExtF(); 11274 case MVT::f64: 11275 return Subtarget.hasStdExtD(); 11276 default: 11277 return false; 11278 } 11279 } 11280 11281 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11282 // If we are using the small code model, we can reduce size of jump table 11283 // entry to 4 bytes. 11284 if (Subtarget.is64Bit() && !isPositionIndependent() && 11285 getTargetMachine().getCodeModel() == CodeModel::Small) { 11286 return MachineJumpTableInfo::EK_Custom32; 11287 } 11288 return TargetLowering::getJumpTableEncoding(); 11289 } 11290 11291 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11292 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11293 unsigned uid, MCContext &Ctx) const { 11294 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11295 getTargetMachine().getCodeModel() == CodeModel::Small); 11296 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11297 } 11298 11299 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11300 EVT VT) const { 11301 VT = VT.getScalarType(); 11302 11303 if (!VT.isSimple()) 11304 return false; 11305 11306 switch (VT.getSimpleVT().SimpleTy) { 11307 case MVT::f16: 11308 return Subtarget.hasStdExtZfh(); 11309 case MVT::f32: 11310 return Subtarget.hasStdExtF(); 11311 case MVT::f64: 11312 return Subtarget.hasStdExtD(); 11313 default: 11314 break; 11315 } 11316 11317 return false; 11318 } 11319 11320 Register RISCVTargetLowering::getExceptionPointerRegister( 11321 const Constant *PersonalityFn) const { 11322 return RISCV::X10; 11323 } 11324 11325 Register RISCVTargetLowering::getExceptionSelectorRegister( 11326 const Constant *PersonalityFn) const { 11327 return RISCV::X11; 11328 } 11329 11330 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11331 // Return false to suppress the unnecessary extensions if the LibCall 11332 // arguments or return value is f32 type for LP64 ABI. 11333 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11334 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11335 return false; 11336 11337 return true; 11338 } 11339 11340 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11341 if (Subtarget.is64Bit() && Type == MVT::i32) 11342 return true; 11343 11344 return IsSigned; 11345 } 11346 11347 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11348 SDValue C) const { 11349 // Check integral scalar types. 11350 if (VT.isScalarInteger()) { 11351 // Omit the optimization if the sub target has the M extension and the data 11352 // size exceeds XLen. 11353 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11354 return false; 11355 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11356 // Break the MUL to a SLLI and an ADD/SUB. 11357 const APInt &Imm = ConstNode->getAPIntValue(); 11358 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11359 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11360 return true; 11361 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11362 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11363 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11364 (Imm - 8).isPowerOf2())) 11365 return true; 11366 // Omit the following optimization if the sub target has the M extension 11367 // and the data size >= XLen. 11368 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11369 return false; 11370 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11371 // a pair of LUI/ADDI. 11372 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11373 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11374 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11375 (1 - ImmS).isPowerOf2()) 11376 return true; 11377 } 11378 } 11379 } 11380 11381 return false; 11382 } 11383 11384 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11385 SDValue ConstNode) const { 11386 // Let the DAGCombiner decide for vectors. 11387 EVT VT = AddNode.getValueType(); 11388 if (VT.isVector()) 11389 return true; 11390 11391 // Let the DAGCombiner decide for larger types. 11392 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11393 return true; 11394 11395 // It is worse if c1 is simm12 while c1*c2 is not. 11396 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11397 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11398 const APInt &C1 = C1Node->getAPIntValue(); 11399 const APInt &C2 = C2Node->getAPIntValue(); 11400 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11401 return false; 11402 11403 // Default to true and let the DAGCombiner decide. 11404 return true; 11405 } 11406 11407 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11408 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11409 bool *Fast) const { 11410 if (!VT.isVector()) 11411 return false; 11412 11413 EVT ElemVT = VT.getVectorElementType(); 11414 if (Alignment >= ElemVT.getStoreSize()) { 11415 if (Fast) 11416 *Fast = true; 11417 return true; 11418 } 11419 11420 return false; 11421 } 11422 11423 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11424 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11425 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11426 bool IsABIRegCopy = CC.hasValue(); 11427 EVT ValueVT = Val.getValueType(); 11428 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11429 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11430 // and cast to f32. 11431 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11432 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11433 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11434 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11435 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11436 Parts[0] = Val; 11437 return true; 11438 } 11439 11440 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11441 LLVMContext &Context = *DAG.getContext(); 11442 EVT ValueEltVT = ValueVT.getVectorElementType(); 11443 EVT PartEltVT = PartVT.getVectorElementType(); 11444 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11445 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11446 if (PartVTBitSize % ValueVTBitSize == 0) { 11447 assert(PartVTBitSize >= ValueVTBitSize); 11448 // If the element types are different, bitcast to the same element type of 11449 // PartVT first. 11450 // Give an example here, we want copy a <vscale x 1 x i8> value to 11451 // <vscale x 4 x i16>. 11452 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11453 // subvector, then we can bitcast to <vscale x 4 x i16>. 11454 if (ValueEltVT != PartEltVT) { 11455 if (PartVTBitSize > ValueVTBitSize) { 11456 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11457 assert(Count != 0 && "The number of element should not be zero."); 11458 EVT SameEltTypeVT = 11459 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11460 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11461 DAG.getUNDEF(SameEltTypeVT), Val, 11462 DAG.getVectorIdxConstant(0, DL)); 11463 } 11464 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11465 } else { 11466 Val = 11467 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11468 Val, DAG.getVectorIdxConstant(0, DL)); 11469 } 11470 Parts[0] = Val; 11471 return true; 11472 } 11473 } 11474 return false; 11475 } 11476 11477 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11478 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11479 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11480 bool IsABIRegCopy = CC.hasValue(); 11481 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11482 SDValue Val = Parts[0]; 11483 11484 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11485 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11486 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11487 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11488 return Val; 11489 } 11490 11491 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11492 LLVMContext &Context = *DAG.getContext(); 11493 SDValue Val = Parts[0]; 11494 EVT ValueEltVT = ValueVT.getVectorElementType(); 11495 EVT PartEltVT = PartVT.getVectorElementType(); 11496 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11497 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11498 if (PartVTBitSize % ValueVTBitSize == 0) { 11499 assert(PartVTBitSize >= ValueVTBitSize); 11500 EVT SameEltTypeVT = ValueVT; 11501 // If the element types are different, convert it to the same element type 11502 // of PartVT. 11503 // Give an example here, we want copy a <vscale x 1 x i8> value from 11504 // <vscale x 4 x i16>. 11505 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11506 // then we can extract <vscale x 1 x i8>. 11507 if (ValueEltVT != PartEltVT) { 11508 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11509 assert(Count != 0 && "The number of element should not be zero."); 11510 SameEltTypeVT = 11511 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11512 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11513 } 11514 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11515 DAG.getVectorIdxConstant(0, DL)); 11516 return Val; 11517 } 11518 } 11519 return SDValue(); 11520 } 11521 11522 SDValue 11523 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11524 SelectionDAG &DAG, 11525 SmallVectorImpl<SDNode *> &Created) const { 11526 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11527 if (isIntDivCheap(N->getValueType(0), Attr)) 11528 return SDValue(N, 0); // Lower SDIV as SDIV 11529 11530 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11531 "Unexpected divisor!"); 11532 11533 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11534 if (!Subtarget.hasStdExtZbt()) 11535 return SDValue(); 11536 11537 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11538 // Besides, more critical path instructions will be generated when dividing 11539 // by 2. So we keep using the original DAGs for these cases. 11540 unsigned Lg2 = Divisor.countTrailingZeros(); 11541 if (Lg2 == 1 || Lg2 >= 12) 11542 return SDValue(); 11543 11544 // fold (sdiv X, pow2) 11545 EVT VT = N->getValueType(0); 11546 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11547 return SDValue(); 11548 11549 SDLoc DL(N); 11550 SDValue N0 = N->getOperand(0); 11551 SDValue Zero = DAG.getConstant(0, DL, VT); 11552 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11553 11554 // Add (N0 < 0) ? Pow2 - 1 : 0; 11555 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11556 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11557 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11558 11559 Created.push_back(Cmp.getNode()); 11560 Created.push_back(Add.getNode()); 11561 Created.push_back(Sel.getNode()); 11562 11563 // Divide by pow2. 11564 SDValue SRA = 11565 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11566 11567 // If we're dividing by a positive value, we're done. Otherwise, we must 11568 // negate the result. 11569 if (Divisor.isNonNegative()) 11570 return SRA; 11571 11572 Created.push_back(SRA.getNode()); 11573 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11574 } 11575 11576 #define GET_REGISTER_MATCHER 11577 #include "RISCVGenAsmMatcher.inc" 11578 11579 Register 11580 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11581 const MachineFunction &MF) const { 11582 Register Reg = MatchRegisterAltName(RegName); 11583 if (Reg == RISCV::NoRegister) 11584 Reg = MatchRegisterName(RegName); 11585 if (Reg == RISCV::NoRegister) 11586 report_fatal_error( 11587 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11588 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11589 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11590 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11591 StringRef(RegName) + "\".")); 11592 return Reg; 11593 } 11594 11595 namespace llvm { 11596 namespace RISCVVIntrinsicsTable { 11597 11598 #define GET_RISCVVIntrinsicsTable_IMPL 11599 #include "RISCVGenSearchableTables.inc" 11600 11601 } // namespace RISCVVIntrinsicsTable 11602 11603 } // namespace llvm 11604