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() || Subtarget.hasStdExtZbb()) 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 lowerVectorIntrinsicScalars(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->hasScalarOperand()) 4576 return SDValue(); 4577 4578 unsigned SplatOp = II->ScalarOperand + 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->ScalarOperand > 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 switch (IntNo) { 4625 case Intrinsic::riscv_vslide1up: 4626 case Intrinsic::riscv_vslide1down: 4627 case Intrinsic::riscv_vslide1up_mask: 4628 case Intrinsic::riscv_vslide1down_mask: { 4629 // We need to special case these when the scalar is larger than XLen. 4630 unsigned NumOps = Op.getNumOperands(); 4631 bool IsMasked = NumOps == 7; 4632 4633 // Convert the vector source to the equivalent nxvXi32 vector. 4634 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4635 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4636 4637 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4638 DAG.getConstant(0, DL, XLenVT)); 4639 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4640 DAG.getConstant(1, DL, XLenVT)); 4641 4642 // Double the VL since we halved SEW. 4643 SDValue VL = getVLOperand(Op); 4644 SDValue I32VL = 4645 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4646 4647 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4648 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4649 4650 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4651 // instructions. 4652 SDValue Passthru; 4653 if (IsMasked) 4654 Passthru = DAG.getUNDEF(I32VT); 4655 else 4656 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4657 4658 if (IntNo == Intrinsic::riscv_vslide1up || 4659 IntNo == Intrinsic::riscv_vslide1up_mask) { 4660 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4661 ScalarHi, I32Mask, I32VL); 4662 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4663 ScalarLo, I32Mask, I32VL); 4664 } else { 4665 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4666 ScalarLo, I32Mask, I32VL); 4667 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4668 ScalarHi, I32Mask, I32VL); 4669 } 4670 4671 // Convert back to nxvXi64. 4672 Vec = DAG.getBitcast(VT, Vec); 4673 4674 if (!IsMasked) 4675 return Vec; 4676 // Apply mask after the operation. 4677 SDValue Mask = Operands[NumOps - 3]; 4678 SDValue MaskedOff = Operands[1]; 4679 // Assume Policy operand is the last operand. 4680 uint64_t Policy = 4681 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4682 // We don't need to select maskedoff if it's undef. 4683 if (MaskedOff.isUndef()) 4684 return Vec; 4685 // TAMU 4686 if (Policy == RISCVII::TAIL_AGNOSTIC) 4687 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4688 VL); 4689 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4690 // It's fine because vmerge does not care mask policy. 4691 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4692 } 4693 } 4694 4695 // We need to convert the scalar to a splat vector. 4696 // FIXME: Can we implicitly truncate the scalar if it is known to 4697 // be sign extended? 4698 SDValue VL = getVLOperand(Op); 4699 assert(VL.getValueType() == XLenVT); 4700 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4701 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4702 } 4703 4704 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4705 SelectionDAG &DAG) const { 4706 unsigned IntNo = Op.getConstantOperandVal(0); 4707 SDLoc DL(Op); 4708 MVT XLenVT = Subtarget.getXLenVT(); 4709 4710 switch (IntNo) { 4711 default: 4712 break; // Don't custom lower most intrinsics. 4713 case Intrinsic::thread_pointer: { 4714 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4715 return DAG.getRegister(RISCV::X4, PtrVT); 4716 } 4717 case Intrinsic::riscv_orc_b: 4718 case Intrinsic::riscv_brev8: { 4719 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4720 unsigned Opc = 4721 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4722 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4723 DAG.getConstant(7, DL, XLenVT)); 4724 } 4725 case Intrinsic::riscv_grev: 4726 case Intrinsic::riscv_gorc: { 4727 unsigned Opc = 4728 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4729 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4730 } 4731 case Intrinsic::riscv_zip: 4732 case Intrinsic::riscv_unzip: { 4733 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4734 // For i32 the immdiate is 15. For i64 the immediate is 31. 4735 unsigned Opc = 4736 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4737 unsigned BitWidth = Op.getValueSizeInBits(); 4738 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4739 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4740 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4741 } 4742 case Intrinsic::riscv_shfl: 4743 case Intrinsic::riscv_unshfl: { 4744 unsigned Opc = 4745 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4746 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4747 } 4748 case Intrinsic::riscv_bcompress: 4749 case Intrinsic::riscv_bdecompress: { 4750 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4751 : RISCVISD::BDECOMPRESS; 4752 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4753 } 4754 case Intrinsic::riscv_bfp: 4755 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4756 Op.getOperand(2)); 4757 case Intrinsic::riscv_fsl: 4758 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4759 Op.getOperand(2), Op.getOperand(3)); 4760 case Intrinsic::riscv_fsr: 4761 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4762 Op.getOperand(2), Op.getOperand(3)); 4763 case Intrinsic::riscv_vmv_x_s: 4764 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4765 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4766 Op.getOperand(1)); 4767 case Intrinsic::riscv_vmv_v_x: 4768 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4769 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4770 Subtarget); 4771 case Intrinsic::riscv_vfmv_v_f: 4772 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4773 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4774 case Intrinsic::riscv_vmv_s_x: { 4775 SDValue Scalar = Op.getOperand(2); 4776 4777 if (Scalar.getValueType().bitsLE(XLenVT)) { 4778 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4779 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4780 Op.getOperand(1), Scalar, Op.getOperand(3)); 4781 } 4782 4783 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4784 4785 // This is an i64 value that lives in two scalar registers. We have to 4786 // insert this in a convoluted way. First we build vXi64 splat containing 4787 // the/ two values that we assemble using some bit math. Next we'll use 4788 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4789 // to merge element 0 from our splat into the source vector. 4790 // FIXME: This is probably not the best way to do this, but it is 4791 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4792 // point. 4793 // sw lo, (a0) 4794 // sw hi, 4(a0) 4795 // vlse vX, (a0) 4796 // 4797 // vid.v vVid 4798 // vmseq.vx mMask, vVid, 0 4799 // vmerge.vvm vDest, vSrc, vVal, mMask 4800 MVT VT = Op.getSimpleValueType(); 4801 SDValue Vec = Op.getOperand(1); 4802 SDValue VL = getVLOperand(Op); 4803 4804 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4805 if (Op.getOperand(1).isUndef()) 4806 return SplattedVal; 4807 SDValue SplattedIdx = 4808 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4809 DAG.getConstant(0, DL, MVT::i32), VL); 4810 4811 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4812 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4813 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4814 SDValue SelectCond = 4815 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4816 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4817 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4818 Vec, VL); 4819 } 4820 } 4821 4822 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4823 } 4824 4825 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4826 SelectionDAG &DAG) const { 4827 unsigned IntNo = Op.getConstantOperandVal(1); 4828 switch (IntNo) { 4829 default: 4830 break; 4831 case Intrinsic::riscv_masked_strided_load: { 4832 SDLoc DL(Op); 4833 MVT XLenVT = Subtarget.getXLenVT(); 4834 4835 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4836 // the selection of the masked intrinsics doesn't do this for us. 4837 SDValue Mask = Op.getOperand(5); 4838 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4839 4840 MVT VT = Op->getSimpleValueType(0); 4841 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4842 4843 SDValue PassThru = Op.getOperand(2); 4844 if (!IsUnmasked) { 4845 MVT MaskVT = 4846 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4847 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4848 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4849 } 4850 4851 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4852 4853 SDValue IntID = DAG.getTargetConstant( 4854 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4855 XLenVT); 4856 4857 auto *Load = cast<MemIntrinsicSDNode>(Op); 4858 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4859 if (IsUnmasked) 4860 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4861 else 4862 Ops.push_back(PassThru); 4863 Ops.push_back(Op.getOperand(3)); // Ptr 4864 Ops.push_back(Op.getOperand(4)); // Stride 4865 if (!IsUnmasked) 4866 Ops.push_back(Mask); 4867 Ops.push_back(VL); 4868 if (!IsUnmasked) { 4869 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4870 Ops.push_back(Policy); 4871 } 4872 4873 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4874 SDValue Result = 4875 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4876 Load->getMemoryVT(), Load->getMemOperand()); 4877 SDValue Chain = Result.getValue(1); 4878 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4879 return DAG.getMergeValues({Result, Chain}, DL); 4880 } 4881 } 4882 4883 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4884 } 4885 4886 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4887 SelectionDAG &DAG) const { 4888 unsigned IntNo = Op.getConstantOperandVal(1); 4889 switch (IntNo) { 4890 default: 4891 break; 4892 case Intrinsic::riscv_masked_strided_store: { 4893 SDLoc DL(Op); 4894 MVT XLenVT = Subtarget.getXLenVT(); 4895 4896 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4897 // the selection of the masked intrinsics doesn't do this for us. 4898 SDValue Mask = Op.getOperand(5); 4899 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4900 4901 SDValue Val = Op.getOperand(2); 4902 MVT VT = Val.getSimpleValueType(); 4903 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4904 4905 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4906 if (!IsUnmasked) { 4907 MVT MaskVT = 4908 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4909 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4910 } 4911 4912 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4913 4914 SDValue IntID = DAG.getTargetConstant( 4915 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4916 XLenVT); 4917 4918 auto *Store = cast<MemIntrinsicSDNode>(Op); 4919 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4920 Ops.push_back(Val); 4921 Ops.push_back(Op.getOperand(3)); // Ptr 4922 Ops.push_back(Op.getOperand(4)); // Stride 4923 if (!IsUnmasked) 4924 Ops.push_back(Mask); 4925 Ops.push_back(VL); 4926 4927 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4928 Ops, Store->getMemoryVT(), 4929 Store->getMemOperand()); 4930 } 4931 } 4932 4933 return SDValue(); 4934 } 4935 4936 static MVT getLMUL1VT(MVT VT) { 4937 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4938 "Unexpected vector MVT"); 4939 return MVT::getScalableVectorVT( 4940 VT.getVectorElementType(), 4941 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4942 } 4943 4944 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4945 switch (ISDOpcode) { 4946 default: 4947 llvm_unreachable("Unhandled reduction"); 4948 case ISD::VECREDUCE_ADD: 4949 return RISCVISD::VECREDUCE_ADD_VL; 4950 case ISD::VECREDUCE_UMAX: 4951 return RISCVISD::VECREDUCE_UMAX_VL; 4952 case ISD::VECREDUCE_SMAX: 4953 return RISCVISD::VECREDUCE_SMAX_VL; 4954 case ISD::VECREDUCE_UMIN: 4955 return RISCVISD::VECREDUCE_UMIN_VL; 4956 case ISD::VECREDUCE_SMIN: 4957 return RISCVISD::VECREDUCE_SMIN_VL; 4958 case ISD::VECREDUCE_AND: 4959 return RISCVISD::VECREDUCE_AND_VL; 4960 case ISD::VECREDUCE_OR: 4961 return RISCVISD::VECREDUCE_OR_VL; 4962 case ISD::VECREDUCE_XOR: 4963 return RISCVISD::VECREDUCE_XOR_VL; 4964 } 4965 } 4966 4967 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4968 SelectionDAG &DAG, 4969 bool IsVP) const { 4970 SDLoc DL(Op); 4971 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4972 MVT VecVT = Vec.getSimpleValueType(); 4973 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4974 Op.getOpcode() == ISD::VECREDUCE_OR || 4975 Op.getOpcode() == ISD::VECREDUCE_XOR || 4976 Op.getOpcode() == ISD::VP_REDUCE_AND || 4977 Op.getOpcode() == ISD::VP_REDUCE_OR || 4978 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4979 "Unexpected reduction lowering"); 4980 4981 MVT XLenVT = Subtarget.getXLenVT(); 4982 assert(Op.getValueType() == XLenVT && 4983 "Expected reduction output to be legalized to XLenVT"); 4984 4985 MVT ContainerVT = VecVT; 4986 if (VecVT.isFixedLengthVector()) { 4987 ContainerVT = getContainerForFixedLengthVector(VecVT); 4988 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4989 } 4990 4991 SDValue Mask, VL; 4992 if (IsVP) { 4993 Mask = Op.getOperand(2); 4994 VL = Op.getOperand(3); 4995 } else { 4996 std::tie(Mask, VL) = 4997 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4998 } 4999 5000 unsigned BaseOpc; 5001 ISD::CondCode CC; 5002 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5003 5004 switch (Op.getOpcode()) { 5005 default: 5006 llvm_unreachable("Unhandled reduction"); 5007 case ISD::VECREDUCE_AND: 5008 case ISD::VP_REDUCE_AND: { 5009 // vcpop ~x == 0 5010 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5011 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5012 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5013 CC = ISD::SETEQ; 5014 BaseOpc = ISD::AND; 5015 break; 5016 } 5017 case ISD::VECREDUCE_OR: 5018 case ISD::VP_REDUCE_OR: 5019 // vcpop x != 0 5020 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5021 CC = ISD::SETNE; 5022 BaseOpc = ISD::OR; 5023 break; 5024 case ISD::VECREDUCE_XOR: 5025 case ISD::VP_REDUCE_XOR: { 5026 // ((vcpop x) & 1) != 0 5027 SDValue One = DAG.getConstant(1, DL, XLenVT); 5028 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5029 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5030 CC = ISD::SETNE; 5031 BaseOpc = ISD::XOR; 5032 break; 5033 } 5034 } 5035 5036 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5037 5038 if (!IsVP) 5039 return SetCC; 5040 5041 // Now include the start value in the operation. 5042 // Note that we must return the start value when no elements are operated 5043 // upon. The vcpop instructions we've emitted in each case above will return 5044 // 0 for an inactive vector, and so we've already received the neutral value: 5045 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5046 // can simply include the start value. 5047 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5048 } 5049 5050 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5051 SelectionDAG &DAG) const { 5052 SDLoc DL(Op); 5053 SDValue Vec = Op.getOperand(0); 5054 EVT VecEVT = Vec.getValueType(); 5055 5056 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5057 5058 // Due to ordering in legalize types we may have a vector type that needs to 5059 // be split. Do that manually so we can get down to a legal type. 5060 while (getTypeAction(*DAG.getContext(), VecEVT) == 5061 TargetLowering::TypeSplitVector) { 5062 SDValue Lo, Hi; 5063 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5064 VecEVT = Lo.getValueType(); 5065 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5066 } 5067 5068 // TODO: The type may need to be widened rather than split. Or widened before 5069 // it can be split. 5070 if (!isTypeLegal(VecEVT)) 5071 return SDValue(); 5072 5073 MVT VecVT = VecEVT.getSimpleVT(); 5074 MVT VecEltVT = VecVT.getVectorElementType(); 5075 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5076 5077 MVT ContainerVT = VecVT; 5078 if (VecVT.isFixedLengthVector()) { 5079 ContainerVT = getContainerForFixedLengthVector(VecVT); 5080 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5081 } 5082 5083 MVT M1VT = getLMUL1VT(ContainerVT); 5084 MVT XLenVT = Subtarget.getXLenVT(); 5085 5086 SDValue Mask, VL; 5087 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5088 5089 SDValue NeutralElem = 5090 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5091 SDValue IdentitySplat = 5092 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5093 M1VT, DL, DAG, Subtarget); 5094 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5095 IdentitySplat, Mask, VL); 5096 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5097 DAG.getConstant(0, DL, XLenVT)); 5098 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5099 } 5100 5101 // Given a reduction op, this function returns the matching reduction opcode, 5102 // the vector SDValue and the scalar SDValue required to lower this to a 5103 // RISCVISD node. 5104 static std::tuple<unsigned, SDValue, SDValue> 5105 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5106 SDLoc DL(Op); 5107 auto Flags = Op->getFlags(); 5108 unsigned Opcode = Op.getOpcode(); 5109 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5110 switch (Opcode) { 5111 default: 5112 llvm_unreachable("Unhandled reduction"); 5113 case ISD::VECREDUCE_FADD: { 5114 // Use positive zero if we can. It is cheaper to materialize. 5115 SDValue Zero = 5116 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5117 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5118 } 5119 case ISD::VECREDUCE_SEQ_FADD: 5120 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5121 Op.getOperand(0)); 5122 case ISD::VECREDUCE_FMIN: 5123 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5124 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5125 case ISD::VECREDUCE_FMAX: 5126 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5127 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5128 } 5129 } 5130 5131 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5132 SelectionDAG &DAG) const { 5133 SDLoc DL(Op); 5134 MVT VecEltVT = Op.getSimpleValueType(); 5135 5136 unsigned RVVOpcode; 5137 SDValue VectorVal, ScalarVal; 5138 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5139 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5140 MVT VecVT = VectorVal.getSimpleValueType(); 5141 5142 MVT ContainerVT = VecVT; 5143 if (VecVT.isFixedLengthVector()) { 5144 ContainerVT = getContainerForFixedLengthVector(VecVT); 5145 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5146 } 5147 5148 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5149 MVT XLenVT = Subtarget.getXLenVT(); 5150 5151 SDValue Mask, VL; 5152 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5153 5154 SDValue ScalarSplat = 5155 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5156 M1VT, DL, DAG, Subtarget); 5157 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5158 VectorVal, ScalarSplat, Mask, VL); 5159 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5160 DAG.getConstant(0, DL, XLenVT)); 5161 } 5162 5163 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5164 switch (ISDOpcode) { 5165 default: 5166 llvm_unreachable("Unhandled reduction"); 5167 case ISD::VP_REDUCE_ADD: 5168 return RISCVISD::VECREDUCE_ADD_VL; 5169 case ISD::VP_REDUCE_UMAX: 5170 return RISCVISD::VECREDUCE_UMAX_VL; 5171 case ISD::VP_REDUCE_SMAX: 5172 return RISCVISD::VECREDUCE_SMAX_VL; 5173 case ISD::VP_REDUCE_UMIN: 5174 return RISCVISD::VECREDUCE_UMIN_VL; 5175 case ISD::VP_REDUCE_SMIN: 5176 return RISCVISD::VECREDUCE_SMIN_VL; 5177 case ISD::VP_REDUCE_AND: 5178 return RISCVISD::VECREDUCE_AND_VL; 5179 case ISD::VP_REDUCE_OR: 5180 return RISCVISD::VECREDUCE_OR_VL; 5181 case ISD::VP_REDUCE_XOR: 5182 return RISCVISD::VECREDUCE_XOR_VL; 5183 case ISD::VP_REDUCE_FADD: 5184 return RISCVISD::VECREDUCE_FADD_VL; 5185 case ISD::VP_REDUCE_SEQ_FADD: 5186 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5187 case ISD::VP_REDUCE_FMAX: 5188 return RISCVISD::VECREDUCE_FMAX_VL; 5189 case ISD::VP_REDUCE_FMIN: 5190 return RISCVISD::VECREDUCE_FMIN_VL; 5191 } 5192 } 5193 5194 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5195 SelectionDAG &DAG) const { 5196 SDLoc DL(Op); 5197 SDValue Vec = Op.getOperand(1); 5198 EVT VecEVT = Vec.getValueType(); 5199 5200 // TODO: The type may need to be widened rather than split. Or widened before 5201 // it can be split. 5202 if (!isTypeLegal(VecEVT)) 5203 return SDValue(); 5204 5205 MVT VecVT = VecEVT.getSimpleVT(); 5206 MVT VecEltVT = VecVT.getVectorElementType(); 5207 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5208 5209 MVT ContainerVT = VecVT; 5210 if (VecVT.isFixedLengthVector()) { 5211 ContainerVT = getContainerForFixedLengthVector(VecVT); 5212 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5213 } 5214 5215 SDValue VL = Op.getOperand(3); 5216 SDValue Mask = Op.getOperand(2); 5217 5218 MVT M1VT = getLMUL1VT(ContainerVT); 5219 MVT XLenVT = Subtarget.getXLenVT(); 5220 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5221 5222 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5223 DAG.getConstant(1, DL, XLenVT), M1VT, 5224 DL, DAG, Subtarget); 5225 SDValue Reduction = 5226 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5227 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5228 DAG.getConstant(0, DL, XLenVT)); 5229 if (!VecVT.isInteger()) 5230 return Elt0; 5231 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5232 } 5233 5234 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5235 SelectionDAG &DAG) const { 5236 SDValue Vec = Op.getOperand(0); 5237 SDValue SubVec = Op.getOperand(1); 5238 MVT VecVT = Vec.getSimpleValueType(); 5239 MVT SubVecVT = SubVec.getSimpleValueType(); 5240 5241 SDLoc DL(Op); 5242 MVT XLenVT = Subtarget.getXLenVT(); 5243 unsigned OrigIdx = Op.getConstantOperandVal(2); 5244 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5245 5246 // We don't have the ability to slide mask vectors up indexed by their i1 5247 // elements; the smallest we can do is i8. Often we are able to bitcast to 5248 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5249 // into a scalable one, we might not necessarily have enough scalable 5250 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5251 if (SubVecVT.getVectorElementType() == MVT::i1 && 5252 (OrigIdx != 0 || !Vec.isUndef())) { 5253 if (VecVT.getVectorMinNumElements() >= 8 && 5254 SubVecVT.getVectorMinNumElements() >= 8) { 5255 assert(OrigIdx % 8 == 0 && "Invalid index"); 5256 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5257 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5258 "Unexpected mask vector lowering"); 5259 OrigIdx /= 8; 5260 SubVecVT = 5261 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5262 SubVecVT.isScalableVector()); 5263 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5264 VecVT.isScalableVector()); 5265 Vec = DAG.getBitcast(VecVT, Vec); 5266 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5267 } else { 5268 // We can't slide this mask vector up indexed by its i1 elements. 5269 // This poses a problem when we wish to insert a scalable vector which 5270 // can't be re-expressed as a larger type. Just choose the slow path and 5271 // extend to a larger type, then truncate back down. 5272 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5273 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5274 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5275 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5276 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5277 Op.getOperand(2)); 5278 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5279 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5280 } 5281 } 5282 5283 // If the subvector vector is a fixed-length type, we cannot use subregister 5284 // manipulation to simplify the codegen; we don't know which register of a 5285 // LMUL group contains the specific subvector as we only know the minimum 5286 // register size. Therefore we must slide the vector group up the full 5287 // amount. 5288 if (SubVecVT.isFixedLengthVector()) { 5289 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5290 return Op; 5291 MVT ContainerVT = VecVT; 5292 if (VecVT.isFixedLengthVector()) { 5293 ContainerVT = getContainerForFixedLengthVector(VecVT); 5294 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5295 } 5296 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5297 DAG.getUNDEF(ContainerVT), SubVec, 5298 DAG.getConstant(0, DL, XLenVT)); 5299 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5300 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5301 return DAG.getBitcast(Op.getValueType(), SubVec); 5302 } 5303 SDValue Mask = 5304 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5305 // Set the vector length to only the number of elements we care about. Note 5306 // that for slideup this includes the offset. 5307 SDValue VL = 5308 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5309 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5310 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5311 SubVec, SlideupAmt, Mask, VL); 5312 if (VecVT.isFixedLengthVector()) 5313 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5314 return DAG.getBitcast(Op.getValueType(), Slideup); 5315 } 5316 5317 unsigned SubRegIdx, RemIdx; 5318 std::tie(SubRegIdx, RemIdx) = 5319 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5320 VecVT, SubVecVT, OrigIdx, TRI); 5321 5322 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5323 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5324 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5325 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5326 5327 // 1. If the Idx has been completely eliminated and this subvector's size is 5328 // a vector register or a multiple thereof, or the surrounding elements are 5329 // undef, then this is a subvector insert which naturally aligns to a vector 5330 // register. These can easily be handled using subregister manipulation. 5331 // 2. If the subvector is smaller than a vector register, then the insertion 5332 // must preserve the undisturbed elements of the register. We do this by 5333 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5334 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5335 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5336 // LMUL=1 type back into the larger vector (resolving to another subregister 5337 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5338 // to avoid allocating a large register group to hold our subvector. 5339 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5340 return Op; 5341 5342 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5343 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5344 // (in our case undisturbed). This means we can set up a subvector insertion 5345 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5346 // size of the subvector. 5347 MVT InterSubVT = VecVT; 5348 SDValue AlignedExtract = Vec; 5349 unsigned AlignedIdx = OrigIdx - RemIdx; 5350 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5351 InterSubVT = getLMUL1VT(VecVT); 5352 // Extract a subvector equal to the nearest full vector register type. This 5353 // should resolve to a EXTRACT_SUBREG instruction. 5354 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5355 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5356 } 5357 5358 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5359 // For scalable vectors this must be further multiplied by vscale. 5360 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5361 5362 SDValue Mask, VL; 5363 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5364 5365 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5366 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5367 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5368 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5369 5370 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5371 DAG.getUNDEF(InterSubVT), SubVec, 5372 DAG.getConstant(0, DL, XLenVT)); 5373 5374 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5375 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5376 5377 // If required, insert this subvector back into the correct vector register. 5378 // This should resolve to an INSERT_SUBREG instruction. 5379 if (VecVT.bitsGT(InterSubVT)) 5380 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5381 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5382 5383 // We might have bitcast from a mask type: cast back to the original type if 5384 // required. 5385 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5386 } 5387 5388 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5389 SelectionDAG &DAG) const { 5390 SDValue Vec = Op.getOperand(0); 5391 MVT SubVecVT = Op.getSimpleValueType(); 5392 MVT VecVT = Vec.getSimpleValueType(); 5393 5394 SDLoc DL(Op); 5395 MVT XLenVT = Subtarget.getXLenVT(); 5396 unsigned OrigIdx = Op.getConstantOperandVal(1); 5397 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5398 5399 // We don't have the ability to slide mask vectors down indexed by their i1 5400 // elements; the smallest we can do is i8. Often we are able to bitcast to 5401 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5402 // from a scalable one, we might not necessarily have enough scalable 5403 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5404 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5405 if (VecVT.getVectorMinNumElements() >= 8 && 5406 SubVecVT.getVectorMinNumElements() >= 8) { 5407 assert(OrigIdx % 8 == 0 && "Invalid index"); 5408 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5409 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5410 "Unexpected mask vector lowering"); 5411 OrigIdx /= 8; 5412 SubVecVT = 5413 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5414 SubVecVT.isScalableVector()); 5415 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5416 VecVT.isScalableVector()); 5417 Vec = DAG.getBitcast(VecVT, Vec); 5418 } else { 5419 // We can't slide this mask vector down, indexed by its i1 elements. 5420 // This poses a problem when we wish to extract a scalable vector which 5421 // can't be re-expressed as a larger type. Just choose the slow path and 5422 // extend to a larger type, then truncate back down. 5423 // TODO: We could probably improve this when extracting certain fixed 5424 // from fixed, where we can extract as i8 and shift the correct element 5425 // right to reach the desired subvector? 5426 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5427 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5428 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5429 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5430 Op.getOperand(1)); 5431 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5432 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5433 } 5434 } 5435 5436 // If the subvector vector is a fixed-length type, we cannot use subregister 5437 // manipulation to simplify the codegen; we don't know which register of a 5438 // LMUL group contains the specific subvector as we only know the minimum 5439 // register size. Therefore we must slide the vector group down the full 5440 // amount. 5441 if (SubVecVT.isFixedLengthVector()) { 5442 // With an index of 0 this is a cast-like subvector, which can be performed 5443 // with subregister operations. 5444 if (OrigIdx == 0) 5445 return Op; 5446 MVT ContainerVT = VecVT; 5447 if (VecVT.isFixedLengthVector()) { 5448 ContainerVT = getContainerForFixedLengthVector(VecVT); 5449 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5450 } 5451 SDValue Mask = 5452 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5453 // Set the vector length to only the number of elements we care about. This 5454 // avoids sliding down elements we're going to discard straight away. 5455 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5456 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5457 SDValue Slidedown = 5458 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5459 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5460 // Now we can use a cast-like subvector extract to get the result. 5461 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5462 DAG.getConstant(0, DL, XLenVT)); 5463 return DAG.getBitcast(Op.getValueType(), Slidedown); 5464 } 5465 5466 unsigned SubRegIdx, RemIdx; 5467 std::tie(SubRegIdx, RemIdx) = 5468 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5469 VecVT, SubVecVT, OrigIdx, TRI); 5470 5471 // If the Idx has been completely eliminated then this is a subvector extract 5472 // which naturally aligns to a vector register. These can easily be handled 5473 // using subregister manipulation. 5474 if (RemIdx == 0) 5475 return Op; 5476 5477 // Else we must shift our vector register directly to extract the subvector. 5478 // Do this using VSLIDEDOWN. 5479 5480 // If the vector type is an LMUL-group type, extract a subvector equal to the 5481 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5482 // instruction. 5483 MVT InterSubVT = VecVT; 5484 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5485 InterSubVT = getLMUL1VT(VecVT); 5486 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5487 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5488 } 5489 5490 // Slide this vector register down by the desired number of elements in order 5491 // to place the desired subvector starting at element 0. 5492 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5493 // For scalable vectors this must be further multiplied by vscale. 5494 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5495 5496 SDValue Mask, VL; 5497 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5498 SDValue Slidedown = 5499 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5500 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5501 5502 // Now the vector is in the right position, extract our final subvector. This 5503 // should resolve to a COPY. 5504 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5505 DAG.getConstant(0, DL, XLenVT)); 5506 5507 // We might have bitcast from a mask type: cast back to the original type if 5508 // required. 5509 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5510 } 5511 5512 // Lower step_vector to the vid instruction. Any non-identity step value must 5513 // be accounted for my manual expansion. 5514 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5515 SelectionDAG &DAG) const { 5516 SDLoc DL(Op); 5517 MVT VT = Op.getSimpleValueType(); 5518 MVT XLenVT = Subtarget.getXLenVT(); 5519 SDValue Mask, VL; 5520 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5521 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5522 uint64_t StepValImm = Op.getConstantOperandVal(0); 5523 if (StepValImm != 1) { 5524 if (isPowerOf2_64(StepValImm)) { 5525 SDValue StepVal = 5526 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5527 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5528 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5529 } else { 5530 SDValue StepVal = lowerScalarSplat( 5531 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5532 VL, VT, DL, DAG, Subtarget); 5533 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5534 } 5535 } 5536 return StepVec; 5537 } 5538 5539 // Implement vector_reverse using vrgather.vv with indices determined by 5540 // subtracting the id of each element from (VLMAX-1). This will convert 5541 // the indices like so: 5542 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5543 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5544 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5545 SelectionDAG &DAG) const { 5546 SDLoc DL(Op); 5547 MVT VecVT = Op.getSimpleValueType(); 5548 unsigned EltSize = VecVT.getScalarSizeInBits(); 5549 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5550 5551 unsigned MaxVLMAX = 0; 5552 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5553 if (VectorBitsMax != 0) 5554 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5555 5556 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5557 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5558 5559 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5560 // to use vrgatherei16.vv. 5561 // TODO: It's also possible to use vrgatherei16.vv for other types to 5562 // decrease register width for the index calculation. 5563 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5564 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5565 // Reverse each half, then reassemble them in reverse order. 5566 // NOTE: It's also possible that after splitting that VLMAX no longer 5567 // requires vrgatherei16.vv. 5568 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5569 SDValue Lo, Hi; 5570 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5571 EVT LoVT, HiVT; 5572 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5573 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5574 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5575 // Reassemble the low and high pieces reversed. 5576 // FIXME: This is a CONCAT_VECTORS. 5577 SDValue Res = 5578 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5579 DAG.getIntPtrConstant(0, DL)); 5580 return DAG.getNode( 5581 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5582 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5583 } 5584 5585 // Just promote the int type to i16 which will double the LMUL. 5586 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5587 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5588 } 5589 5590 MVT XLenVT = Subtarget.getXLenVT(); 5591 SDValue Mask, VL; 5592 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5593 5594 // Calculate VLMAX-1 for the desired SEW. 5595 unsigned MinElts = VecVT.getVectorMinNumElements(); 5596 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5597 DAG.getConstant(MinElts, DL, XLenVT)); 5598 SDValue VLMinus1 = 5599 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5600 5601 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5602 bool IsRV32E64 = 5603 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5604 SDValue SplatVL; 5605 if (!IsRV32E64) 5606 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5607 else 5608 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5609 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5610 5611 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5612 SDValue Indices = 5613 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5614 5615 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5616 } 5617 5618 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5619 SelectionDAG &DAG) const { 5620 SDLoc DL(Op); 5621 SDValue V1 = Op.getOperand(0); 5622 SDValue V2 = Op.getOperand(1); 5623 MVT XLenVT = Subtarget.getXLenVT(); 5624 MVT VecVT = Op.getSimpleValueType(); 5625 5626 unsigned MinElts = VecVT.getVectorMinNumElements(); 5627 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5628 DAG.getConstant(MinElts, DL, XLenVT)); 5629 5630 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5631 SDValue DownOffset, UpOffset; 5632 if (ImmValue >= 0) { 5633 // The operand is a TargetConstant, we need to rebuild it as a regular 5634 // constant. 5635 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5636 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5637 } else { 5638 // The operand is a TargetConstant, we need to rebuild it as a regular 5639 // constant rather than negating the original operand. 5640 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5641 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5642 } 5643 5644 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5645 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax); 5646 5647 SDValue SlideDown = 5648 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5649 DownOffset, TrueMask, UpOffset); 5650 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5651 TrueMask, 5652 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5653 } 5654 5655 SDValue 5656 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5657 SelectionDAG &DAG) const { 5658 SDLoc DL(Op); 5659 auto *Load = cast<LoadSDNode>(Op); 5660 5661 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5662 Load->getMemoryVT(), 5663 *Load->getMemOperand()) && 5664 "Expecting a correctly-aligned load"); 5665 5666 MVT VT = Op.getSimpleValueType(); 5667 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5668 5669 SDValue VL = 5670 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5671 5672 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5673 SDValue NewLoad = DAG.getMemIntrinsicNode( 5674 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5675 Load->getMemoryVT(), Load->getMemOperand()); 5676 5677 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5678 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5679 } 5680 5681 SDValue 5682 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5683 SelectionDAG &DAG) const { 5684 SDLoc DL(Op); 5685 auto *Store = cast<StoreSDNode>(Op); 5686 5687 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5688 Store->getMemoryVT(), 5689 *Store->getMemOperand()) && 5690 "Expecting a correctly-aligned store"); 5691 5692 SDValue StoreVal = Store->getValue(); 5693 MVT VT = StoreVal.getSimpleValueType(); 5694 5695 // If the size less than a byte, we need to pad with zeros to make a byte. 5696 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5697 VT = MVT::v8i1; 5698 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5699 DAG.getConstant(0, DL, VT), StoreVal, 5700 DAG.getIntPtrConstant(0, DL)); 5701 } 5702 5703 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5704 5705 SDValue VL = 5706 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5707 5708 SDValue NewValue = 5709 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5710 return DAG.getMemIntrinsicNode( 5711 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5712 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5713 Store->getMemoryVT(), Store->getMemOperand()); 5714 } 5715 5716 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5717 SelectionDAG &DAG) const { 5718 SDLoc DL(Op); 5719 MVT VT = Op.getSimpleValueType(); 5720 5721 const auto *MemSD = cast<MemSDNode>(Op); 5722 EVT MemVT = MemSD->getMemoryVT(); 5723 MachineMemOperand *MMO = MemSD->getMemOperand(); 5724 SDValue Chain = MemSD->getChain(); 5725 SDValue BasePtr = MemSD->getBasePtr(); 5726 5727 SDValue Mask, PassThru, VL; 5728 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5729 Mask = VPLoad->getMask(); 5730 PassThru = DAG.getUNDEF(VT); 5731 VL = VPLoad->getVectorLength(); 5732 } else { 5733 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5734 Mask = MLoad->getMask(); 5735 PassThru = MLoad->getPassThru(); 5736 } 5737 5738 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5739 5740 MVT XLenVT = Subtarget.getXLenVT(); 5741 5742 MVT ContainerVT = VT; 5743 if (VT.isFixedLengthVector()) { 5744 ContainerVT = getContainerForFixedLengthVector(VT); 5745 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5746 if (!IsUnmasked) { 5747 MVT MaskVT = 5748 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5749 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5750 } 5751 } 5752 5753 if (!VL) 5754 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5755 5756 unsigned IntID = 5757 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5758 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5759 if (IsUnmasked) 5760 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5761 else 5762 Ops.push_back(PassThru); 5763 Ops.push_back(BasePtr); 5764 if (!IsUnmasked) 5765 Ops.push_back(Mask); 5766 Ops.push_back(VL); 5767 if (!IsUnmasked) 5768 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5769 5770 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5771 5772 SDValue Result = 5773 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5774 Chain = Result.getValue(1); 5775 5776 if (VT.isFixedLengthVector()) 5777 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5778 5779 return DAG.getMergeValues({Result, Chain}, DL); 5780 } 5781 5782 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5783 SelectionDAG &DAG) const { 5784 SDLoc DL(Op); 5785 5786 const auto *MemSD = cast<MemSDNode>(Op); 5787 EVT MemVT = MemSD->getMemoryVT(); 5788 MachineMemOperand *MMO = MemSD->getMemOperand(); 5789 SDValue Chain = MemSD->getChain(); 5790 SDValue BasePtr = MemSD->getBasePtr(); 5791 SDValue Val, Mask, VL; 5792 5793 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5794 Val = VPStore->getValue(); 5795 Mask = VPStore->getMask(); 5796 VL = VPStore->getVectorLength(); 5797 } else { 5798 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5799 Val = MStore->getValue(); 5800 Mask = MStore->getMask(); 5801 } 5802 5803 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5804 5805 MVT VT = Val.getSimpleValueType(); 5806 MVT XLenVT = Subtarget.getXLenVT(); 5807 5808 MVT ContainerVT = VT; 5809 if (VT.isFixedLengthVector()) { 5810 ContainerVT = getContainerForFixedLengthVector(VT); 5811 5812 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5813 if (!IsUnmasked) { 5814 MVT MaskVT = 5815 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5816 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5817 } 5818 } 5819 5820 if (!VL) 5821 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5822 5823 unsigned IntID = 5824 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5825 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5826 Ops.push_back(Val); 5827 Ops.push_back(BasePtr); 5828 if (!IsUnmasked) 5829 Ops.push_back(Mask); 5830 Ops.push_back(VL); 5831 5832 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5833 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5834 } 5835 5836 SDValue 5837 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5838 SelectionDAG &DAG) const { 5839 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5840 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5841 5842 MVT VT = Op.getSimpleValueType(); 5843 5844 SDValue Op1 = 5845 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5846 SDValue Op2 = 5847 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5848 5849 SDLoc DL(Op); 5850 SDValue VL = 5851 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5852 5853 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5854 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5855 5856 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5857 Op.getOperand(2), Mask, VL); 5858 5859 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5860 } 5861 5862 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5863 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5864 MVT VT = Op.getSimpleValueType(); 5865 5866 if (VT.getVectorElementType() == MVT::i1) 5867 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5868 5869 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5870 } 5871 5872 SDValue 5873 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5874 SelectionDAG &DAG) const { 5875 unsigned Opc; 5876 switch (Op.getOpcode()) { 5877 default: llvm_unreachable("Unexpected opcode!"); 5878 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5879 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5880 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5881 } 5882 5883 return lowerToScalableOp(Op, DAG, Opc); 5884 } 5885 5886 // Lower vector ABS to smax(X, sub(0, X)). 5887 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5888 SDLoc DL(Op); 5889 MVT VT = Op.getSimpleValueType(); 5890 SDValue X = Op.getOperand(0); 5891 5892 assert(VT.isFixedLengthVector() && "Unexpected type"); 5893 5894 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5895 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5896 5897 SDValue Mask, VL; 5898 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5899 5900 SDValue SplatZero = DAG.getNode( 5901 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5902 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5903 SDValue NegX = 5904 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5905 SDValue Max = 5906 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5907 5908 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5909 } 5910 5911 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5912 SDValue Op, SelectionDAG &DAG) const { 5913 SDLoc DL(Op); 5914 MVT VT = Op.getSimpleValueType(); 5915 SDValue Mag = Op.getOperand(0); 5916 SDValue Sign = Op.getOperand(1); 5917 assert(Mag.getValueType() == Sign.getValueType() && 5918 "Can only handle COPYSIGN with matching types."); 5919 5920 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5921 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5922 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5923 5924 SDValue Mask, VL; 5925 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5926 5927 SDValue CopySign = 5928 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5929 5930 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5931 } 5932 5933 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5934 SDValue Op, SelectionDAG &DAG) const { 5935 MVT VT = Op.getSimpleValueType(); 5936 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5937 5938 MVT I1ContainerVT = 5939 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5940 5941 SDValue CC = 5942 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5943 SDValue Op1 = 5944 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5945 SDValue Op2 = 5946 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5947 5948 SDLoc DL(Op); 5949 SDValue Mask, VL; 5950 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5951 5952 SDValue Select = 5953 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5954 5955 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5956 } 5957 5958 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5959 unsigned NewOpc, 5960 bool HasMask) const { 5961 MVT VT = Op.getSimpleValueType(); 5962 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5963 5964 // Create list of operands by converting existing ones to scalable types. 5965 SmallVector<SDValue, 6> Ops; 5966 for (const SDValue &V : Op->op_values()) { 5967 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5968 5969 // Pass through non-vector operands. 5970 if (!V.getValueType().isVector()) { 5971 Ops.push_back(V); 5972 continue; 5973 } 5974 5975 // "cast" fixed length vector to a scalable vector. 5976 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5977 "Only fixed length vectors are supported!"); 5978 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5979 } 5980 5981 SDLoc DL(Op); 5982 SDValue Mask, VL; 5983 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5984 if (HasMask) 5985 Ops.push_back(Mask); 5986 Ops.push_back(VL); 5987 5988 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5989 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5990 } 5991 5992 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5993 // * Operands of each node are assumed to be in the same order. 5994 // * The EVL operand is promoted from i32 to i64 on RV64. 5995 // * Fixed-length vectors are converted to their scalable-vector container 5996 // types. 5997 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5998 unsigned RISCVISDOpc) const { 5999 SDLoc DL(Op); 6000 MVT VT = Op.getSimpleValueType(); 6001 SmallVector<SDValue, 4> Ops; 6002 6003 for (const auto &OpIdx : enumerate(Op->ops())) { 6004 SDValue V = OpIdx.value(); 6005 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6006 // Pass through operands which aren't fixed-length vectors. 6007 if (!V.getValueType().isFixedLengthVector()) { 6008 Ops.push_back(V); 6009 continue; 6010 } 6011 // "cast" fixed length vector to a scalable vector. 6012 MVT OpVT = V.getSimpleValueType(); 6013 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6014 assert(useRVVForFixedLengthVectorVT(OpVT) && 6015 "Only fixed length vectors are supported!"); 6016 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6017 } 6018 6019 if (!VT.isFixedLengthVector()) 6020 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6021 6022 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6023 6024 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6025 6026 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6027 } 6028 6029 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6030 unsigned MaskOpc, 6031 unsigned VecOpc) const { 6032 MVT VT = Op.getSimpleValueType(); 6033 if (VT.getVectorElementType() != MVT::i1) 6034 return lowerVPOp(Op, DAG, VecOpc); 6035 6036 // It is safe to drop mask parameter as masked-off elements are undef. 6037 SDValue Op1 = Op->getOperand(0); 6038 SDValue Op2 = Op->getOperand(1); 6039 SDValue VL = Op->getOperand(3); 6040 6041 MVT ContainerVT = VT; 6042 const bool IsFixed = VT.isFixedLengthVector(); 6043 if (IsFixed) { 6044 ContainerVT = getContainerForFixedLengthVector(VT); 6045 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6046 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6047 } 6048 6049 SDLoc DL(Op); 6050 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6051 if (!IsFixed) 6052 return Val; 6053 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6054 } 6055 6056 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6057 // matched to a RVV indexed load. The RVV indexed load instructions only 6058 // support the "unsigned unscaled" addressing mode; indices are implicitly 6059 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6060 // signed or scaled indexing is extended to the XLEN value type and scaled 6061 // accordingly. 6062 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6063 SelectionDAG &DAG) const { 6064 SDLoc DL(Op); 6065 MVT VT = Op.getSimpleValueType(); 6066 6067 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6068 EVT MemVT = MemSD->getMemoryVT(); 6069 MachineMemOperand *MMO = MemSD->getMemOperand(); 6070 SDValue Chain = MemSD->getChain(); 6071 SDValue BasePtr = MemSD->getBasePtr(); 6072 6073 ISD::LoadExtType LoadExtType; 6074 SDValue Index, Mask, PassThru, VL; 6075 6076 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6077 Index = VPGN->getIndex(); 6078 Mask = VPGN->getMask(); 6079 PassThru = DAG.getUNDEF(VT); 6080 VL = VPGN->getVectorLength(); 6081 // VP doesn't support extending loads. 6082 LoadExtType = ISD::NON_EXTLOAD; 6083 } else { 6084 // Else it must be a MGATHER. 6085 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6086 Index = MGN->getIndex(); 6087 Mask = MGN->getMask(); 6088 PassThru = MGN->getPassThru(); 6089 LoadExtType = MGN->getExtensionType(); 6090 } 6091 6092 MVT IndexVT = Index.getSimpleValueType(); 6093 MVT XLenVT = Subtarget.getXLenVT(); 6094 6095 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6096 "Unexpected VTs!"); 6097 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6098 // Targets have to explicitly opt-in for extending vector loads. 6099 assert(LoadExtType == ISD::NON_EXTLOAD && 6100 "Unexpected extending MGATHER/VP_GATHER"); 6101 (void)LoadExtType; 6102 6103 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6104 // the selection of the masked intrinsics doesn't do this for us. 6105 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6106 6107 MVT ContainerVT = VT; 6108 if (VT.isFixedLengthVector()) { 6109 // We need to use the larger of the result and index type to determine the 6110 // scalable type to use so we don't increase LMUL for any operand/result. 6111 if (VT.bitsGE(IndexVT)) { 6112 ContainerVT = getContainerForFixedLengthVector(VT); 6113 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6114 ContainerVT.getVectorElementCount()); 6115 } else { 6116 IndexVT = getContainerForFixedLengthVector(IndexVT); 6117 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6118 IndexVT.getVectorElementCount()); 6119 } 6120 6121 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6122 6123 if (!IsUnmasked) { 6124 MVT MaskVT = 6125 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6126 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6127 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6128 } 6129 } 6130 6131 if (!VL) 6132 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6133 6134 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6135 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6136 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6137 VL); 6138 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6139 TrueMask, VL); 6140 } 6141 6142 unsigned IntID = 6143 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6144 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6145 if (IsUnmasked) 6146 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6147 else 6148 Ops.push_back(PassThru); 6149 Ops.push_back(BasePtr); 6150 Ops.push_back(Index); 6151 if (!IsUnmasked) 6152 Ops.push_back(Mask); 6153 Ops.push_back(VL); 6154 if (!IsUnmasked) 6155 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6156 6157 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6158 SDValue Result = 6159 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6160 Chain = Result.getValue(1); 6161 6162 if (VT.isFixedLengthVector()) 6163 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6164 6165 return DAG.getMergeValues({Result, Chain}, DL); 6166 } 6167 6168 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6169 // matched to a RVV indexed store. The RVV indexed store instructions only 6170 // support the "unsigned unscaled" addressing mode; indices are implicitly 6171 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6172 // signed or scaled indexing is extended to the XLEN value type and scaled 6173 // accordingly. 6174 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6175 SelectionDAG &DAG) const { 6176 SDLoc DL(Op); 6177 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6178 EVT MemVT = MemSD->getMemoryVT(); 6179 MachineMemOperand *MMO = MemSD->getMemOperand(); 6180 SDValue Chain = MemSD->getChain(); 6181 SDValue BasePtr = MemSD->getBasePtr(); 6182 6183 bool IsTruncatingStore = false; 6184 SDValue Index, Mask, Val, VL; 6185 6186 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6187 Index = VPSN->getIndex(); 6188 Mask = VPSN->getMask(); 6189 Val = VPSN->getValue(); 6190 VL = VPSN->getVectorLength(); 6191 // VP doesn't support truncating stores. 6192 IsTruncatingStore = false; 6193 } else { 6194 // Else it must be a MSCATTER. 6195 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6196 Index = MSN->getIndex(); 6197 Mask = MSN->getMask(); 6198 Val = MSN->getValue(); 6199 IsTruncatingStore = MSN->isTruncatingStore(); 6200 } 6201 6202 MVT VT = Val.getSimpleValueType(); 6203 MVT IndexVT = Index.getSimpleValueType(); 6204 MVT XLenVT = Subtarget.getXLenVT(); 6205 6206 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6207 "Unexpected VTs!"); 6208 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6209 // Targets have to explicitly opt-in for extending vector loads and 6210 // truncating vector stores. 6211 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6212 (void)IsTruncatingStore; 6213 6214 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6215 // the selection of the masked intrinsics doesn't do this for us. 6216 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6217 6218 MVT ContainerVT = VT; 6219 if (VT.isFixedLengthVector()) { 6220 // We need to use the larger of the value and index type to determine the 6221 // scalable type to use so we don't increase LMUL for any operand/result. 6222 if (VT.bitsGE(IndexVT)) { 6223 ContainerVT = getContainerForFixedLengthVector(VT); 6224 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6225 ContainerVT.getVectorElementCount()); 6226 } else { 6227 IndexVT = getContainerForFixedLengthVector(IndexVT); 6228 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6229 IndexVT.getVectorElementCount()); 6230 } 6231 6232 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6233 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6234 6235 if (!IsUnmasked) { 6236 MVT MaskVT = 6237 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6238 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6239 } 6240 } 6241 6242 if (!VL) 6243 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6244 6245 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6246 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6247 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6248 VL); 6249 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6250 TrueMask, VL); 6251 } 6252 6253 unsigned IntID = 6254 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6255 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6256 Ops.push_back(Val); 6257 Ops.push_back(BasePtr); 6258 Ops.push_back(Index); 6259 if (!IsUnmasked) 6260 Ops.push_back(Mask); 6261 Ops.push_back(VL); 6262 6263 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6264 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6265 } 6266 6267 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6268 SelectionDAG &DAG) const { 6269 const MVT XLenVT = Subtarget.getXLenVT(); 6270 SDLoc DL(Op); 6271 SDValue Chain = Op->getOperand(0); 6272 SDValue SysRegNo = DAG.getTargetConstant( 6273 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6274 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6275 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6276 6277 // Encoding used for rounding mode in RISCV differs from that used in 6278 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6279 // table, which consists of a sequence of 4-bit fields, each representing 6280 // corresponding FLT_ROUNDS mode. 6281 static const int Table = 6282 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6283 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6284 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6285 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6286 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6287 6288 SDValue Shift = 6289 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6290 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6291 DAG.getConstant(Table, DL, XLenVT), Shift); 6292 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6293 DAG.getConstant(7, DL, XLenVT)); 6294 6295 return DAG.getMergeValues({Masked, Chain}, DL); 6296 } 6297 6298 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6299 SelectionDAG &DAG) const { 6300 const MVT XLenVT = Subtarget.getXLenVT(); 6301 SDLoc DL(Op); 6302 SDValue Chain = Op->getOperand(0); 6303 SDValue RMValue = Op->getOperand(1); 6304 SDValue SysRegNo = DAG.getTargetConstant( 6305 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6306 6307 // Encoding used for rounding mode in RISCV differs from that used in 6308 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6309 // a table, which consists of a sequence of 4-bit fields, each representing 6310 // corresponding RISCV mode. 6311 static const unsigned Table = 6312 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6313 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6314 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6315 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6316 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6317 6318 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6319 DAG.getConstant(2, DL, XLenVT)); 6320 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6321 DAG.getConstant(Table, DL, XLenVT), Shift); 6322 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6323 DAG.getConstant(0x7, DL, XLenVT)); 6324 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6325 RMValue); 6326 } 6327 6328 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6329 switch (IntNo) { 6330 default: 6331 llvm_unreachable("Unexpected Intrinsic"); 6332 case Intrinsic::riscv_grev: 6333 return RISCVISD::GREVW; 6334 case Intrinsic::riscv_gorc: 6335 return RISCVISD::GORCW; 6336 case Intrinsic::riscv_bcompress: 6337 return RISCVISD::BCOMPRESSW; 6338 case Intrinsic::riscv_bdecompress: 6339 return RISCVISD::BDECOMPRESSW; 6340 case Intrinsic::riscv_bfp: 6341 return RISCVISD::BFPW; 6342 case Intrinsic::riscv_fsl: 6343 return RISCVISD::FSLW; 6344 case Intrinsic::riscv_fsr: 6345 return RISCVISD::FSRW; 6346 } 6347 } 6348 6349 // Converts the given intrinsic to a i64 operation with any extension. 6350 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6351 unsigned IntNo) { 6352 SDLoc DL(N); 6353 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6354 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6355 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6356 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6357 // ReplaceNodeResults requires we maintain the same type for the return value. 6358 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6359 } 6360 6361 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6362 // form of the given Opcode. 6363 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6364 switch (Opcode) { 6365 default: 6366 llvm_unreachable("Unexpected opcode"); 6367 case ISD::SHL: 6368 return RISCVISD::SLLW; 6369 case ISD::SRA: 6370 return RISCVISD::SRAW; 6371 case ISD::SRL: 6372 return RISCVISD::SRLW; 6373 case ISD::SDIV: 6374 return RISCVISD::DIVW; 6375 case ISD::UDIV: 6376 return RISCVISD::DIVUW; 6377 case ISD::UREM: 6378 return RISCVISD::REMUW; 6379 case ISD::ROTL: 6380 return RISCVISD::ROLW; 6381 case ISD::ROTR: 6382 return RISCVISD::RORW; 6383 case RISCVISD::GREV: 6384 return RISCVISD::GREVW; 6385 case RISCVISD::GORC: 6386 return RISCVISD::GORCW; 6387 } 6388 } 6389 6390 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6391 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6392 // otherwise be promoted to i64, making it difficult to select the 6393 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6394 // type i8/i16/i32 is lost. 6395 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6396 unsigned ExtOpc = ISD::ANY_EXTEND) { 6397 SDLoc DL(N); 6398 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6399 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6400 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6401 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6402 // ReplaceNodeResults requires we maintain the same type for the return value. 6403 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6404 } 6405 6406 // Converts the given 32-bit operation to a i64 operation with signed extension 6407 // semantic to reduce the signed extension instructions. 6408 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6409 SDLoc DL(N); 6410 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6411 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6412 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6413 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6414 DAG.getValueType(MVT::i32)); 6415 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6416 } 6417 6418 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6419 SmallVectorImpl<SDValue> &Results, 6420 SelectionDAG &DAG) const { 6421 SDLoc DL(N); 6422 switch (N->getOpcode()) { 6423 default: 6424 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6425 case ISD::STRICT_FP_TO_SINT: 6426 case ISD::STRICT_FP_TO_UINT: 6427 case ISD::FP_TO_SINT: 6428 case ISD::FP_TO_UINT: { 6429 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6430 "Unexpected custom legalisation"); 6431 bool IsStrict = N->isStrictFPOpcode(); 6432 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6433 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6434 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6435 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6436 TargetLowering::TypeSoftenFloat) { 6437 if (!isTypeLegal(Op0.getValueType())) 6438 return; 6439 if (IsStrict) { 6440 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6441 : RISCVISD::STRICT_FCVT_WU_RV64; 6442 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6443 SDValue Res = DAG.getNode( 6444 Opc, DL, VTs, N->getOperand(0), Op0, 6445 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6446 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6447 Results.push_back(Res.getValue(1)); 6448 return; 6449 } 6450 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6451 SDValue Res = 6452 DAG.getNode(Opc, DL, MVT::i64, Op0, 6453 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6454 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6455 return; 6456 } 6457 // If the FP type needs to be softened, emit a library call using the 'si' 6458 // version. If we left it to default legalization we'd end up with 'di'. If 6459 // the FP type doesn't need to be softened just let generic type 6460 // legalization promote the result type. 6461 RTLIB::Libcall LC; 6462 if (IsSigned) 6463 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6464 else 6465 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6466 MakeLibCallOptions CallOptions; 6467 EVT OpVT = Op0.getValueType(); 6468 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6469 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6470 SDValue Result; 6471 std::tie(Result, Chain) = 6472 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6473 Results.push_back(Result); 6474 if (IsStrict) 6475 Results.push_back(Chain); 6476 break; 6477 } 6478 case ISD::READCYCLECOUNTER: { 6479 assert(!Subtarget.is64Bit() && 6480 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6481 6482 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6483 SDValue RCW = 6484 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6485 6486 Results.push_back( 6487 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6488 Results.push_back(RCW.getValue(2)); 6489 break; 6490 } 6491 case ISD::MUL: { 6492 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6493 unsigned XLen = Subtarget.getXLen(); 6494 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6495 if (Size > XLen) { 6496 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6497 SDValue LHS = N->getOperand(0); 6498 SDValue RHS = N->getOperand(1); 6499 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6500 6501 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6502 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6503 // We need exactly one side to be unsigned. 6504 if (LHSIsU == RHSIsU) 6505 return; 6506 6507 auto MakeMULPair = [&](SDValue S, SDValue U) { 6508 MVT XLenVT = Subtarget.getXLenVT(); 6509 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6510 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6511 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6512 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6513 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6514 }; 6515 6516 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6517 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6518 6519 // The other operand should be signed, but still prefer MULH when 6520 // possible. 6521 if (RHSIsU && LHSIsS && !RHSIsS) 6522 Results.push_back(MakeMULPair(LHS, RHS)); 6523 else if (LHSIsU && RHSIsS && !LHSIsS) 6524 Results.push_back(MakeMULPair(RHS, LHS)); 6525 6526 return; 6527 } 6528 LLVM_FALLTHROUGH; 6529 } 6530 case ISD::ADD: 6531 case ISD::SUB: 6532 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6533 "Unexpected custom legalisation"); 6534 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6535 break; 6536 case ISD::SHL: 6537 case ISD::SRA: 6538 case ISD::SRL: 6539 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6540 "Unexpected custom legalisation"); 6541 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6542 Results.push_back(customLegalizeToWOp(N, DAG)); 6543 break; 6544 } 6545 6546 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6547 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6548 // shift amount. 6549 if (N->getOpcode() == ISD::SHL) { 6550 SDLoc DL(N); 6551 SDValue NewOp0 = 6552 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6553 SDValue NewOp1 = 6554 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6555 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6556 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6557 DAG.getValueType(MVT::i32)); 6558 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6559 } 6560 6561 break; 6562 case ISD::ROTL: 6563 case ISD::ROTR: 6564 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6565 "Unexpected custom legalisation"); 6566 Results.push_back(customLegalizeToWOp(N, DAG)); 6567 break; 6568 case ISD::CTTZ: 6569 case ISD::CTTZ_ZERO_UNDEF: 6570 case ISD::CTLZ: 6571 case ISD::CTLZ_ZERO_UNDEF: { 6572 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6573 "Unexpected custom legalisation"); 6574 6575 SDValue NewOp0 = 6576 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6577 bool IsCTZ = 6578 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6579 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6580 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6581 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6582 return; 6583 } 6584 case ISD::SDIV: 6585 case ISD::UDIV: 6586 case ISD::UREM: { 6587 MVT VT = N->getSimpleValueType(0); 6588 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6589 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6590 "Unexpected custom legalisation"); 6591 // Don't promote division/remainder by constant since we should expand those 6592 // to multiply by magic constant. 6593 // FIXME: What if the expansion is disabled for minsize. 6594 if (N->getOperand(1).getOpcode() == ISD::Constant) 6595 return; 6596 6597 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6598 // the upper 32 bits. For other types we need to sign or zero extend 6599 // based on the opcode. 6600 unsigned ExtOpc = ISD::ANY_EXTEND; 6601 if (VT != MVT::i32) 6602 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6603 : ISD::ZERO_EXTEND; 6604 6605 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6606 break; 6607 } 6608 case ISD::UADDO: 6609 case ISD::USUBO: { 6610 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6611 "Unexpected custom legalisation"); 6612 bool IsAdd = N->getOpcode() == ISD::UADDO; 6613 // Create an ADDW or SUBW. 6614 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6615 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6616 SDValue Res = 6617 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6618 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6619 DAG.getValueType(MVT::i32)); 6620 6621 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6622 // Since the inputs are sign extended from i32, this is equivalent to 6623 // comparing the lower 32 bits. 6624 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6625 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6626 IsAdd ? ISD::SETULT : ISD::SETUGT); 6627 6628 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6629 Results.push_back(Overflow); 6630 return; 6631 } 6632 case ISD::UADDSAT: 6633 case ISD::USUBSAT: { 6634 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6635 "Unexpected custom legalisation"); 6636 if (Subtarget.hasStdExtZbb()) { 6637 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6638 // sign extend allows overflow of the lower 32 bits to be detected on 6639 // the promoted size. 6640 SDValue LHS = 6641 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6642 SDValue RHS = 6643 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6644 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6645 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6646 return; 6647 } 6648 6649 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6650 // promotion for UADDO/USUBO. 6651 Results.push_back(expandAddSubSat(N, DAG)); 6652 return; 6653 } 6654 case ISD::ABS: { 6655 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6656 "Unexpected custom legalisation"); 6657 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6658 6659 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6660 6661 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6662 6663 // Freeze the source so we can increase it's use count. 6664 Src = DAG.getFreeze(Src); 6665 6666 // Copy sign bit to all bits using the sraiw pattern. 6667 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6668 DAG.getValueType(MVT::i32)); 6669 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6670 DAG.getConstant(31, DL, MVT::i64)); 6671 6672 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6673 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6674 6675 // NOTE: The result is only required to be anyextended, but sext is 6676 // consistent with type legalization of sub. 6677 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6678 DAG.getValueType(MVT::i32)); 6679 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6680 return; 6681 } 6682 case ISD::BITCAST: { 6683 EVT VT = N->getValueType(0); 6684 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6685 SDValue Op0 = N->getOperand(0); 6686 EVT Op0VT = Op0.getValueType(); 6687 MVT XLenVT = Subtarget.getXLenVT(); 6688 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6689 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6690 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6691 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6692 Subtarget.hasStdExtF()) { 6693 SDValue FPConv = 6694 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6695 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6696 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6697 isTypeLegal(Op0VT)) { 6698 // Custom-legalize bitcasts from fixed-length vector types to illegal 6699 // scalar types in order to improve codegen. Bitcast the vector to a 6700 // one-element vector type whose element type is the same as the result 6701 // type, and extract the first element. 6702 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6703 if (isTypeLegal(BVT)) { 6704 SDValue BVec = DAG.getBitcast(BVT, Op0); 6705 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6706 DAG.getConstant(0, DL, XLenVT))); 6707 } 6708 } 6709 break; 6710 } 6711 case RISCVISD::GREV: 6712 case RISCVISD::GORC: { 6713 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6714 "Unexpected custom legalisation"); 6715 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6716 // This is similar to customLegalizeToWOp, except that we pass the second 6717 // operand (a TargetConstant) straight through: it is already of type 6718 // XLenVT. 6719 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6720 SDValue NewOp0 = 6721 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6722 SDValue NewOp1 = 6723 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6724 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6725 // ReplaceNodeResults requires we maintain the same type for the return 6726 // value. 6727 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6728 break; 6729 } 6730 case RISCVISD::SHFL: { 6731 // There is no SHFLIW instruction, but we can just promote the operation. 6732 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6733 "Unexpected custom legalisation"); 6734 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6735 SDValue NewOp0 = 6736 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6737 SDValue NewOp1 = 6738 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6739 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6740 // ReplaceNodeResults requires we maintain the same type for the return 6741 // value. 6742 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6743 break; 6744 } 6745 case ISD::BSWAP: 6746 case ISD::BITREVERSE: { 6747 MVT VT = N->getSimpleValueType(0); 6748 MVT XLenVT = Subtarget.getXLenVT(); 6749 assert((VT == MVT::i8 || VT == MVT::i16 || 6750 (VT == MVT::i32 && Subtarget.is64Bit())) && 6751 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6752 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6753 unsigned Imm = VT.getSizeInBits() - 1; 6754 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6755 if (N->getOpcode() == ISD::BSWAP) 6756 Imm &= ~0x7U; 6757 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6758 SDValue GREVI = 6759 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6760 // ReplaceNodeResults requires we maintain the same type for the return 6761 // value. 6762 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6763 break; 6764 } 6765 case ISD::FSHL: 6766 case ISD::FSHR: { 6767 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6768 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6769 SDValue NewOp0 = 6770 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6771 SDValue NewOp1 = 6772 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6773 SDValue NewShAmt = 6774 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6775 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6776 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6777 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6778 DAG.getConstant(0x1f, DL, MVT::i64)); 6779 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6780 // instruction use different orders. fshl will return its first operand for 6781 // shift of zero, fshr will return its second operand. fsl and fsr both 6782 // return rs1 so the ISD nodes need to have different operand orders. 6783 // Shift amount is in rs2. 6784 unsigned Opc = RISCVISD::FSLW; 6785 if (N->getOpcode() == ISD::FSHR) { 6786 std::swap(NewOp0, NewOp1); 6787 Opc = RISCVISD::FSRW; 6788 } 6789 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6790 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6791 break; 6792 } 6793 case ISD::EXTRACT_VECTOR_ELT: { 6794 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6795 // type is illegal (currently only vXi64 RV32). 6796 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6797 // transferred to the destination register. We issue two of these from the 6798 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6799 // first element. 6800 SDValue Vec = N->getOperand(0); 6801 SDValue Idx = N->getOperand(1); 6802 6803 // The vector type hasn't been legalized yet so we can't issue target 6804 // specific nodes if it needs legalization. 6805 // FIXME: We would manually legalize if it's important. 6806 if (!isTypeLegal(Vec.getValueType())) 6807 return; 6808 6809 MVT VecVT = Vec.getSimpleValueType(); 6810 6811 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6812 VecVT.getVectorElementType() == MVT::i64 && 6813 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6814 6815 // If this is a fixed vector, we need to convert it to a scalable vector. 6816 MVT ContainerVT = VecVT; 6817 if (VecVT.isFixedLengthVector()) { 6818 ContainerVT = getContainerForFixedLengthVector(VecVT); 6819 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6820 } 6821 6822 MVT XLenVT = Subtarget.getXLenVT(); 6823 6824 // Use a VL of 1 to avoid processing more elements than we need. 6825 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6826 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6827 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6828 6829 // Unless the index is known to be 0, we must slide the vector down to get 6830 // the desired element into index 0. 6831 if (!isNullConstant(Idx)) { 6832 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6833 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6834 } 6835 6836 // Extract the lower XLEN bits of the correct vector element. 6837 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6838 6839 // To extract the upper XLEN bits of the vector element, shift the first 6840 // element right by 32 bits and re-extract the lower XLEN bits. 6841 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6842 DAG.getUNDEF(ContainerVT), 6843 DAG.getConstant(32, DL, XLenVT), VL); 6844 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6845 ThirtyTwoV, Mask, VL); 6846 6847 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6848 6849 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6850 break; 6851 } 6852 case ISD::INTRINSIC_WO_CHAIN: { 6853 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6854 switch (IntNo) { 6855 default: 6856 llvm_unreachable( 6857 "Don't know how to custom type legalize this intrinsic!"); 6858 case Intrinsic::riscv_grev: 6859 case Intrinsic::riscv_gorc: 6860 case Intrinsic::riscv_bcompress: 6861 case Intrinsic::riscv_bdecompress: 6862 case Intrinsic::riscv_bfp: { 6863 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6864 "Unexpected custom legalisation"); 6865 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6866 break; 6867 } 6868 case Intrinsic::riscv_fsl: 6869 case Intrinsic::riscv_fsr: { 6870 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6871 "Unexpected custom legalisation"); 6872 SDValue NewOp1 = 6873 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6874 SDValue NewOp2 = 6875 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6876 SDValue NewOp3 = 6877 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6878 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6879 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6880 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6881 break; 6882 } 6883 case Intrinsic::riscv_orc_b: { 6884 // Lower to the GORCI encoding for orc.b with the operand extended. 6885 SDValue NewOp = 6886 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6887 // If Zbp is enabled, use GORCIW which will sign extend the result. 6888 unsigned Opc = 6889 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6890 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6891 DAG.getConstant(7, DL, MVT::i64)); 6892 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6893 return; 6894 } 6895 case Intrinsic::riscv_shfl: 6896 case Intrinsic::riscv_unshfl: { 6897 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6898 "Unexpected custom legalisation"); 6899 SDValue NewOp1 = 6900 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6901 SDValue NewOp2 = 6902 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6903 unsigned Opc = 6904 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6905 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6906 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6907 // will be shuffled the same way as the lower 32 bit half, but the two 6908 // halves won't cross. 6909 if (isa<ConstantSDNode>(NewOp2)) { 6910 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6911 DAG.getConstant(0xf, DL, MVT::i64)); 6912 Opc = 6913 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6914 } 6915 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6916 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6917 break; 6918 } 6919 case Intrinsic::riscv_vmv_x_s: { 6920 EVT VT = N->getValueType(0); 6921 MVT XLenVT = Subtarget.getXLenVT(); 6922 if (VT.bitsLT(XLenVT)) { 6923 // Simple case just extract using vmv.x.s and truncate. 6924 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6925 Subtarget.getXLenVT(), N->getOperand(1)); 6926 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6927 return; 6928 } 6929 6930 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6931 "Unexpected custom legalization"); 6932 6933 // We need to do the move in two steps. 6934 SDValue Vec = N->getOperand(1); 6935 MVT VecVT = Vec.getSimpleValueType(); 6936 6937 // First extract the lower XLEN bits of the element. 6938 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6939 6940 // To extract the upper XLEN bits of the vector element, shift the first 6941 // element right by 32 bits and re-extract the lower XLEN bits. 6942 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6943 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6944 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6945 SDValue ThirtyTwoV = 6946 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 6947 DAG.getConstant(32, DL, XLenVT), VL); 6948 SDValue LShr32 = 6949 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6950 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6951 6952 Results.push_back( 6953 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6954 break; 6955 } 6956 } 6957 break; 6958 } 6959 case ISD::VECREDUCE_ADD: 6960 case ISD::VECREDUCE_AND: 6961 case ISD::VECREDUCE_OR: 6962 case ISD::VECREDUCE_XOR: 6963 case ISD::VECREDUCE_SMAX: 6964 case ISD::VECREDUCE_UMAX: 6965 case ISD::VECREDUCE_SMIN: 6966 case ISD::VECREDUCE_UMIN: 6967 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6968 Results.push_back(V); 6969 break; 6970 case ISD::VP_REDUCE_ADD: 6971 case ISD::VP_REDUCE_AND: 6972 case ISD::VP_REDUCE_OR: 6973 case ISD::VP_REDUCE_XOR: 6974 case ISD::VP_REDUCE_SMAX: 6975 case ISD::VP_REDUCE_UMAX: 6976 case ISD::VP_REDUCE_SMIN: 6977 case ISD::VP_REDUCE_UMIN: 6978 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6979 Results.push_back(V); 6980 break; 6981 case ISD::FLT_ROUNDS_: { 6982 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6983 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6984 Results.push_back(Res.getValue(0)); 6985 Results.push_back(Res.getValue(1)); 6986 break; 6987 } 6988 } 6989 } 6990 6991 // A structure to hold one of the bit-manipulation patterns below. Together, a 6992 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6993 // (or (and (shl x, 1), 0xAAAAAAAA), 6994 // (and (srl x, 1), 0x55555555)) 6995 struct RISCVBitmanipPat { 6996 SDValue Op; 6997 unsigned ShAmt; 6998 bool IsSHL; 6999 7000 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7001 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7002 } 7003 }; 7004 7005 // Matches patterns of the form 7006 // (and (shl x, C2), (C1 << C2)) 7007 // (and (srl x, C2), C1) 7008 // (shl (and x, C1), C2) 7009 // (srl (and x, (C1 << C2)), C2) 7010 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7011 // The expected masks for each shift amount are specified in BitmanipMasks where 7012 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7013 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7014 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7015 // XLen is 64. 7016 static Optional<RISCVBitmanipPat> 7017 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7018 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7019 "Unexpected number of masks"); 7020 Optional<uint64_t> Mask; 7021 // Optionally consume a mask around the shift operation. 7022 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7023 Mask = Op.getConstantOperandVal(1); 7024 Op = Op.getOperand(0); 7025 } 7026 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7027 return None; 7028 bool IsSHL = Op.getOpcode() == ISD::SHL; 7029 7030 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7031 return None; 7032 uint64_t ShAmt = Op.getConstantOperandVal(1); 7033 7034 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7035 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7036 return None; 7037 // If we don't have enough masks for 64 bit, then we must be trying to 7038 // match SHFL so we're only allowed to shift 1/4 of the width. 7039 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7040 return None; 7041 7042 SDValue Src = Op.getOperand(0); 7043 7044 // The expected mask is shifted left when the AND is found around SHL 7045 // patterns. 7046 // ((x >> 1) & 0x55555555) 7047 // ((x << 1) & 0xAAAAAAAA) 7048 bool SHLExpMask = IsSHL; 7049 7050 if (!Mask) { 7051 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7052 // the mask is all ones: consume that now. 7053 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7054 Mask = Src.getConstantOperandVal(1); 7055 Src = Src.getOperand(0); 7056 // The expected mask is now in fact shifted left for SRL, so reverse the 7057 // decision. 7058 // ((x & 0xAAAAAAAA) >> 1) 7059 // ((x & 0x55555555) << 1) 7060 SHLExpMask = !SHLExpMask; 7061 } else { 7062 // Use a default shifted mask of all-ones if there's no AND, truncated 7063 // down to the expected width. This simplifies the logic later on. 7064 Mask = maskTrailingOnes<uint64_t>(Width); 7065 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7066 } 7067 } 7068 7069 unsigned MaskIdx = Log2_32(ShAmt); 7070 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7071 7072 if (SHLExpMask) 7073 ExpMask <<= ShAmt; 7074 7075 if (Mask != ExpMask) 7076 return None; 7077 7078 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7079 } 7080 7081 // Matches any of the following bit-manipulation patterns: 7082 // (and (shl x, 1), (0x55555555 << 1)) 7083 // (and (srl x, 1), 0x55555555) 7084 // (shl (and x, 0x55555555), 1) 7085 // (srl (and x, (0x55555555 << 1)), 1) 7086 // where the shift amount and mask may vary thus: 7087 // [1] = 0x55555555 / 0xAAAAAAAA 7088 // [2] = 0x33333333 / 0xCCCCCCCC 7089 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7090 // [8] = 0x00FF00FF / 0xFF00FF00 7091 // [16] = 0x0000FFFF / 0xFFFFFFFF 7092 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7093 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7094 // These are the unshifted masks which we use to match bit-manipulation 7095 // patterns. They may be shifted left in certain circumstances. 7096 static const uint64_t BitmanipMasks[] = { 7097 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7098 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7099 7100 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7101 } 7102 7103 // Match the following pattern as a GREVI(W) operation 7104 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7105 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7106 const RISCVSubtarget &Subtarget) { 7107 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7108 EVT VT = Op.getValueType(); 7109 7110 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7111 auto LHS = matchGREVIPat(Op.getOperand(0)); 7112 auto RHS = matchGREVIPat(Op.getOperand(1)); 7113 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7114 SDLoc DL(Op); 7115 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7116 DAG.getConstant(LHS->ShAmt, DL, VT)); 7117 } 7118 } 7119 return SDValue(); 7120 } 7121 7122 // Matches any the following pattern as a GORCI(W) operation 7123 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7124 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7125 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7126 // Note that with the variant of 3., 7127 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7128 // the inner pattern will first be matched as GREVI and then the outer 7129 // pattern will be matched to GORC via the first rule above. 7130 // 4. (or (rotl/rotr x, bitwidth/2), x) 7131 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7132 const RISCVSubtarget &Subtarget) { 7133 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7134 EVT VT = Op.getValueType(); 7135 7136 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7137 SDLoc DL(Op); 7138 SDValue Op0 = Op.getOperand(0); 7139 SDValue Op1 = Op.getOperand(1); 7140 7141 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7142 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7143 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7144 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7145 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7146 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7147 if ((Reverse.getOpcode() == ISD::ROTL || 7148 Reverse.getOpcode() == ISD::ROTR) && 7149 Reverse.getOperand(0) == X && 7150 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7151 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7152 if (RotAmt == (VT.getSizeInBits() / 2)) 7153 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7154 DAG.getConstant(RotAmt, DL, VT)); 7155 } 7156 return SDValue(); 7157 }; 7158 7159 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7160 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7161 return V; 7162 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7163 return V; 7164 7165 // OR is commutable so canonicalize its OR operand to the left 7166 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7167 std::swap(Op0, Op1); 7168 if (Op0.getOpcode() != ISD::OR) 7169 return SDValue(); 7170 SDValue OrOp0 = Op0.getOperand(0); 7171 SDValue OrOp1 = Op0.getOperand(1); 7172 auto LHS = matchGREVIPat(OrOp0); 7173 // OR is commutable so swap the operands and try again: x might have been 7174 // on the left 7175 if (!LHS) { 7176 std::swap(OrOp0, OrOp1); 7177 LHS = matchGREVIPat(OrOp0); 7178 } 7179 auto RHS = matchGREVIPat(Op1); 7180 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7181 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7182 DAG.getConstant(LHS->ShAmt, DL, VT)); 7183 } 7184 } 7185 return SDValue(); 7186 } 7187 7188 // Matches any of the following bit-manipulation patterns: 7189 // (and (shl x, 1), (0x22222222 << 1)) 7190 // (and (srl x, 1), 0x22222222) 7191 // (shl (and x, 0x22222222), 1) 7192 // (srl (and x, (0x22222222 << 1)), 1) 7193 // where the shift amount and mask may vary thus: 7194 // [1] = 0x22222222 / 0x44444444 7195 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7196 // [4] = 0x00F000F0 / 0x0F000F00 7197 // [8] = 0x0000FF00 / 0x00FF0000 7198 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7199 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7200 // These are the unshifted masks which we use to match bit-manipulation 7201 // patterns. They may be shifted left in certain circumstances. 7202 static const uint64_t BitmanipMasks[] = { 7203 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7204 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7205 7206 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7207 } 7208 7209 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7210 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7211 const RISCVSubtarget &Subtarget) { 7212 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7213 EVT VT = Op.getValueType(); 7214 7215 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7216 return SDValue(); 7217 7218 SDValue Op0 = Op.getOperand(0); 7219 SDValue Op1 = Op.getOperand(1); 7220 7221 // Or is commutable so canonicalize the second OR to the LHS. 7222 if (Op0.getOpcode() != ISD::OR) 7223 std::swap(Op0, Op1); 7224 if (Op0.getOpcode() != ISD::OR) 7225 return SDValue(); 7226 7227 // We found an inner OR, so our operands are the operands of the inner OR 7228 // and the other operand of the outer OR. 7229 SDValue A = Op0.getOperand(0); 7230 SDValue B = Op0.getOperand(1); 7231 SDValue C = Op1; 7232 7233 auto Match1 = matchSHFLPat(A); 7234 auto Match2 = matchSHFLPat(B); 7235 7236 // If neither matched, we failed. 7237 if (!Match1 && !Match2) 7238 return SDValue(); 7239 7240 // We had at least one match. if one failed, try the remaining C operand. 7241 if (!Match1) { 7242 std::swap(A, C); 7243 Match1 = matchSHFLPat(A); 7244 if (!Match1) 7245 return SDValue(); 7246 } else if (!Match2) { 7247 std::swap(B, C); 7248 Match2 = matchSHFLPat(B); 7249 if (!Match2) 7250 return SDValue(); 7251 } 7252 assert(Match1 && Match2); 7253 7254 // Make sure our matches pair up. 7255 if (!Match1->formsPairWith(*Match2)) 7256 return SDValue(); 7257 7258 // All the remains is to make sure C is an AND with the same input, that masks 7259 // out the bits that are being shuffled. 7260 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7261 C.getOperand(0) != Match1->Op) 7262 return SDValue(); 7263 7264 uint64_t Mask = C.getConstantOperandVal(1); 7265 7266 static const uint64_t BitmanipMasks[] = { 7267 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7268 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7269 }; 7270 7271 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7272 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7273 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7274 7275 if (Mask != ExpMask) 7276 return SDValue(); 7277 7278 SDLoc DL(Op); 7279 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7280 DAG.getConstant(Match1->ShAmt, DL, VT)); 7281 } 7282 7283 // Optimize (add (shl x, c0), (shl y, c1)) -> 7284 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7285 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7286 const RISCVSubtarget &Subtarget) { 7287 // Perform this optimization only in the zba extension. 7288 if (!Subtarget.hasStdExtZba()) 7289 return SDValue(); 7290 7291 // Skip for vector types and larger types. 7292 EVT VT = N->getValueType(0); 7293 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7294 return SDValue(); 7295 7296 // The two operand nodes must be SHL and have no other use. 7297 SDValue N0 = N->getOperand(0); 7298 SDValue N1 = N->getOperand(1); 7299 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7300 !N0->hasOneUse() || !N1->hasOneUse()) 7301 return SDValue(); 7302 7303 // Check c0 and c1. 7304 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7305 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7306 if (!N0C || !N1C) 7307 return SDValue(); 7308 int64_t C0 = N0C->getSExtValue(); 7309 int64_t C1 = N1C->getSExtValue(); 7310 if (C0 <= 0 || C1 <= 0) 7311 return SDValue(); 7312 7313 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7314 int64_t Bits = std::min(C0, C1); 7315 int64_t Diff = std::abs(C0 - C1); 7316 if (Diff != 1 && Diff != 2 && Diff != 3) 7317 return SDValue(); 7318 7319 // Build nodes. 7320 SDLoc DL(N); 7321 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7322 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7323 SDValue NA0 = 7324 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7325 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7326 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7327 } 7328 7329 // Combine 7330 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) for RV32 7331 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) for RV32 7332 // ROTR ((GREV x, 56), 32) -> (GREVI x, 24) for RV64 7333 // ROTL ((GREV x, 56), 32) -> (GREVI x, 24) for RV64 7334 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64 7335 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64 7336 // The grev patterns represents BSWAP. 7337 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7338 // off the grev. 7339 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7340 const RISCVSubtarget &Subtarget) { 7341 bool IsWInstruction = 7342 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7343 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7344 IsWInstruction) && 7345 "Unexpected opcode!"); 7346 SDValue Src = N->getOperand(0); 7347 EVT VT = N->getValueType(0); 7348 SDLoc DL(N); 7349 7350 if (!Subtarget.hasStdExtZbp()) 7351 return SDValue(); 7352 7353 unsigned GrevOpc = IsWInstruction ? RISCVISD::GREVW : RISCVISD::GREV; 7354 if (Src.getOpcode() != GrevOpc) 7355 return SDValue(); 7356 7357 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7358 !isa<ConstantSDNode>(Src.getOperand(1))) 7359 return SDValue(); 7360 7361 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7362 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7363 7364 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7365 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7366 unsigned ShAmt1 = N->getConstantOperandVal(1); 7367 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7368 if (BitWidth < 16 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7369 return SDValue(); 7370 7371 Src = Src.getOperand(0); 7372 7373 // Toggle bit the MSB of the shift. 7374 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7375 if (CombinedShAmt == 0) 7376 return Src; 7377 7378 return DAG.getNode( 7379 GrevOpc, DL, VT, Src, 7380 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7381 } 7382 7383 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7384 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7385 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7386 // not undo itself, but they are redundant. 7387 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7388 SDValue Src = N->getOperand(0); 7389 7390 if (Src.getOpcode() != N->getOpcode()) 7391 return SDValue(); 7392 7393 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7394 !isa<ConstantSDNode>(Src.getOperand(1))) 7395 return SDValue(); 7396 7397 unsigned ShAmt1 = N->getConstantOperandVal(1); 7398 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7399 Src = Src.getOperand(0); 7400 7401 unsigned CombinedShAmt; 7402 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7403 CombinedShAmt = ShAmt1 | ShAmt2; 7404 else 7405 CombinedShAmt = ShAmt1 ^ ShAmt2; 7406 7407 if (CombinedShAmt == 0) 7408 return Src; 7409 7410 SDLoc DL(N); 7411 return DAG.getNode( 7412 N->getOpcode(), DL, N->getValueType(0), Src, 7413 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7414 } 7415 7416 // Combine a constant select operand into its use: 7417 // 7418 // (and (select cond, -1, c), x) 7419 // -> (select cond, x, (and x, c)) [AllOnes=1] 7420 // (or (select cond, 0, c), x) 7421 // -> (select cond, x, (or x, c)) [AllOnes=0] 7422 // (xor (select cond, 0, c), x) 7423 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7424 // (add (select cond, 0, c), x) 7425 // -> (select cond, x, (add x, c)) [AllOnes=0] 7426 // (sub x, (select cond, 0, c)) 7427 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7428 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7429 SelectionDAG &DAG, bool AllOnes) { 7430 EVT VT = N->getValueType(0); 7431 7432 // Skip vectors. 7433 if (VT.isVector()) 7434 return SDValue(); 7435 7436 if ((Slct.getOpcode() != ISD::SELECT && 7437 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7438 !Slct.hasOneUse()) 7439 return SDValue(); 7440 7441 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7442 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7443 }; 7444 7445 bool SwapSelectOps; 7446 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7447 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7448 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7449 SDValue NonConstantVal; 7450 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7451 SwapSelectOps = false; 7452 NonConstantVal = FalseVal; 7453 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7454 SwapSelectOps = true; 7455 NonConstantVal = TrueVal; 7456 } else 7457 return SDValue(); 7458 7459 // Slct is now know to be the desired identity constant when CC is true. 7460 TrueVal = OtherOp; 7461 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7462 // Unless SwapSelectOps says the condition should be false. 7463 if (SwapSelectOps) 7464 std::swap(TrueVal, FalseVal); 7465 7466 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7467 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7468 {Slct.getOperand(0), Slct.getOperand(1), 7469 Slct.getOperand(2), TrueVal, FalseVal}); 7470 7471 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7472 {Slct.getOperand(0), TrueVal, FalseVal}); 7473 } 7474 7475 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7476 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7477 bool AllOnes) { 7478 SDValue N0 = N->getOperand(0); 7479 SDValue N1 = N->getOperand(1); 7480 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7481 return Result; 7482 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7483 return Result; 7484 return SDValue(); 7485 } 7486 7487 // Transform (add (mul x, c0), c1) -> 7488 // (add (mul (add x, c1/c0), c0), c1%c0). 7489 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7490 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7491 // to an infinite loop in DAGCombine if transformed. 7492 // Or transform (add (mul x, c0), c1) -> 7493 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7494 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7495 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7496 // lead to an infinite loop in DAGCombine if transformed. 7497 // Or transform (add (mul x, c0), c1) -> 7498 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7499 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7500 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7501 // lead to an infinite loop in DAGCombine if transformed. 7502 // Or transform (add (mul x, c0), c1) -> 7503 // (mul (add x, c1/c0), c0). 7504 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7505 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7506 const RISCVSubtarget &Subtarget) { 7507 // Skip for vector types and larger types. 7508 EVT VT = N->getValueType(0); 7509 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7510 return SDValue(); 7511 // The first operand node must be a MUL and has no other use. 7512 SDValue N0 = N->getOperand(0); 7513 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7514 return SDValue(); 7515 // Check if c0 and c1 match above conditions. 7516 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7517 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7518 if (!N0C || !N1C) 7519 return SDValue(); 7520 // If N0C has multiple uses it's possible one of the cases in 7521 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7522 // in an infinite loop. 7523 if (!N0C->hasOneUse()) 7524 return SDValue(); 7525 int64_t C0 = N0C->getSExtValue(); 7526 int64_t C1 = N1C->getSExtValue(); 7527 int64_t CA, CB; 7528 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7529 return SDValue(); 7530 // Search for proper CA (non-zero) and CB that both are simm12. 7531 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7532 !isInt<12>(C0 * (C1 / C0))) { 7533 CA = C1 / C0; 7534 CB = C1 % C0; 7535 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7536 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7537 CA = C1 / C0 + 1; 7538 CB = C1 % C0 - C0; 7539 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7540 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7541 CA = C1 / C0 - 1; 7542 CB = C1 % C0 + C0; 7543 } else 7544 return SDValue(); 7545 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7546 SDLoc DL(N); 7547 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7548 DAG.getConstant(CA, DL, VT)); 7549 SDValue New1 = 7550 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7551 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7552 } 7553 7554 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7555 const RISCVSubtarget &Subtarget) { 7556 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7557 return V; 7558 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7559 return V; 7560 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7561 // (select lhs, rhs, cc, x, (add x, y)) 7562 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7563 } 7564 7565 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7566 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7567 // (select lhs, rhs, cc, x, (sub x, y)) 7568 SDValue N0 = N->getOperand(0); 7569 SDValue N1 = N->getOperand(1); 7570 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7571 } 7572 7573 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7574 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7575 // (select lhs, rhs, cc, x, (and x, y)) 7576 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7577 } 7578 7579 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7580 const RISCVSubtarget &Subtarget) { 7581 if (Subtarget.hasStdExtZbp()) { 7582 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7583 return GREV; 7584 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7585 return GORC; 7586 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7587 return SHFL; 7588 } 7589 7590 // fold (or (select cond, 0, y), x) -> 7591 // (select cond, x, (or x, y)) 7592 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7593 } 7594 7595 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7596 // fold (xor (select cond, 0, y), x) -> 7597 // (select cond, x, (xor x, y)) 7598 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7599 } 7600 7601 static SDValue 7602 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7603 const RISCVSubtarget &Subtarget) { 7604 SDValue Src = N->getOperand(0); 7605 EVT VT = N->getValueType(0); 7606 7607 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7608 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7609 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7610 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7611 Src.getOperand(0)); 7612 7613 // Fold (i64 (sext_inreg (abs X), i32)) -> 7614 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7615 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7616 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7617 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7618 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7619 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7620 // may get combined into an earlier operation so we need to use 7621 // ComputeNumSignBits. 7622 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7623 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7624 // we can't assume that X has 33 sign bits. We must check. 7625 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7626 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7627 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7628 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7629 SDLoc DL(N); 7630 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7631 SDValue Neg = 7632 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7633 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7634 DAG.getValueType(MVT::i32)); 7635 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7636 } 7637 7638 return SDValue(); 7639 } 7640 7641 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7642 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7643 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7644 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7645 // ADDW/SUBW/MULW. 7646 static SDValue performANY_EXTENDCombine(SDNode *N, 7647 TargetLowering::DAGCombinerInfo &DCI, 7648 const RISCVSubtarget &Subtarget) { 7649 if (!Subtarget.is64Bit()) 7650 return SDValue(); 7651 7652 SelectionDAG &DAG = DCI.DAG; 7653 7654 SDValue Src = N->getOperand(0); 7655 EVT VT = N->getValueType(0); 7656 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7657 return SDValue(); 7658 7659 // The opcode must be one that can implicitly sign_extend. 7660 // FIXME: Additional opcodes. 7661 switch (Src.getOpcode()) { 7662 default: 7663 return SDValue(); 7664 case ISD::MUL: 7665 if (!Subtarget.hasStdExtM()) 7666 return SDValue(); 7667 LLVM_FALLTHROUGH; 7668 case ISD::ADD: 7669 case ISD::SUB: 7670 break; 7671 } 7672 7673 // Only handle cases where the result is used by a CopyToReg. That likely 7674 // means the value is a liveout of the basic block. This helps prevent 7675 // infinite combine loops like PR51206. 7676 if (none_of(N->uses(), 7677 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7678 return SDValue(); 7679 7680 SmallVector<SDNode *, 4> SetCCs; 7681 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7682 UE = Src.getNode()->use_end(); 7683 UI != UE; ++UI) { 7684 SDNode *User = *UI; 7685 if (User == N) 7686 continue; 7687 if (UI.getUse().getResNo() != Src.getResNo()) 7688 continue; 7689 // All i32 setccs are legalized by sign extending operands. 7690 if (User->getOpcode() == ISD::SETCC) { 7691 SetCCs.push_back(User); 7692 continue; 7693 } 7694 // We don't know if we can extend this user. 7695 break; 7696 } 7697 7698 // If we don't have any SetCCs, this isn't worthwhile. 7699 if (SetCCs.empty()) 7700 return SDValue(); 7701 7702 SDLoc DL(N); 7703 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7704 DCI.CombineTo(N, SExt); 7705 7706 // Promote all the setccs. 7707 for (SDNode *SetCC : SetCCs) { 7708 SmallVector<SDValue, 4> Ops; 7709 7710 for (unsigned j = 0; j != 2; ++j) { 7711 SDValue SOp = SetCC->getOperand(j); 7712 if (SOp == Src) 7713 Ops.push_back(SExt); 7714 else 7715 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7716 } 7717 7718 Ops.push_back(SetCC->getOperand(2)); 7719 DCI.CombineTo(SetCC, 7720 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7721 } 7722 return SDValue(N, 0); 7723 } 7724 7725 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7726 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7727 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7728 bool Commute = false) { 7729 assert((N->getOpcode() == RISCVISD::ADD_VL || 7730 N->getOpcode() == RISCVISD::SUB_VL) && 7731 "Unexpected opcode"); 7732 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7733 SDValue Op0 = N->getOperand(0); 7734 SDValue Op1 = N->getOperand(1); 7735 if (Commute) 7736 std::swap(Op0, Op1); 7737 7738 MVT VT = N->getSimpleValueType(0); 7739 7740 // Determine the narrow size for a widening add/sub. 7741 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7742 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7743 VT.getVectorElementCount()); 7744 7745 SDValue Mask = N->getOperand(2); 7746 SDValue VL = N->getOperand(3); 7747 7748 SDLoc DL(N); 7749 7750 // If the RHS is a sext or zext, we can form a widening op. 7751 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7752 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7753 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7754 unsigned ExtOpc = Op1.getOpcode(); 7755 Op1 = Op1.getOperand(0); 7756 // Re-introduce narrower extends if needed. 7757 if (Op1.getValueType() != NarrowVT) 7758 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7759 7760 unsigned WOpc; 7761 if (ExtOpc == RISCVISD::VSEXT_VL) 7762 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7763 else 7764 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7765 7766 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7767 } 7768 7769 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7770 // sext/zext? 7771 7772 return SDValue(); 7773 } 7774 7775 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7776 // vwsub(u).vv/vx. 7777 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7778 SDValue Op0 = N->getOperand(0); 7779 SDValue Op1 = N->getOperand(1); 7780 SDValue Mask = N->getOperand(2); 7781 SDValue VL = N->getOperand(3); 7782 7783 MVT VT = N->getSimpleValueType(0); 7784 MVT NarrowVT = Op1.getSimpleValueType(); 7785 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7786 7787 unsigned VOpc; 7788 switch (N->getOpcode()) { 7789 default: llvm_unreachable("Unexpected opcode"); 7790 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7791 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7792 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7793 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7794 } 7795 7796 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7797 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7798 7799 SDLoc DL(N); 7800 7801 // If the LHS is a sext or zext, we can narrow this op to the same size as 7802 // the RHS. 7803 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7804 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7805 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7806 unsigned ExtOpc = Op0.getOpcode(); 7807 Op0 = Op0.getOperand(0); 7808 // Re-introduce narrower extends if needed. 7809 if (Op0.getValueType() != NarrowVT) 7810 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7811 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7812 } 7813 7814 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7815 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7816 7817 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7818 // to commute and use a vwadd(u).vx instead. 7819 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7820 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 7821 Op0 = Op0.getOperand(1); 7822 7823 // See if have enough sign bits or zero bits in the scalar to use a 7824 // widening add/sub by splatting to smaller element size. 7825 unsigned EltBits = VT.getScalarSizeInBits(); 7826 unsigned ScalarBits = Op0.getValueSizeInBits(); 7827 // Make sure we're getting all element bits from the scalar register. 7828 // FIXME: Support implicit sign extension of vmv.v.x? 7829 if (ScalarBits < EltBits) 7830 return SDValue(); 7831 7832 if (IsSigned) { 7833 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7834 return SDValue(); 7835 } else { 7836 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7837 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7838 return SDValue(); 7839 } 7840 7841 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7842 DAG.getUNDEF(NarrowVT), Op0, VL); 7843 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7844 } 7845 7846 return SDValue(); 7847 } 7848 7849 // Try to form VWMUL, VWMULU or VWMULSU. 7850 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7851 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7852 bool Commute) { 7853 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7854 SDValue Op0 = N->getOperand(0); 7855 SDValue Op1 = N->getOperand(1); 7856 if (Commute) 7857 std::swap(Op0, Op1); 7858 7859 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7860 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7861 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7862 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7863 return SDValue(); 7864 7865 SDValue Mask = N->getOperand(2); 7866 SDValue VL = N->getOperand(3); 7867 7868 // Make sure the mask and VL match. 7869 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7870 return SDValue(); 7871 7872 MVT VT = N->getSimpleValueType(0); 7873 7874 // Determine the narrow size for a widening multiply. 7875 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7876 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7877 VT.getVectorElementCount()); 7878 7879 SDLoc DL(N); 7880 7881 // See if the other operand is the same opcode. 7882 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7883 if (!Op1.hasOneUse()) 7884 return SDValue(); 7885 7886 // Make sure the mask and VL match. 7887 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7888 return SDValue(); 7889 7890 Op1 = Op1.getOperand(0); 7891 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7892 // The operand is a splat of a scalar. 7893 7894 // The pasthru must be undef for tail agnostic 7895 if (!Op1.getOperand(0).isUndef()) 7896 return SDValue(); 7897 // The VL must be the same. 7898 if (Op1.getOperand(2) != VL) 7899 return SDValue(); 7900 7901 // Get the scalar value. 7902 Op1 = Op1.getOperand(1); 7903 7904 // See if have enough sign bits or zero bits in the scalar to use a 7905 // widening multiply by splatting to smaller element size. 7906 unsigned EltBits = VT.getScalarSizeInBits(); 7907 unsigned ScalarBits = Op1.getValueSizeInBits(); 7908 // Make sure we're getting all element bits from the scalar register. 7909 // FIXME: Support implicit sign extension of vmv.v.x? 7910 if (ScalarBits < EltBits) 7911 return SDValue(); 7912 7913 // If the LHS is a sign extend, try to use vwmul. 7914 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 7915 // Can use vwmul. 7916 } else { 7917 // Otherwise try to use vwmulu or vwmulsu. 7918 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7919 if (DAG.MaskedValueIsZero(Op1, Mask)) 7920 IsVWMULSU = IsSignExt; 7921 else 7922 return SDValue(); 7923 } 7924 7925 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 7926 DAG.getUNDEF(NarrowVT), Op1, VL); 7927 } else 7928 return SDValue(); 7929 7930 Op0 = Op0.getOperand(0); 7931 7932 // Re-introduce narrower extends if needed. 7933 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7934 if (Op0.getValueType() != NarrowVT) 7935 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7936 // vwmulsu requires second operand to be zero extended. 7937 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 7938 if (Op1.getValueType() != NarrowVT) 7939 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7940 7941 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7942 if (!IsVWMULSU) 7943 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7944 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7945 } 7946 7947 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7948 switch (Op.getOpcode()) { 7949 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7950 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7951 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7952 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7953 case ISD::FROUND: return RISCVFPRndMode::RMM; 7954 } 7955 7956 return RISCVFPRndMode::Invalid; 7957 } 7958 7959 // Fold 7960 // (fp_to_int (froundeven X)) -> fcvt X, rne 7961 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7962 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7963 // (fp_to_int (fceil X)) -> fcvt X, rup 7964 // (fp_to_int (fround X)) -> fcvt X, rmm 7965 static SDValue performFP_TO_INTCombine(SDNode *N, 7966 TargetLowering::DAGCombinerInfo &DCI, 7967 const RISCVSubtarget &Subtarget) { 7968 SelectionDAG &DAG = DCI.DAG; 7969 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7970 MVT XLenVT = Subtarget.getXLenVT(); 7971 7972 // Only handle XLen or i32 types. Other types narrower than XLen will 7973 // eventually be legalized to XLenVT. 7974 EVT VT = N->getValueType(0); 7975 if (VT != MVT::i32 && VT != XLenVT) 7976 return SDValue(); 7977 7978 SDValue Src = N->getOperand(0); 7979 7980 // Ensure the FP type is also legal. 7981 if (!TLI.isTypeLegal(Src.getValueType())) 7982 return SDValue(); 7983 7984 // Don't do this for f16 with Zfhmin and not Zfh. 7985 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7986 return SDValue(); 7987 7988 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7989 if (FRM == RISCVFPRndMode::Invalid) 7990 return SDValue(); 7991 7992 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7993 7994 unsigned Opc; 7995 if (VT == XLenVT) 7996 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7997 else 7998 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7999 8000 SDLoc DL(N); 8001 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8002 DAG.getTargetConstant(FRM, DL, XLenVT)); 8003 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8004 } 8005 8006 // Fold 8007 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8008 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8009 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8010 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8011 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8012 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8013 TargetLowering::DAGCombinerInfo &DCI, 8014 const RISCVSubtarget &Subtarget) { 8015 SelectionDAG &DAG = DCI.DAG; 8016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8017 MVT XLenVT = Subtarget.getXLenVT(); 8018 8019 // Only handle XLen types. Other types narrower than XLen will eventually be 8020 // legalized to XLenVT. 8021 EVT DstVT = N->getValueType(0); 8022 if (DstVT != XLenVT) 8023 return SDValue(); 8024 8025 SDValue Src = N->getOperand(0); 8026 8027 // Ensure the FP type is also legal. 8028 if (!TLI.isTypeLegal(Src.getValueType())) 8029 return SDValue(); 8030 8031 // Don't do this for f16 with Zfhmin and not Zfh. 8032 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8033 return SDValue(); 8034 8035 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8036 8037 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8038 if (FRM == RISCVFPRndMode::Invalid) 8039 return SDValue(); 8040 8041 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8042 8043 unsigned Opc; 8044 if (SatVT == DstVT) 8045 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8046 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8047 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8048 else 8049 return SDValue(); 8050 // FIXME: Support other SatVTs by clamping before or after the conversion. 8051 8052 Src = Src.getOperand(0); 8053 8054 SDLoc DL(N); 8055 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8056 DAG.getTargetConstant(FRM, DL, XLenVT)); 8057 8058 // RISCV FP-to-int conversions saturate to the destination register size, but 8059 // don't produce 0 for nan. 8060 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8061 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8062 } 8063 8064 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8065 DAGCombinerInfo &DCI) const { 8066 SelectionDAG &DAG = DCI.DAG; 8067 8068 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8069 // bits are demanded. N will be added to the Worklist if it was not deleted. 8070 // Caller should return SDValue(N, 0) if this returns true. 8071 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8072 SDValue Op = N->getOperand(OpNo); 8073 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8074 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8075 return false; 8076 8077 if (N->getOpcode() != ISD::DELETED_NODE) 8078 DCI.AddToWorklist(N); 8079 return true; 8080 }; 8081 8082 switch (N->getOpcode()) { 8083 default: 8084 break; 8085 case RISCVISD::SplitF64: { 8086 SDValue Op0 = N->getOperand(0); 8087 // If the input to SplitF64 is just BuildPairF64 then the operation is 8088 // redundant. Instead, use BuildPairF64's operands directly. 8089 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8090 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8091 8092 if (Op0->isUndef()) { 8093 SDValue Lo = DAG.getUNDEF(MVT::i32); 8094 SDValue Hi = DAG.getUNDEF(MVT::i32); 8095 return DCI.CombineTo(N, Lo, Hi); 8096 } 8097 8098 SDLoc DL(N); 8099 8100 // It's cheaper to materialise two 32-bit integers than to load a double 8101 // from the constant pool and transfer it to integer registers through the 8102 // stack. 8103 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8104 APInt V = C->getValueAPF().bitcastToAPInt(); 8105 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8106 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8107 return DCI.CombineTo(N, Lo, Hi); 8108 } 8109 8110 // This is a target-specific version of a DAGCombine performed in 8111 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8112 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8113 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8114 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8115 !Op0.getNode()->hasOneUse()) 8116 break; 8117 SDValue NewSplitF64 = 8118 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8119 Op0.getOperand(0)); 8120 SDValue Lo = NewSplitF64.getValue(0); 8121 SDValue Hi = NewSplitF64.getValue(1); 8122 APInt SignBit = APInt::getSignMask(32); 8123 if (Op0.getOpcode() == ISD::FNEG) { 8124 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8125 DAG.getConstant(SignBit, DL, MVT::i32)); 8126 return DCI.CombineTo(N, Lo, NewHi); 8127 } 8128 assert(Op0.getOpcode() == ISD::FABS); 8129 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8130 DAG.getConstant(~SignBit, DL, MVT::i32)); 8131 return DCI.CombineTo(N, Lo, NewHi); 8132 } 8133 case RISCVISD::SLLW: 8134 case RISCVISD::SRAW: 8135 case RISCVISD::SRLW: { 8136 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8137 if (SimplifyDemandedLowBitsHelper(0, 32) || 8138 SimplifyDemandedLowBitsHelper(1, 5)) 8139 return SDValue(N, 0); 8140 8141 break; 8142 } 8143 case ISD::ROTR: 8144 case ISD::ROTL: 8145 case RISCVISD::RORW: 8146 case RISCVISD::ROLW: { 8147 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8148 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8149 if (SimplifyDemandedLowBitsHelper(0, 32) || 8150 SimplifyDemandedLowBitsHelper(1, 5)) 8151 return SDValue(N, 0); 8152 } 8153 8154 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8155 } 8156 case RISCVISD::CLZW: 8157 case RISCVISD::CTZW: { 8158 // Only the lower 32 bits of the first operand are read 8159 if (SimplifyDemandedLowBitsHelper(0, 32)) 8160 return SDValue(N, 0); 8161 break; 8162 } 8163 case RISCVISD::GREV: 8164 case RISCVISD::GORC: { 8165 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8166 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8167 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8168 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8169 return SDValue(N, 0); 8170 8171 return combineGREVI_GORCI(N, DAG); 8172 } 8173 case RISCVISD::GREVW: 8174 case RISCVISD::GORCW: { 8175 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8176 if (SimplifyDemandedLowBitsHelper(0, 32) || 8177 SimplifyDemandedLowBitsHelper(1, 5)) 8178 return SDValue(N, 0); 8179 8180 return combineGREVI_GORCI(N, DAG); 8181 } 8182 case RISCVISD::SHFL: 8183 case RISCVISD::UNSHFL: { 8184 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8185 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8186 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8187 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8188 return SDValue(N, 0); 8189 8190 break; 8191 } 8192 case RISCVISD::SHFLW: 8193 case RISCVISD::UNSHFLW: { 8194 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8195 if (SimplifyDemandedLowBitsHelper(0, 32) || 8196 SimplifyDemandedLowBitsHelper(1, 4)) 8197 return SDValue(N, 0); 8198 8199 break; 8200 } 8201 case RISCVISD::BCOMPRESSW: 8202 case RISCVISD::BDECOMPRESSW: { 8203 // Only the lower 32 bits of LHS and RHS are read. 8204 if (SimplifyDemandedLowBitsHelper(0, 32) || 8205 SimplifyDemandedLowBitsHelper(1, 32)) 8206 return SDValue(N, 0); 8207 8208 break; 8209 } 8210 case RISCVISD::FSR: 8211 case RISCVISD::FSL: 8212 case RISCVISD::FSRW: 8213 case RISCVISD::FSLW: { 8214 bool IsWInstruction = 8215 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8216 unsigned BitWidth = 8217 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8218 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8219 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8220 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8221 return SDValue(N, 0); 8222 8223 break; 8224 } 8225 case RISCVISD::FMV_X_ANYEXTH: 8226 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8227 SDLoc DL(N); 8228 SDValue Op0 = N->getOperand(0); 8229 MVT VT = N->getSimpleValueType(0); 8230 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8231 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8232 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8233 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8234 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8235 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8236 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8237 assert(Op0.getOperand(0).getValueType() == VT && 8238 "Unexpected value type!"); 8239 return Op0.getOperand(0); 8240 } 8241 8242 // This is a target-specific version of a DAGCombine performed in 8243 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8244 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8245 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8246 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8247 !Op0.getNode()->hasOneUse()) 8248 break; 8249 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8250 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8251 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8252 if (Op0.getOpcode() == ISD::FNEG) 8253 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8254 DAG.getConstant(SignBit, DL, VT)); 8255 8256 assert(Op0.getOpcode() == ISD::FABS); 8257 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8258 DAG.getConstant(~SignBit, DL, VT)); 8259 } 8260 case ISD::ADD: 8261 return performADDCombine(N, DAG, Subtarget); 8262 case ISD::SUB: 8263 return performSUBCombine(N, DAG); 8264 case ISD::AND: 8265 return performANDCombine(N, DAG); 8266 case ISD::OR: 8267 return performORCombine(N, DAG, Subtarget); 8268 case ISD::XOR: 8269 return performXORCombine(N, DAG); 8270 case ISD::SIGN_EXTEND_INREG: 8271 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8272 case ISD::ANY_EXTEND: 8273 return performANY_EXTENDCombine(N, DCI, Subtarget); 8274 case ISD::ZERO_EXTEND: 8275 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8276 // type legalization. This is safe because fp_to_uint produces poison if 8277 // it overflows. 8278 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8279 SDValue Src = N->getOperand(0); 8280 if (Src.getOpcode() == ISD::FP_TO_UINT && 8281 isTypeLegal(Src.getOperand(0).getValueType())) 8282 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8283 Src.getOperand(0)); 8284 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8285 isTypeLegal(Src.getOperand(1).getValueType())) { 8286 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8287 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8288 Src.getOperand(0), Src.getOperand(1)); 8289 DCI.CombineTo(N, Res); 8290 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8291 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8292 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8293 } 8294 } 8295 return SDValue(); 8296 case RISCVISD::SELECT_CC: { 8297 // Transform 8298 SDValue LHS = N->getOperand(0); 8299 SDValue RHS = N->getOperand(1); 8300 SDValue TrueV = N->getOperand(3); 8301 SDValue FalseV = N->getOperand(4); 8302 8303 // If the True and False values are the same, we don't need a select_cc. 8304 if (TrueV == FalseV) 8305 return TrueV; 8306 8307 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8308 if (!ISD::isIntEqualitySetCC(CCVal)) 8309 break; 8310 8311 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8312 // (select_cc X, Y, lt, trueV, falseV) 8313 // Sometimes the setcc is introduced after select_cc has been formed. 8314 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8315 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8316 // If we're looking for eq 0 instead of ne 0, we need to invert the 8317 // condition. 8318 bool Invert = CCVal == ISD::SETEQ; 8319 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8320 if (Invert) 8321 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8322 8323 SDLoc DL(N); 8324 RHS = LHS.getOperand(1); 8325 LHS = LHS.getOperand(0); 8326 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8327 8328 SDValue TargetCC = DAG.getCondCode(CCVal); 8329 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8330 {LHS, RHS, TargetCC, TrueV, FalseV}); 8331 } 8332 8333 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8334 // (select_cc X, Y, eq/ne, trueV, falseV) 8335 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8336 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8337 {LHS.getOperand(0), LHS.getOperand(1), 8338 N->getOperand(2), TrueV, FalseV}); 8339 // (select_cc X, 1, setne, trueV, falseV) -> 8340 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8341 // This can occur when legalizing some floating point comparisons. 8342 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8343 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8344 SDLoc DL(N); 8345 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8346 SDValue TargetCC = DAG.getCondCode(CCVal); 8347 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8348 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8349 {LHS, RHS, TargetCC, TrueV, FalseV}); 8350 } 8351 8352 break; 8353 } 8354 case RISCVISD::BR_CC: { 8355 SDValue LHS = N->getOperand(1); 8356 SDValue RHS = N->getOperand(2); 8357 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8358 if (!ISD::isIntEqualitySetCC(CCVal)) 8359 break; 8360 8361 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8362 // (br_cc X, Y, lt, dest) 8363 // Sometimes the setcc is introduced after br_cc has been formed. 8364 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8365 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8366 // If we're looking for eq 0 instead of ne 0, we need to invert the 8367 // condition. 8368 bool Invert = CCVal == ISD::SETEQ; 8369 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8370 if (Invert) 8371 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8372 8373 SDLoc DL(N); 8374 RHS = LHS.getOperand(1); 8375 LHS = LHS.getOperand(0); 8376 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8377 8378 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8379 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8380 N->getOperand(4)); 8381 } 8382 8383 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8384 // (br_cc X, Y, eq/ne, trueV, falseV) 8385 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8386 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8387 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8388 N->getOperand(3), N->getOperand(4)); 8389 8390 // (br_cc X, 1, setne, br_cc) -> 8391 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8392 // This can occur when legalizing some floating point comparisons. 8393 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8394 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8395 SDLoc DL(N); 8396 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8397 SDValue TargetCC = DAG.getCondCode(CCVal); 8398 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8399 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8400 N->getOperand(0), LHS, RHS, TargetCC, 8401 N->getOperand(4)); 8402 } 8403 break; 8404 } 8405 case ISD::FP_TO_SINT: 8406 case ISD::FP_TO_UINT: 8407 return performFP_TO_INTCombine(N, DCI, Subtarget); 8408 case ISD::FP_TO_SINT_SAT: 8409 case ISD::FP_TO_UINT_SAT: 8410 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8411 case ISD::FCOPYSIGN: { 8412 EVT VT = N->getValueType(0); 8413 if (!VT.isVector()) 8414 break; 8415 // There is a form of VFSGNJ which injects the negated sign of its second 8416 // operand. Try and bubble any FNEG up after the extend/round to produce 8417 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8418 // TRUNC=1. 8419 SDValue In2 = N->getOperand(1); 8420 // Avoid cases where the extend/round has multiple uses, as duplicating 8421 // those is typically more expensive than removing a fneg. 8422 if (!In2.hasOneUse()) 8423 break; 8424 if (In2.getOpcode() != ISD::FP_EXTEND && 8425 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8426 break; 8427 In2 = In2.getOperand(0); 8428 if (In2.getOpcode() != ISD::FNEG) 8429 break; 8430 SDLoc DL(N); 8431 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8432 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8433 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8434 } 8435 case ISD::MGATHER: 8436 case ISD::MSCATTER: 8437 case ISD::VP_GATHER: 8438 case ISD::VP_SCATTER: { 8439 if (!DCI.isBeforeLegalize()) 8440 break; 8441 SDValue Index, ScaleOp; 8442 bool IsIndexScaled = false; 8443 bool IsIndexSigned = false; 8444 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8445 Index = VPGSN->getIndex(); 8446 ScaleOp = VPGSN->getScale(); 8447 IsIndexScaled = VPGSN->isIndexScaled(); 8448 IsIndexSigned = VPGSN->isIndexSigned(); 8449 } else { 8450 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8451 Index = MGSN->getIndex(); 8452 ScaleOp = MGSN->getScale(); 8453 IsIndexScaled = MGSN->isIndexScaled(); 8454 IsIndexSigned = MGSN->isIndexSigned(); 8455 } 8456 EVT IndexVT = Index.getValueType(); 8457 MVT XLenVT = Subtarget.getXLenVT(); 8458 // RISCV indexed loads only support the "unsigned unscaled" addressing 8459 // mode, so anything else must be manually legalized. 8460 bool NeedsIdxLegalization = 8461 IsIndexScaled || 8462 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8463 if (!NeedsIdxLegalization) 8464 break; 8465 8466 SDLoc DL(N); 8467 8468 // Any index legalization should first promote to XLenVT, so we don't lose 8469 // bits when scaling. This may create an illegal index type so we let 8470 // LLVM's legalization take care of the splitting. 8471 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8472 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8473 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8474 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8475 DL, IndexVT, Index); 8476 } 8477 8478 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8479 if (IsIndexScaled && Scale != 1) { 8480 // Manually scale the indices by the element size. 8481 // TODO: Sanitize the scale operand here? 8482 // TODO: For VP nodes, should we use VP_SHL here? 8483 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8484 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8485 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8486 } 8487 8488 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8489 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8490 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8491 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8492 VPGN->getScale(), VPGN->getMask(), 8493 VPGN->getVectorLength()}, 8494 VPGN->getMemOperand(), NewIndexTy); 8495 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8496 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8497 {VPSN->getChain(), VPSN->getValue(), 8498 VPSN->getBasePtr(), Index, VPSN->getScale(), 8499 VPSN->getMask(), VPSN->getVectorLength()}, 8500 VPSN->getMemOperand(), NewIndexTy); 8501 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8502 return DAG.getMaskedGather( 8503 N->getVTList(), MGN->getMemoryVT(), DL, 8504 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8505 MGN->getBasePtr(), Index, MGN->getScale()}, 8506 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8507 const auto *MSN = cast<MaskedScatterSDNode>(N); 8508 return DAG.getMaskedScatter( 8509 N->getVTList(), MSN->getMemoryVT(), DL, 8510 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8511 Index, MSN->getScale()}, 8512 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8513 } 8514 case RISCVISD::SRA_VL: 8515 case RISCVISD::SRL_VL: 8516 case RISCVISD::SHL_VL: { 8517 SDValue ShAmt = N->getOperand(1); 8518 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8519 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8520 SDLoc DL(N); 8521 SDValue VL = N->getOperand(3); 8522 EVT VT = N->getValueType(0); 8523 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8524 ShAmt.getOperand(1), VL); 8525 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8526 N->getOperand(2), N->getOperand(3)); 8527 } 8528 break; 8529 } 8530 case ISD::SRA: 8531 case ISD::SRL: 8532 case ISD::SHL: { 8533 SDValue ShAmt = N->getOperand(1); 8534 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8535 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8536 SDLoc DL(N); 8537 EVT VT = N->getValueType(0); 8538 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8539 ShAmt.getOperand(1), 8540 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8541 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8542 } 8543 break; 8544 } 8545 case RISCVISD::ADD_VL: 8546 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8547 return V; 8548 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8549 case RISCVISD::SUB_VL: 8550 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8551 case RISCVISD::VWADD_W_VL: 8552 case RISCVISD::VWADDU_W_VL: 8553 case RISCVISD::VWSUB_W_VL: 8554 case RISCVISD::VWSUBU_W_VL: 8555 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8556 case RISCVISD::MUL_VL: 8557 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8558 return V; 8559 // Mul is commutative. 8560 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8561 case ISD::STORE: { 8562 auto *Store = cast<StoreSDNode>(N); 8563 SDValue Val = Store->getValue(); 8564 // Combine store of vmv.x.s to vse with VL of 1. 8565 // FIXME: Support FP. 8566 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8567 SDValue Src = Val.getOperand(0); 8568 EVT VecVT = Src.getValueType(); 8569 EVT MemVT = Store->getMemoryVT(); 8570 // The memory VT and the element type must match. 8571 if (VecVT.getVectorElementType() == MemVT) { 8572 SDLoc DL(N); 8573 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8574 return DAG.getStoreVP( 8575 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8576 DAG.getConstant(1, DL, MaskVT), 8577 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8578 Store->getMemOperand(), Store->getAddressingMode(), 8579 Store->isTruncatingStore(), /*IsCompress*/ false); 8580 } 8581 } 8582 8583 break; 8584 } 8585 case ISD::SPLAT_VECTOR: { 8586 EVT VT = N->getValueType(0); 8587 // Only perform this combine on legal MVT types. 8588 if (!isTypeLegal(VT)) 8589 break; 8590 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8591 DAG, Subtarget)) 8592 return Gather; 8593 break; 8594 } 8595 case RISCVISD::VMV_V_X_VL: { 8596 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8597 // scalar input. 8598 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8599 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8600 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8601 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8602 return SDValue(N, 0); 8603 8604 break; 8605 } 8606 case ISD::INTRINSIC_WO_CHAIN: { 8607 unsigned IntNo = N->getConstantOperandVal(0); 8608 switch (IntNo) { 8609 // By default we do not combine any intrinsic. 8610 default: 8611 return SDValue(); 8612 case Intrinsic::riscv_vcpop: 8613 case Intrinsic::riscv_vcpop_mask: 8614 case Intrinsic::riscv_vfirst: 8615 case Intrinsic::riscv_vfirst_mask: { 8616 SDValue VL = N->getOperand(2); 8617 if (IntNo == Intrinsic::riscv_vcpop_mask || 8618 IntNo == Intrinsic::riscv_vfirst_mask) 8619 VL = N->getOperand(3); 8620 if (!isNullConstant(VL)) 8621 return SDValue(); 8622 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8623 SDLoc DL(N); 8624 EVT VT = N->getValueType(0); 8625 if (IntNo == Intrinsic::riscv_vfirst || 8626 IntNo == Intrinsic::riscv_vfirst_mask) 8627 return DAG.getConstant(-1, DL, VT); 8628 return DAG.getConstant(0, DL, VT); 8629 } 8630 } 8631 } 8632 } 8633 8634 return SDValue(); 8635 } 8636 8637 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8638 const SDNode *N, CombineLevel Level) const { 8639 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8640 // materialised in fewer instructions than `(OP _, c1)`: 8641 // 8642 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8643 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8644 SDValue N0 = N->getOperand(0); 8645 EVT Ty = N0.getValueType(); 8646 if (Ty.isScalarInteger() && 8647 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8648 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8649 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8650 if (C1 && C2) { 8651 const APInt &C1Int = C1->getAPIntValue(); 8652 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8653 8654 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8655 // and the combine should happen, to potentially allow further combines 8656 // later. 8657 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8658 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8659 return true; 8660 8661 // We can materialise `c1` in an add immediate, so it's "free", and the 8662 // combine should be prevented. 8663 if (C1Int.getMinSignedBits() <= 64 && 8664 isLegalAddImmediate(C1Int.getSExtValue())) 8665 return false; 8666 8667 // Neither constant will fit into an immediate, so find materialisation 8668 // costs. 8669 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8670 Subtarget.getFeatureBits(), 8671 /*CompressionCost*/true); 8672 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8673 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8674 /*CompressionCost*/true); 8675 8676 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8677 // combine should be prevented. 8678 if (C1Cost < ShiftedC1Cost) 8679 return false; 8680 } 8681 } 8682 return true; 8683 } 8684 8685 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8686 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8687 TargetLoweringOpt &TLO) const { 8688 // Delay this optimization as late as possible. 8689 if (!TLO.LegalOps) 8690 return false; 8691 8692 EVT VT = Op.getValueType(); 8693 if (VT.isVector()) 8694 return false; 8695 8696 // Only handle AND for now. 8697 if (Op.getOpcode() != ISD::AND) 8698 return false; 8699 8700 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8701 if (!C) 8702 return false; 8703 8704 const APInt &Mask = C->getAPIntValue(); 8705 8706 // Clear all non-demanded bits initially. 8707 APInt ShrunkMask = Mask & DemandedBits; 8708 8709 // Try to make a smaller immediate by setting undemanded bits. 8710 8711 APInt ExpandedMask = Mask | ~DemandedBits; 8712 8713 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8714 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8715 }; 8716 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8717 if (NewMask == Mask) 8718 return true; 8719 SDLoc DL(Op); 8720 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8721 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8722 return TLO.CombineTo(Op, NewOp); 8723 }; 8724 8725 // If the shrunk mask fits in sign extended 12 bits, let the target 8726 // independent code apply it. 8727 if (ShrunkMask.isSignedIntN(12)) 8728 return false; 8729 8730 // Preserve (and X, 0xffff) when zext.h is supported. 8731 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8732 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8733 if (IsLegalMask(NewMask)) 8734 return UseMask(NewMask); 8735 } 8736 8737 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8738 if (VT == MVT::i64) { 8739 APInt NewMask = APInt(64, 0xffffffff); 8740 if (IsLegalMask(NewMask)) 8741 return UseMask(NewMask); 8742 } 8743 8744 // For the remaining optimizations, we need to be able to make a negative 8745 // number through a combination of mask and undemanded bits. 8746 if (!ExpandedMask.isNegative()) 8747 return false; 8748 8749 // What is the fewest number of bits we need to represent the negative number. 8750 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8751 8752 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8753 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8754 APInt NewMask = ShrunkMask; 8755 if (MinSignedBits <= 12) 8756 NewMask.setBitsFrom(11); 8757 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8758 NewMask.setBitsFrom(31); 8759 else 8760 return false; 8761 8762 // Check that our new mask is a subset of the demanded mask. 8763 assert(IsLegalMask(NewMask)); 8764 return UseMask(NewMask); 8765 } 8766 8767 static void computeGREV(APInt &Src, unsigned ShAmt) { 8768 ShAmt &= Src.getBitWidth() - 1; 8769 uint64_t x = Src.getZExtValue(); 8770 if (ShAmt & 1) 8771 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8772 if (ShAmt & 2) 8773 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8774 if (ShAmt & 4) 8775 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8776 if (ShAmt & 8) 8777 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8778 if (ShAmt & 16) 8779 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8780 if (ShAmt & 32) 8781 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8782 Src = x; 8783 } 8784 8785 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8786 KnownBits &Known, 8787 const APInt &DemandedElts, 8788 const SelectionDAG &DAG, 8789 unsigned Depth) const { 8790 unsigned BitWidth = Known.getBitWidth(); 8791 unsigned Opc = Op.getOpcode(); 8792 assert((Opc >= ISD::BUILTIN_OP_END || 8793 Opc == ISD::INTRINSIC_WO_CHAIN || 8794 Opc == ISD::INTRINSIC_W_CHAIN || 8795 Opc == ISD::INTRINSIC_VOID) && 8796 "Should use MaskedValueIsZero if you don't know whether Op" 8797 " is a target node!"); 8798 8799 Known.resetAll(); 8800 switch (Opc) { 8801 default: break; 8802 case RISCVISD::SELECT_CC: { 8803 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8804 // If we don't know any bits, early out. 8805 if (Known.isUnknown()) 8806 break; 8807 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8808 8809 // Only known if known in both the LHS and RHS. 8810 Known = KnownBits::commonBits(Known, Known2); 8811 break; 8812 } 8813 case RISCVISD::REMUW: { 8814 KnownBits Known2; 8815 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8816 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8817 // We only care about the lower 32 bits. 8818 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8819 // Restore the original width by sign extending. 8820 Known = Known.sext(BitWidth); 8821 break; 8822 } 8823 case RISCVISD::DIVUW: { 8824 KnownBits Known2; 8825 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8826 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8827 // We only care about the lower 32 bits. 8828 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8829 // Restore the original width by sign extending. 8830 Known = Known.sext(BitWidth); 8831 break; 8832 } 8833 case RISCVISD::CTZW: { 8834 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8835 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8836 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8837 Known.Zero.setBitsFrom(LowBits); 8838 break; 8839 } 8840 case RISCVISD::CLZW: { 8841 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8842 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8843 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8844 Known.Zero.setBitsFrom(LowBits); 8845 break; 8846 } 8847 case RISCVISD::GREV: 8848 case RISCVISD::GREVW: { 8849 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8850 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8851 if (Opc == RISCVISD::GREVW) 8852 Known = Known.trunc(32); 8853 unsigned ShAmt = C->getZExtValue(); 8854 computeGREV(Known.Zero, ShAmt); 8855 computeGREV(Known.One, ShAmt); 8856 if (Opc == RISCVISD::GREVW) 8857 Known = Known.sext(BitWidth); 8858 } 8859 break; 8860 } 8861 case RISCVISD::READ_VLENB: { 8862 // If we know the minimum VLen from Zvl extensions, we can use that to 8863 // determine the trailing zeros of VLENB. 8864 // FIXME: Limit to 128 bit vectors until we have more testing. 8865 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8866 if (MinVLenB > 0) 8867 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8868 // We assume VLENB is no more than 65536 / 8 bytes. 8869 Known.Zero.setBitsFrom(14); 8870 break; 8871 } 8872 case ISD::INTRINSIC_W_CHAIN: 8873 case ISD::INTRINSIC_WO_CHAIN: { 8874 unsigned IntNo = 8875 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8876 switch (IntNo) { 8877 default: 8878 // We can't do anything for most intrinsics. 8879 break; 8880 case Intrinsic::riscv_vsetvli: 8881 case Intrinsic::riscv_vsetvlimax: 8882 case Intrinsic::riscv_vsetvli_opt: 8883 case Intrinsic::riscv_vsetvlimax_opt: 8884 // Assume that VL output is positive and would fit in an int32_t. 8885 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8886 if (BitWidth >= 32) 8887 Known.Zero.setBitsFrom(31); 8888 break; 8889 } 8890 break; 8891 } 8892 } 8893 } 8894 8895 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8896 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8897 unsigned Depth) const { 8898 switch (Op.getOpcode()) { 8899 default: 8900 break; 8901 case RISCVISD::SELECT_CC: { 8902 unsigned Tmp = 8903 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8904 if (Tmp == 1) return 1; // Early out. 8905 unsigned Tmp2 = 8906 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8907 return std::min(Tmp, Tmp2); 8908 } 8909 case RISCVISD::SLLW: 8910 case RISCVISD::SRAW: 8911 case RISCVISD::SRLW: 8912 case RISCVISD::DIVW: 8913 case RISCVISD::DIVUW: 8914 case RISCVISD::REMUW: 8915 case RISCVISD::ROLW: 8916 case RISCVISD::RORW: 8917 case RISCVISD::GREVW: 8918 case RISCVISD::GORCW: 8919 case RISCVISD::FSLW: 8920 case RISCVISD::FSRW: 8921 case RISCVISD::SHFLW: 8922 case RISCVISD::UNSHFLW: 8923 case RISCVISD::BCOMPRESSW: 8924 case RISCVISD::BDECOMPRESSW: 8925 case RISCVISD::BFPW: 8926 case RISCVISD::FCVT_W_RV64: 8927 case RISCVISD::FCVT_WU_RV64: 8928 case RISCVISD::STRICT_FCVT_W_RV64: 8929 case RISCVISD::STRICT_FCVT_WU_RV64: 8930 // TODO: As the result is sign-extended, this is conservatively correct. A 8931 // more precise answer could be calculated for SRAW depending on known 8932 // bits in the shift amount. 8933 return 33; 8934 case RISCVISD::SHFL: 8935 case RISCVISD::UNSHFL: { 8936 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8937 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8938 // will stay within the upper 32 bits. If there were more than 32 sign bits 8939 // before there will be at least 33 sign bits after. 8940 if (Op.getValueType() == MVT::i64 && 8941 isa<ConstantSDNode>(Op.getOperand(1)) && 8942 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8943 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8944 if (Tmp > 32) 8945 return 33; 8946 } 8947 break; 8948 } 8949 case RISCVISD::VMV_X_S: { 8950 // The number of sign bits of the scalar result is computed by obtaining the 8951 // element type of the input vector operand, subtracting its width from the 8952 // XLEN, and then adding one (sign bit within the element type). If the 8953 // element type is wider than XLen, the least-significant XLEN bits are 8954 // taken. 8955 unsigned XLen = Subtarget.getXLen(); 8956 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8957 if (EltBits <= XLen) 8958 return XLen - EltBits + 1; 8959 break; 8960 } 8961 } 8962 8963 return 1; 8964 } 8965 8966 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8967 MachineBasicBlock *BB) { 8968 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8969 8970 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8971 // Should the count have wrapped while it was being read, we need to try 8972 // again. 8973 // ... 8974 // read: 8975 // rdcycleh x3 # load high word of cycle 8976 // rdcycle x2 # load low word of cycle 8977 // rdcycleh x4 # load high word of cycle 8978 // bne x3, x4, read # check if high word reads match, otherwise try again 8979 // ... 8980 8981 MachineFunction &MF = *BB->getParent(); 8982 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8983 MachineFunction::iterator It = ++BB->getIterator(); 8984 8985 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8986 MF.insert(It, LoopMBB); 8987 8988 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8989 MF.insert(It, DoneMBB); 8990 8991 // Transfer the remainder of BB and its successor edges to DoneMBB. 8992 DoneMBB->splice(DoneMBB->begin(), BB, 8993 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8994 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8995 8996 BB->addSuccessor(LoopMBB); 8997 8998 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8999 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9000 Register LoReg = MI.getOperand(0).getReg(); 9001 Register HiReg = MI.getOperand(1).getReg(); 9002 DebugLoc DL = MI.getDebugLoc(); 9003 9004 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9005 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9006 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9007 .addReg(RISCV::X0); 9008 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9009 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9010 .addReg(RISCV::X0); 9011 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9012 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9013 .addReg(RISCV::X0); 9014 9015 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9016 .addReg(HiReg) 9017 .addReg(ReadAgainReg) 9018 .addMBB(LoopMBB); 9019 9020 LoopMBB->addSuccessor(LoopMBB); 9021 LoopMBB->addSuccessor(DoneMBB); 9022 9023 MI.eraseFromParent(); 9024 9025 return DoneMBB; 9026 } 9027 9028 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9029 MachineBasicBlock *BB) { 9030 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9031 9032 MachineFunction &MF = *BB->getParent(); 9033 DebugLoc DL = MI.getDebugLoc(); 9034 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9035 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9036 Register LoReg = MI.getOperand(0).getReg(); 9037 Register HiReg = MI.getOperand(1).getReg(); 9038 Register SrcReg = MI.getOperand(2).getReg(); 9039 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9040 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9041 9042 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9043 RI); 9044 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9045 MachineMemOperand *MMOLo = 9046 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9047 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9048 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9049 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9050 .addFrameIndex(FI) 9051 .addImm(0) 9052 .addMemOperand(MMOLo); 9053 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9054 .addFrameIndex(FI) 9055 .addImm(4) 9056 .addMemOperand(MMOHi); 9057 MI.eraseFromParent(); // The pseudo instruction is gone now. 9058 return BB; 9059 } 9060 9061 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9062 MachineBasicBlock *BB) { 9063 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9064 "Unexpected instruction"); 9065 9066 MachineFunction &MF = *BB->getParent(); 9067 DebugLoc DL = MI.getDebugLoc(); 9068 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9069 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9070 Register DstReg = MI.getOperand(0).getReg(); 9071 Register LoReg = MI.getOperand(1).getReg(); 9072 Register HiReg = MI.getOperand(2).getReg(); 9073 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9074 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9075 9076 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9077 MachineMemOperand *MMOLo = 9078 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9079 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9080 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9081 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9082 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9083 .addFrameIndex(FI) 9084 .addImm(0) 9085 .addMemOperand(MMOLo); 9086 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9087 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9088 .addFrameIndex(FI) 9089 .addImm(4) 9090 .addMemOperand(MMOHi); 9091 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9092 MI.eraseFromParent(); // The pseudo instruction is gone now. 9093 return BB; 9094 } 9095 9096 static bool isSelectPseudo(MachineInstr &MI) { 9097 switch (MI.getOpcode()) { 9098 default: 9099 return false; 9100 case RISCV::Select_GPR_Using_CC_GPR: 9101 case RISCV::Select_FPR16_Using_CC_GPR: 9102 case RISCV::Select_FPR32_Using_CC_GPR: 9103 case RISCV::Select_FPR64_Using_CC_GPR: 9104 return true; 9105 } 9106 } 9107 9108 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9109 unsigned RelOpcode, unsigned EqOpcode, 9110 const RISCVSubtarget &Subtarget) { 9111 DebugLoc DL = MI.getDebugLoc(); 9112 Register DstReg = MI.getOperand(0).getReg(); 9113 Register Src1Reg = MI.getOperand(1).getReg(); 9114 Register Src2Reg = MI.getOperand(2).getReg(); 9115 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9116 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9117 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9118 9119 // Save the current FFLAGS. 9120 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9121 9122 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9123 .addReg(Src1Reg) 9124 .addReg(Src2Reg); 9125 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9126 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9127 9128 // Restore the FFLAGS. 9129 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9130 .addReg(SavedFFlags, RegState::Kill); 9131 9132 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9133 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9134 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9135 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9136 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9137 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9138 9139 // Erase the pseudoinstruction. 9140 MI.eraseFromParent(); 9141 return BB; 9142 } 9143 9144 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9145 MachineBasicBlock *BB, 9146 const RISCVSubtarget &Subtarget) { 9147 // To "insert" Select_* instructions, we actually have to insert the triangle 9148 // control-flow pattern. The incoming instructions know the destination vreg 9149 // to set, the condition code register to branch on, the true/false values to 9150 // select between, and the condcode to use to select the appropriate branch. 9151 // 9152 // We produce the following control flow: 9153 // HeadMBB 9154 // | \ 9155 // | IfFalseMBB 9156 // | / 9157 // TailMBB 9158 // 9159 // When we find a sequence of selects we attempt to optimize their emission 9160 // by sharing the control flow. Currently we only handle cases where we have 9161 // multiple selects with the exact same condition (same LHS, RHS and CC). 9162 // The selects may be interleaved with other instructions if the other 9163 // instructions meet some requirements we deem safe: 9164 // - They are debug instructions. Otherwise, 9165 // - They do not have side-effects, do not access memory and their inputs do 9166 // not depend on the results of the select pseudo-instructions. 9167 // The TrueV/FalseV operands of the selects cannot depend on the result of 9168 // previous selects in the sequence. 9169 // These conditions could be further relaxed. See the X86 target for a 9170 // related approach and more information. 9171 Register LHS = MI.getOperand(1).getReg(); 9172 Register RHS = MI.getOperand(2).getReg(); 9173 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9174 9175 SmallVector<MachineInstr *, 4> SelectDebugValues; 9176 SmallSet<Register, 4> SelectDests; 9177 SelectDests.insert(MI.getOperand(0).getReg()); 9178 9179 MachineInstr *LastSelectPseudo = &MI; 9180 9181 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9182 SequenceMBBI != E; ++SequenceMBBI) { 9183 if (SequenceMBBI->isDebugInstr()) 9184 continue; 9185 else if (isSelectPseudo(*SequenceMBBI)) { 9186 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9187 SequenceMBBI->getOperand(2).getReg() != RHS || 9188 SequenceMBBI->getOperand(3).getImm() != CC || 9189 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9190 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9191 break; 9192 LastSelectPseudo = &*SequenceMBBI; 9193 SequenceMBBI->collectDebugValues(SelectDebugValues); 9194 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9195 } else { 9196 if (SequenceMBBI->hasUnmodeledSideEffects() || 9197 SequenceMBBI->mayLoadOrStore()) 9198 break; 9199 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9200 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9201 })) 9202 break; 9203 } 9204 } 9205 9206 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9207 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9208 DebugLoc DL = MI.getDebugLoc(); 9209 MachineFunction::iterator I = ++BB->getIterator(); 9210 9211 MachineBasicBlock *HeadMBB = BB; 9212 MachineFunction *F = BB->getParent(); 9213 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9214 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9215 9216 F->insert(I, IfFalseMBB); 9217 F->insert(I, TailMBB); 9218 9219 // Transfer debug instructions associated with the selects to TailMBB. 9220 for (MachineInstr *DebugInstr : SelectDebugValues) { 9221 TailMBB->push_back(DebugInstr->removeFromParent()); 9222 } 9223 9224 // Move all instructions after the sequence to TailMBB. 9225 TailMBB->splice(TailMBB->end(), HeadMBB, 9226 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9227 // Update machine-CFG edges by transferring all successors of the current 9228 // block to the new block which will contain the Phi nodes for the selects. 9229 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9230 // Set the successors for HeadMBB. 9231 HeadMBB->addSuccessor(IfFalseMBB); 9232 HeadMBB->addSuccessor(TailMBB); 9233 9234 // Insert appropriate branch. 9235 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9236 .addReg(LHS) 9237 .addReg(RHS) 9238 .addMBB(TailMBB); 9239 9240 // IfFalseMBB just falls through to TailMBB. 9241 IfFalseMBB->addSuccessor(TailMBB); 9242 9243 // Create PHIs for all of the select pseudo-instructions. 9244 auto SelectMBBI = MI.getIterator(); 9245 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9246 auto InsertionPoint = TailMBB->begin(); 9247 while (SelectMBBI != SelectEnd) { 9248 auto Next = std::next(SelectMBBI); 9249 if (isSelectPseudo(*SelectMBBI)) { 9250 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9251 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9252 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9253 .addReg(SelectMBBI->getOperand(4).getReg()) 9254 .addMBB(HeadMBB) 9255 .addReg(SelectMBBI->getOperand(5).getReg()) 9256 .addMBB(IfFalseMBB); 9257 SelectMBBI->eraseFromParent(); 9258 } 9259 SelectMBBI = Next; 9260 } 9261 9262 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9263 return TailMBB; 9264 } 9265 9266 MachineBasicBlock * 9267 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9268 MachineBasicBlock *BB) const { 9269 switch (MI.getOpcode()) { 9270 default: 9271 llvm_unreachable("Unexpected instr type to insert"); 9272 case RISCV::ReadCycleWide: 9273 assert(!Subtarget.is64Bit() && 9274 "ReadCycleWrite is only to be used on riscv32"); 9275 return emitReadCycleWidePseudo(MI, BB); 9276 case RISCV::Select_GPR_Using_CC_GPR: 9277 case RISCV::Select_FPR16_Using_CC_GPR: 9278 case RISCV::Select_FPR32_Using_CC_GPR: 9279 case RISCV::Select_FPR64_Using_CC_GPR: 9280 return emitSelectPseudo(MI, BB, Subtarget); 9281 case RISCV::BuildPairF64Pseudo: 9282 return emitBuildPairF64Pseudo(MI, BB); 9283 case RISCV::SplitF64Pseudo: 9284 return emitSplitF64Pseudo(MI, BB); 9285 case RISCV::PseudoQuietFLE_H: 9286 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9287 case RISCV::PseudoQuietFLT_H: 9288 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9289 case RISCV::PseudoQuietFLE_S: 9290 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9291 case RISCV::PseudoQuietFLT_S: 9292 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9293 case RISCV::PseudoQuietFLE_D: 9294 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9295 case RISCV::PseudoQuietFLT_D: 9296 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9297 } 9298 } 9299 9300 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9301 SDNode *Node) const { 9302 // Add FRM dependency to any instructions with dynamic rounding mode. 9303 unsigned Opc = MI.getOpcode(); 9304 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9305 if (Idx < 0) 9306 return; 9307 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9308 return; 9309 // If the instruction already reads FRM, don't add another read. 9310 if (MI.readsRegister(RISCV::FRM)) 9311 return; 9312 MI.addOperand( 9313 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9314 } 9315 9316 // Calling Convention Implementation. 9317 // The expectations for frontend ABI lowering vary from target to target. 9318 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9319 // details, but this is a longer term goal. For now, we simply try to keep the 9320 // role of the frontend as simple and well-defined as possible. The rules can 9321 // be summarised as: 9322 // * Never split up large scalar arguments. We handle them here. 9323 // * If a hardfloat calling convention is being used, and the struct may be 9324 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9325 // available, then pass as two separate arguments. If either the GPRs or FPRs 9326 // are exhausted, then pass according to the rule below. 9327 // * If a struct could never be passed in registers or directly in a stack 9328 // slot (as it is larger than 2*XLEN and the floating point rules don't 9329 // apply), then pass it using a pointer with the byval attribute. 9330 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9331 // word-sized array or a 2*XLEN scalar (depending on alignment). 9332 // * The frontend can determine whether a struct is returned by reference or 9333 // not based on its size and fields. If it will be returned by reference, the 9334 // frontend must modify the prototype so a pointer with the sret annotation is 9335 // passed as the first argument. This is not necessary for large scalar 9336 // returns. 9337 // * Struct return values and varargs should be coerced to structs containing 9338 // register-size fields in the same situations they would be for fixed 9339 // arguments. 9340 9341 static const MCPhysReg ArgGPRs[] = { 9342 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9343 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9344 }; 9345 static const MCPhysReg ArgFPR16s[] = { 9346 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9347 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9348 }; 9349 static const MCPhysReg ArgFPR32s[] = { 9350 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9351 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9352 }; 9353 static const MCPhysReg ArgFPR64s[] = { 9354 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9355 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9356 }; 9357 // This is an interim calling convention and it may be changed in the future. 9358 static const MCPhysReg ArgVRs[] = { 9359 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9360 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9361 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9362 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9363 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9364 RISCV::V20M2, RISCV::V22M2}; 9365 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9366 RISCV::V20M4}; 9367 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9368 9369 // Pass a 2*XLEN argument that has been split into two XLEN values through 9370 // registers or the stack as necessary. 9371 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9372 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9373 MVT ValVT2, MVT LocVT2, 9374 ISD::ArgFlagsTy ArgFlags2) { 9375 unsigned XLenInBytes = XLen / 8; 9376 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9377 // At least one half can be passed via register. 9378 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9379 VA1.getLocVT(), CCValAssign::Full)); 9380 } else { 9381 // Both halves must be passed on the stack, with proper alignment. 9382 Align StackAlign = 9383 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9384 State.addLoc( 9385 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9386 State.AllocateStack(XLenInBytes, StackAlign), 9387 VA1.getLocVT(), CCValAssign::Full)); 9388 State.addLoc(CCValAssign::getMem( 9389 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9390 LocVT2, CCValAssign::Full)); 9391 return false; 9392 } 9393 9394 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9395 // The second half can also be passed via register. 9396 State.addLoc( 9397 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9398 } else { 9399 // The second half is passed via the stack, without additional alignment. 9400 State.addLoc(CCValAssign::getMem( 9401 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9402 LocVT2, CCValAssign::Full)); 9403 } 9404 9405 return false; 9406 } 9407 9408 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9409 Optional<unsigned> FirstMaskArgument, 9410 CCState &State, const RISCVTargetLowering &TLI) { 9411 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9412 if (RC == &RISCV::VRRegClass) { 9413 // Assign the first mask argument to V0. 9414 // This is an interim calling convention and it may be changed in the 9415 // future. 9416 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9417 return State.AllocateReg(RISCV::V0); 9418 return State.AllocateReg(ArgVRs); 9419 } 9420 if (RC == &RISCV::VRM2RegClass) 9421 return State.AllocateReg(ArgVRM2s); 9422 if (RC == &RISCV::VRM4RegClass) 9423 return State.AllocateReg(ArgVRM4s); 9424 if (RC == &RISCV::VRM8RegClass) 9425 return State.AllocateReg(ArgVRM8s); 9426 llvm_unreachable("Unhandled register class for ValueType"); 9427 } 9428 9429 // Implements the RISC-V calling convention. Returns true upon failure. 9430 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9431 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9432 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9433 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9434 Optional<unsigned> FirstMaskArgument) { 9435 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9436 assert(XLen == 32 || XLen == 64); 9437 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9438 9439 // Any return value split in to more than two values can't be returned 9440 // directly. Vectors are returned via the available vector registers. 9441 if (!LocVT.isVector() && IsRet && ValNo > 1) 9442 return true; 9443 9444 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9445 // variadic argument, or if no F16/F32 argument registers are available. 9446 bool UseGPRForF16_F32 = true; 9447 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9448 // variadic argument, or if no F64 argument registers are available. 9449 bool UseGPRForF64 = true; 9450 9451 switch (ABI) { 9452 default: 9453 llvm_unreachable("Unexpected ABI"); 9454 case RISCVABI::ABI_ILP32: 9455 case RISCVABI::ABI_LP64: 9456 break; 9457 case RISCVABI::ABI_ILP32F: 9458 case RISCVABI::ABI_LP64F: 9459 UseGPRForF16_F32 = !IsFixed; 9460 break; 9461 case RISCVABI::ABI_ILP32D: 9462 case RISCVABI::ABI_LP64D: 9463 UseGPRForF16_F32 = !IsFixed; 9464 UseGPRForF64 = !IsFixed; 9465 break; 9466 } 9467 9468 // FPR16, FPR32, and FPR64 alias each other. 9469 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9470 UseGPRForF16_F32 = true; 9471 UseGPRForF64 = true; 9472 } 9473 9474 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9475 // similar local variables rather than directly checking against the target 9476 // ABI. 9477 9478 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9479 LocVT = XLenVT; 9480 LocInfo = CCValAssign::BCvt; 9481 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9482 LocVT = MVT::i64; 9483 LocInfo = CCValAssign::BCvt; 9484 } 9485 9486 // If this is a variadic argument, the RISC-V calling convention requires 9487 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9488 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9489 // be used regardless of whether the original argument was split during 9490 // legalisation or not. The argument will not be passed by registers if the 9491 // original type is larger than 2*XLEN, so the register alignment rule does 9492 // not apply. 9493 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9494 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9495 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9496 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9497 // Skip 'odd' register if necessary. 9498 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9499 State.AllocateReg(ArgGPRs); 9500 } 9501 9502 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9503 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9504 State.getPendingArgFlags(); 9505 9506 assert(PendingLocs.size() == PendingArgFlags.size() && 9507 "PendingLocs and PendingArgFlags out of sync"); 9508 9509 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9510 // registers are exhausted. 9511 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9512 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9513 "Can't lower f64 if it is split"); 9514 // Depending on available argument GPRS, f64 may be passed in a pair of 9515 // GPRs, split between a GPR and the stack, or passed completely on the 9516 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9517 // cases. 9518 Register Reg = State.AllocateReg(ArgGPRs); 9519 LocVT = MVT::i32; 9520 if (!Reg) { 9521 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9522 State.addLoc( 9523 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9524 return false; 9525 } 9526 if (!State.AllocateReg(ArgGPRs)) 9527 State.AllocateStack(4, Align(4)); 9528 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9529 return false; 9530 } 9531 9532 // Fixed-length vectors are located in the corresponding scalable-vector 9533 // container types. 9534 if (ValVT.isFixedLengthVector()) 9535 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9536 9537 // Split arguments might be passed indirectly, so keep track of the pending 9538 // values. Split vectors are passed via a mix of registers and indirectly, so 9539 // treat them as we would any other argument. 9540 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9541 LocVT = XLenVT; 9542 LocInfo = CCValAssign::Indirect; 9543 PendingLocs.push_back( 9544 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9545 PendingArgFlags.push_back(ArgFlags); 9546 if (!ArgFlags.isSplitEnd()) { 9547 return false; 9548 } 9549 } 9550 9551 // If the split argument only had two elements, it should be passed directly 9552 // in registers or on the stack. 9553 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9554 PendingLocs.size() <= 2) { 9555 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9556 // Apply the normal calling convention rules to the first half of the 9557 // split argument. 9558 CCValAssign VA = PendingLocs[0]; 9559 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9560 PendingLocs.clear(); 9561 PendingArgFlags.clear(); 9562 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9563 ArgFlags); 9564 } 9565 9566 // Allocate to a register if possible, or else a stack slot. 9567 Register Reg; 9568 unsigned StoreSizeBytes = XLen / 8; 9569 Align StackAlign = Align(XLen / 8); 9570 9571 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9572 Reg = State.AllocateReg(ArgFPR16s); 9573 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9574 Reg = State.AllocateReg(ArgFPR32s); 9575 else if (ValVT == MVT::f64 && !UseGPRForF64) 9576 Reg = State.AllocateReg(ArgFPR64s); 9577 else if (ValVT.isVector()) { 9578 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9579 if (!Reg) { 9580 // For return values, the vector must be passed fully via registers or 9581 // via the stack. 9582 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9583 // but we're using all of them. 9584 if (IsRet) 9585 return true; 9586 // Try using a GPR to pass the address 9587 if ((Reg = State.AllocateReg(ArgGPRs))) { 9588 LocVT = XLenVT; 9589 LocInfo = CCValAssign::Indirect; 9590 } else if (ValVT.isScalableVector()) { 9591 LocVT = XLenVT; 9592 LocInfo = CCValAssign::Indirect; 9593 } else { 9594 // Pass fixed-length vectors on the stack. 9595 LocVT = ValVT; 9596 StoreSizeBytes = ValVT.getStoreSize(); 9597 // Align vectors to their element sizes, being careful for vXi1 9598 // vectors. 9599 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9600 } 9601 } 9602 } else { 9603 Reg = State.AllocateReg(ArgGPRs); 9604 } 9605 9606 unsigned StackOffset = 9607 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9608 9609 // If we reach this point and PendingLocs is non-empty, we must be at the 9610 // end of a split argument that must be passed indirectly. 9611 if (!PendingLocs.empty()) { 9612 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9613 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9614 9615 for (auto &It : PendingLocs) { 9616 if (Reg) 9617 It.convertToReg(Reg); 9618 else 9619 It.convertToMem(StackOffset); 9620 State.addLoc(It); 9621 } 9622 PendingLocs.clear(); 9623 PendingArgFlags.clear(); 9624 return false; 9625 } 9626 9627 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9628 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9629 "Expected an XLenVT or vector types at this stage"); 9630 9631 if (Reg) { 9632 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9633 return false; 9634 } 9635 9636 // When a floating-point value is passed on the stack, no bit-conversion is 9637 // needed. 9638 if (ValVT.isFloatingPoint()) { 9639 LocVT = ValVT; 9640 LocInfo = CCValAssign::Full; 9641 } 9642 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9643 return false; 9644 } 9645 9646 template <typename ArgTy> 9647 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9648 for (const auto &ArgIdx : enumerate(Args)) { 9649 MVT ArgVT = ArgIdx.value().VT; 9650 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9651 return ArgIdx.index(); 9652 } 9653 return None; 9654 } 9655 9656 void RISCVTargetLowering::analyzeInputArgs( 9657 MachineFunction &MF, CCState &CCInfo, 9658 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9659 RISCVCCAssignFn Fn) const { 9660 unsigned NumArgs = Ins.size(); 9661 FunctionType *FType = MF.getFunction().getFunctionType(); 9662 9663 Optional<unsigned> FirstMaskArgument; 9664 if (Subtarget.hasVInstructions()) 9665 FirstMaskArgument = preAssignMask(Ins); 9666 9667 for (unsigned i = 0; i != NumArgs; ++i) { 9668 MVT ArgVT = Ins[i].VT; 9669 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9670 9671 Type *ArgTy = nullptr; 9672 if (IsRet) 9673 ArgTy = FType->getReturnType(); 9674 else if (Ins[i].isOrigArg()) 9675 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9676 9677 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9678 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9679 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9680 FirstMaskArgument)) { 9681 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9682 << EVT(ArgVT).getEVTString() << '\n'); 9683 llvm_unreachable(nullptr); 9684 } 9685 } 9686 } 9687 9688 void RISCVTargetLowering::analyzeOutputArgs( 9689 MachineFunction &MF, CCState &CCInfo, 9690 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9691 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9692 unsigned NumArgs = Outs.size(); 9693 9694 Optional<unsigned> FirstMaskArgument; 9695 if (Subtarget.hasVInstructions()) 9696 FirstMaskArgument = preAssignMask(Outs); 9697 9698 for (unsigned i = 0; i != NumArgs; i++) { 9699 MVT ArgVT = Outs[i].VT; 9700 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9701 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9702 9703 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9704 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9705 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9706 FirstMaskArgument)) { 9707 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9708 << EVT(ArgVT).getEVTString() << "\n"); 9709 llvm_unreachable(nullptr); 9710 } 9711 } 9712 } 9713 9714 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9715 // values. 9716 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9717 const CCValAssign &VA, const SDLoc &DL, 9718 const RISCVSubtarget &Subtarget) { 9719 switch (VA.getLocInfo()) { 9720 default: 9721 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9722 case CCValAssign::Full: 9723 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9724 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9725 break; 9726 case CCValAssign::BCvt: 9727 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9728 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9729 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9730 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9731 else 9732 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9733 break; 9734 } 9735 return Val; 9736 } 9737 9738 // The caller is responsible for loading the full value if the argument is 9739 // passed with CCValAssign::Indirect. 9740 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9741 const CCValAssign &VA, const SDLoc &DL, 9742 const RISCVTargetLowering &TLI) { 9743 MachineFunction &MF = DAG.getMachineFunction(); 9744 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9745 EVT LocVT = VA.getLocVT(); 9746 SDValue Val; 9747 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9748 Register VReg = RegInfo.createVirtualRegister(RC); 9749 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9750 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9751 9752 if (VA.getLocInfo() == CCValAssign::Indirect) 9753 return Val; 9754 9755 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9756 } 9757 9758 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9759 const CCValAssign &VA, const SDLoc &DL, 9760 const RISCVSubtarget &Subtarget) { 9761 EVT LocVT = VA.getLocVT(); 9762 9763 switch (VA.getLocInfo()) { 9764 default: 9765 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9766 case CCValAssign::Full: 9767 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9768 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9769 break; 9770 case CCValAssign::BCvt: 9771 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9772 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9773 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9774 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9775 else 9776 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9777 break; 9778 } 9779 return Val; 9780 } 9781 9782 // The caller is responsible for loading the full value if the argument is 9783 // passed with CCValAssign::Indirect. 9784 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9785 const CCValAssign &VA, const SDLoc &DL) { 9786 MachineFunction &MF = DAG.getMachineFunction(); 9787 MachineFrameInfo &MFI = MF.getFrameInfo(); 9788 EVT LocVT = VA.getLocVT(); 9789 EVT ValVT = VA.getValVT(); 9790 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9791 if (ValVT.isScalableVector()) { 9792 // When the value is a scalable vector, we save the pointer which points to 9793 // the scalable vector value in the stack. The ValVT will be the pointer 9794 // type, instead of the scalable vector type. 9795 ValVT = LocVT; 9796 } 9797 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9798 /*IsImmutable=*/true); 9799 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9800 SDValue Val; 9801 9802 ISD::LoadExtType ExtType; 9803 switch (VA.getLocInfo()) { 9804 default: 9805 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9806 case CCValAssign::Full: 9807 case CCValAssign::Indirect: 9808 case CCValAssign::BCvt: 9809 ExtType = ISD::NON_EXTLOAD; 9810 break; 9811 } 9812 Val = DAG.getExtLoad( 9813 ExtType, DL, LocVT, Chain, FIN, 9814 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9815 return Val; 9816 } 9817 9818 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9819 const CCValAssign &VA, const SDLoc &DL) { 9820 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9821 "Unexpected VA"); 9822 MachineFunction &MF = DAG.getMachineFunction(); 9823 MachineFrameInfo &MFI = MF.getFrameInfo(); 9824 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9825 9826 if (VA.isMemLoc()) { 9827 // f64 is passed on the stack. 9828 int FI = 9829 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9830 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9831 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9832 MachinePointerInfo::getFixedStack(MF, FI)); 9833 } 9834 9835 assert(VA.isRegLoc() && "Expected register VA assignment"); 9836 9837 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9838 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9839 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9840 SDValue Hi; 9841 if (VA.getLocReg() == RISCV::X17) { 9842 // Second half of f64 is passed on the stack. 9843 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9844 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9845 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9846 MachinePointerInfo::getFixedStack(MF, FI)); 9847 } else { 9848 // Second half of f64 is passed in another GPR. 9849 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9850 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9851 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9852 } 9853 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9854 } 9855 9856 // FastCC has less than 1% performance improvement for some particular 9857 // benchmark. But theoretically, it may has benenfit for some cases. 9858 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9859 unsigned ValNo, MVT ValVT, MVT LocVT, 9860 CCValAssign::LocInfo LocInfo, 9861 ISD::ArgFlagsTy ArgFlags, CCState &State, 9862 bool IsFixed, bool IsRet, Type *OrigTy, 9863 const RISCVTargetLowering &TLI, 9864 Optional<unsigned> FirstMaskArgument) { 9865 9866 // X5 and X6 might be used for save-restore libcall. 9867 static const MCPhysReg GPRList[] = { 9868 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9869 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9870 RISCV::X29, RISCV::X30, RISCV::X31}; 9871 9872 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9873 if (unsigned Reg = State.AllocateReg(GPRList)) { 9874 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9875 return false; 9876 } 9877 } 9878 9879 if (LocVT == MVT::f16) { 9880 static const MCPhysReg FPR16List[] = { 9881 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9882 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9883 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9884 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9885 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9886 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9887 return false; 9888 } 9889 } 9890 9891 if (LocVT == MVT::f32) { 9892 static const MCPhysReg FPR32List[] = { 9893 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9894 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9895 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9896 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9897 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9898 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9899 return false; 9900 } 9901 } 9902 9903 if (LocVT == MVT::f64) { 9904 static const MCPhysReg FPR64List[] = { 9905 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9906 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9907 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9908 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9909 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9910 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9911 return false; 9912 } 9913 } 9914 9915 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9916 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9917 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9918 return false; 9919 } 9920 9921 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9922 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9923 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9924 return false; 9925 } 9926 9927 if (LocVT.isVector()) { 9928 if (unsigned Reg = 9929 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9930 // Fixed-length vectors are located in the corresponding scalable-vector 9931 // container types. 9932 if (ValVT.isFixedLengthVector()) 9933 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9934 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9935 } else { 9936 // Try and pass the address via a "fast" GPR. 9937 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9938 LocInfo = CCValAssign::Indirect; 9939 LocVT = TLI.getSubtarget().getXLenVT(); 9940 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9941 } else if (ValVT.isFixedLengthVector()) { 9942 auto StackAlign = 9943 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9944 unsigned StackOffset = 9945 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9946 State.addLoc( 9947 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9948 } else { 9949 // Can't pass scalable vectors on the stack. 9950 return true; 9951 } 9952 } 9953 9954 return false; 9955 } 9956 9957 return true; // CC didn't match. 9958 } 9959 9960 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9961 CCValAssign::LocInfo LocInfo, 9962 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9963 9964 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9965 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9966 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9967 static const MCPhysReg GPRList[] = { 9968 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9969 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9970 if (unsigned Reg = State.AllocateReg(GPRList)) { 9971 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9972 return false; 9973 } 9974 } 9975 9976 if (LocVT == MVT::f32) { 9977 // Pass in STG registers: F1, ..., F6 9978 // fs0 ... fs5 9979 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9980 RISCV::F18_F, RISCV::F19_F, 9981 RISCV::F20_F, RISCV::F21_F}; 9982 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9983 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9984 return false; 9985 } 9986 } 9987 9988 if (LocVT == MVT::f64) { 9989 // Pass in STG registers: D1, ..., D6 9990 // fs6 ... fs11 9991 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9992 RISCV::F24_D, RISCV::F25_D, 9993 RISCV::F26_D, RISCV::F27_D}; 9994 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9995 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9996 return false; 9997 } 9998 } 9999 10000 report_fatal_error("No registers left in GHC calling convention"); 10001 return true; 10002 } 10003 10004 // Transform physical registers into virtual registers. 10005 SDValue RISCVTargetLowering::LowerFormalArguments( 10006 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10007 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10008 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10009 10010 MachineFunction &MF = DAG.getMachineFunction(); 10011 10012 switch (CallConv) { 10013 default: 10014 report_fatal_error("Unsupported calling convention"); 10015 case CallingConv::C: 10016 case CallingConv::Fast: 10017 break; 10018 case CallingConv::GHC: 10019 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10020 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10021 report_fatal_error( 10022 "GHC calling convention requires the F and D instruction set extensions"); 10023 } 10024 10025 const Function &Func = MF.getFunction(); 10026 if (Func.hasFnAttribute("interrupt")) { 10027 if (!Func.arg_empty()) 10028 report_fatal_error( 10029 "Functions with the interrupt attribute cannot have arguments!"); 10030 10031 StringRef Kind = 10032 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10033 10034 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10035 report_fatal_error( 10036 "Function interrupt attribute argument not supported!"); 10037 } 10038 10039 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10040 MVT XLenVT = Subtarget.getXLenVT(); 10041 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10042 // Used with vargs to acumulate store chains. 10043 std::vector<SDValue> OutChains; 10044 10045 // Assign locations to all of the incoming arguments. 10046 SmallVector<CCValAssign, 16> ArgLocs; 10047 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10048 10049 if (CallConv == CallingConv::GHC) 10050 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10051 else 10052 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10053 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10054 : CC_RISCV); 10055 10056 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10057 CCValAssign &VA = ArgLocs[i]; 10058 SDValue ArgValue; 10059 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10060 // case. 10061 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10062 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10063 else if (VA.isRegLoc()) 10064 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10065 else 10066 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10067 10068 if (VA.getLocInfo() == CCValAssign::Indirect) { 10069 // If the original argument was split and passed by reference (e.g. i128 10070 // on RV32), we need to load all parts of it here (using the same 10071 // address). Vectors may be partly split to registers and partly to the 10072 // stack, in which case the base address is partly offset and subsequent 10073 // stores are relative to that. 10074 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10075 MachinePointerInfo())); 10076 unsigned ArgIndex = Ins[i].OrigArgIndex; 10077 unsigned ArgPartOffset = Ins[i].PartOffset; 10078 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10079 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10080 CCValAssign &PartVA = ArgLocs[i + 1]; 10081 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10082 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10083 if (PartVA.getValVT().isScalableVector()) 10084 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10085 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10086 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10087 MachinePointerInfo())); 10088 ++i; 10089 } 10090 continue; 10091 } 10092 InVals.push_back(ArgValue); 10093 } 10094 10095 if (IsVarArg) { 10096 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10097 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10098 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10099 MachineFrameInfo &MFI = MF.getFrameInfo(); 10100 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10101 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10102 10103 // Offset of the first variable argument from stack pointer, and size of 10104 // the vararg save area. For now, the varargs save area is either zero or 10105 // large enough to hold a0-a7. 10106 int VaArgOffset, VarArgsSaveSize; 10107 10108 // If all registers are allocated, then all varargs must be passed on the 10109 // stack and we don't need to save any argregs. 10110 if (ArgRegs.size() == Idx) { 10111 VaArgOffset = CCInfo.getNextStackOffset(); 10112 VarArgsSaveSize = 0; 10113 } else { 10114 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10115 VaArgOffset = -VarArgsSaveSize; 10116 } 10117 10118 // Record the frame index of the first variable argument 10119 // which is a value necessary to VASTART. 10120 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10121 RVFI->setVarArgsFrameIndex(FI); 10122 10123 // If saving an odd number of registers then create an extra stack slot to 10124 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10125 // offsets to even-numbered registered remain 2*XLEN-aligned. 10126 if (Idx % 2) { 10127 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10128 VarArgsSaveSize += XLenInBytes; 10129 } 10130 10131 // Copy the integer registers that may have been used for passing varargs 10132 // to the vararg save area. 10133 for (unsigned I = Idx; I < ArgRegs.size(); 10134 ++I, VaArgOffset += XLenInBytes) { 10135 const Register Reg = RegInfo.createVirtualRegister(RC); 10136 RegInfo.addLiveIn(ArgRegs[I], Reg); 10137 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10138 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10139 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10140 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10141 MachinePointerInfo::getFixedStack(MF, FI)); 10142 cast<StoreSDNode>(Store.getNode()) 10143 ->getMemOperand() 10144 ->setValue((Value *)nullptr); 10145 OutChains.push_back(Store); 10146 } 10147 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10148 } 10149 10150 // All stores are grouped in one node to allow the matching between 10151 // the size of Ins and InVals. This only happens for vararg functions. 10152 if (!OutChains.empty()) { 10153 OutChains.push_back(Chain); 10154 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10155 } 10156 10157 return Chain; 10158 } 10159 10160 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10161 /// for tail call optimization. 10162 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10163 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10164 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10165 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10166 10167 auto &Callee = CLI.Callee; 10168 auto CalleeCC = CLI.CallConv; 10169 auto &Outs = CLI.Outs; 10170 auto &Caller = MF.getFunction(); 10171 auto CallerCC = Caller.getCallingConv(); 10172 10173 // Exception-handling functions need a special set of instructions to 10174 // indicate a return to the hardware. Tail-calling another function would 10175 // probably break this. 10176 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10177 // should be expanded as new function attributes are introduced. 10178 if (Caller.hasFnAttribute("interrupt")) 10179 return false; 10180 10181 // Do not tail call opt if the stack is used to pass parameters. 10182 if (CCInfo.getNextStackOffset() != 0) 10183 return false; 10184 10185 // Do not tail call opt if any parameters need to be passed indirectly. 10186 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10187 // passed indirectly. So the address of the value will be passed in a 10188 // register, or if not available, then the address is put on the stack. In 10189 // order to pass indirectly, space on the stack often needs to be allocated 10190 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10191 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10192 // are passed CCValAssign::Indirect. 10193 for (auto &VA : ArgLocs) 10194 if (VA.getLocInfo() == CCValAssign::Indirect) 10195 return false; 10196 10197 // Do not tail call opt if either caller or callee uses struct return 10198 // semantics. 10199 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10200 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10201 if (IsCallerStructRet || IsCalleeStructRet) 10202 return false; 10203 10204 // Externally-defined functions with weak linkage should not be 10205 // tail-called. The behaviour of branch instructions in this situation (as 10206 // used for tail calls) is implementation-defined, so we cannot rely on the 10207 // linker replacing the tail call with a return. 10208 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10209 const GlobalValue *GV = G->getGlobal(); 10210 if (GV->hasExternalWeakLinkage()) 10211 return false; 10212 } 10213 10214 // The callee has to preserve all registers the caller needs to preserve. 10215 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10216 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10217 if (CalleeCC != CallerCC) { 10218 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10219 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10220 return false; 10221 } 10222 10223 // Byval parameters hand the function a pointer directly into the stack area 10224 // we want to reuse during a tail call. Working around this *is* possible 10225 // but less efficient and uglier in LowerCall. 10226 for (auto &Arg : Outs) 10227 if (Arg.Flags.isByVal()) 10228 return false; 10229 10230 return true; 10231 } 10232 10233 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10234 return DAG.getDataLayout().getPrefTypeAlign( 10235 VT.getTypeForEVT(*DAG.getContext())); 10236 } 10237 10238 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10239 // and output parameter nodes. 10240 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10241 SmallVectorImpl<SDValue> &InVals) const { 10242 SelectionDAG &DAG = CLI.DAG; 10243 SDLoc &DL = CLI.DL; 10244 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10245 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10246 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10247 SDValue Chain = CLI.Chain; 10248 SDValue Callee = CLI.Callee; 10249 bool &IsTailCall = CLI.IsTailCall; 10250 CallingConv::ID CallConv = CLI.CallConv; 10251 bool IsVarArg = CLI.IsVarArg; 10252 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10253 MVT XLenVT = Subtarget.getXLenVT(); 10254 10255 MachineFunction &MF = DAG.getMachineFunction(); 10256 10257 // Analyze the operands of the call, assigning locations to each operand. 10258 SmallVector<CCValAssign, 16> ArgLocs; 10259 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10260 10261 if (CallConv == CallingConv::GHC) 10262 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10263 else 10264 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10265 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10266 : CC_RISCV); 10267 10268 // Check if it's really possible to do a tail call. 10269 if (IsTailCall) 10270 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10271 10272 if (IsTailCall) 10273 ++NumTailCalls; 10274 else if (CLI.CB && CLI.CB->isMustTailCall()) 10275 report_fatal_error("failed to perform tail call elimination on a call " 10276 "site marked musttail"); 10277 10278 // Get a count of how many bytes are to be pushed on the stack. 10279 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10280 10281 // Create local copies for byval args 10282 SmallVector<SDValue, 8> ByValArgs; 10283 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10284 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10285 if (!Flags.isByVal()) 10286 continue; 10287 10288 SDValue Arg = OutVals[i]; 10289 unsigned Size = Flags.getByValSize(); 10290 Align Alignment = Flags.getNonZeroByValAlign(); 10291 10292 int FI = 10293 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10294 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10295 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10296 10297 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10298 /*IsVolatile=*/false, 10299 /*AlwaysInline=*/false, IsTailCall, 10300 MachinePointerInfo(), MachinePointerInfo()); 10301 ByValArgs.push_back(FIPtr); 10302 } 10303 10304 if (!IsTailCall) 10305 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10306 10307 // Copy argument values to their designated locations. 10308 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10309 SmallVector<SDValue, 8> MemOpChains; 10310 SDValue StackPtr; 10311 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10312 CCValAssign &VA = ArgLocs[i]; 10313 SDValue ArgValue = OutVals[i]; 10314 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10315 10316 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10317 bool IsF64OnRV32DSoftABI = 10318 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10319 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10320 SDValue SplitF64 = DAG.getNode( 10321 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10322 SDValue Lo = SplitF64.getValue(0); 10323 SDValue Hi = SplitF64.getValue(1); 10324 10325 Register RegLo = VA.getLocReg(); 10326 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10327 10328 if (RegLo == RISCV::X17) { 10329 // Second half of f64 is passed on the stack. 10330 // Work out the address of the stack slot. 10331 if (!StackPtr.getNode()) 10332 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10333 // Emit the store. 10334 MemOpChains.push_back( 10335 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10336 } else { 10337 // Second half of f64 is passed in another GPR. 10338 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10339 Register RegHigh = RegLo + 1; 10340 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10341 } 10342 continue; 10343 } 10344 10345 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10346 // as any other MemLoc. 10347 10348 // Promote the value if needed. 10349 // For now, only handle fully promoted and indirect arguments. 10350 if (VA.getLocInfo() == CCValAssign::Indirect) { 10351 // Store the argument in a stack slot and pass its address. 10352 Align StackAlign = 10353 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10354 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10355 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10356 // If the original argument was split (e.g. i128), we need 10357 // to store the required parts of it here (and pass just one address). 10358 // Vectors may be partly split to registers and partly to the stack, in 10359 // which case the base address is partly offset and subsequent stores are 10360 // relative to that. 10361 unsigned ArgIndex = Outs[i].OrigArgIndex; 10362 unsigned ArgPartOffset = Outs[i].PartOffset; 10363 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10364 // Calculate the total size to store. We don't have access to what we're 10365 // actually storing other than performing the loop and collecting the 10366 // info. 10367 SmallVector<std::pair<SDValue, SDValue>> Parts; 10368 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10369 SDValue PartValue = OutVals[i + 1]; 10370 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10371 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10372 EVT PartVT = PartValue.getValueType(); 10373 if (PartVT.isScalableVector()) 10374 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10375 StoredSize += PartVT.getStoreSize(); 10376 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10377 Parts.push_back(std::make_pair(PartValue, Offset)); 10378 ++i; 10379 } 10380 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10381 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10382 MemOpChains.push_back( 10383 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10384 MachinePointerInfo::getFixedStack(MF, FI))); 10385 for (const auto &Part : Parts) { 10386 SDValue PartValue = Part.first; 10387 SDValue PartOffset = Part.second; 10388 SDValue Address = 10389 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10390 MemOpChains.push_back( 10391 DAG.getStore(Chain, DL, PartValue, Address, 10392 MachinePointerInfo::getFixedStack(MF, FI))); 10393 } 10394 ArgValue = SpillSlot; 10395 } else { 10396 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10397 } 10398 10399 // Use local copy if it is a byval arg. 10400 if (Flags.isByVal()) 10401 ArgValue = ByValArgs[j++]; 10402 10403 if (VA.isRegLoc()) { 10404 // Queue up the argument copies and emit them at the end. 10405 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10406 } else { 10407 assert(VA.isMemLoc() && "Argument not register or memory"); 10408 assert(!IsTailCall && "Tail call not allowed if stack is used " 10409 "for passing parameters"); 10410 10411 // Work out the address of the stack slot. 10412 if (!StackPtr.getNode()) 10413 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10414 SDValue Address = 10415 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10416 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10417 10418 // Emit the store. 10419 MemOpChains.push_back( 10420 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10421 } 10422 } 10423 10424 // Join the stores, which are independent of one another. 10425 if (!MemOpChains.empty()) 10426 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10427 10428 SDValue Glue; 10429 10430 // Build a sequence of copy-to-reg nodes, chained and glued together. 10431 for (auto &Reg : RegsToPass) { 10432 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10433 Glue = Chain.getValue(1); 10434 } 10435 10436 // Validate that none of the argument registers have been marked as 10437 // reserved, if so report an error. Do the same for the return address if this 10438 // is not a tailcall. 10439 validateCCReservedRegs(RegsToPass, MF); 10440 if (!IsTailCall && 10441 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10442 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10443 MF.getFunction(), 10444 "Return address register required, but has been reserved."}); 10445 10446 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10447 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10448 // split it and then direct call can be matched by PseudoCALL. 10449 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10450 const GlobalValue *GV = S->getGlobal(); 10451 10452 unsigned OpFlags = RISCVII::MO_CALL; 10453 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10454 OpFlags = RISCVII::MO_PLT; 10455 10456 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10457 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10458 unsigned OpFlags = RISCVII::MO_CALL; 10459 10460 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10461 nullptr)) 10462 OpFlags = RISCVII::MO_PLT; 10463 10464 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10465 } 10466 10467 // The first call operand is the chain and the second is the target address. 10468 SmallVector<SDValue, 8> Ops; 10469 Ops.push_back(Chain); 10470 Ops.push_back(Callee); 10471 10472 // Add argument registers to the end of the list so that they are 10473 // known live into the call. 10474 for (auto &Reg : RegsToPass) 10475 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10476 10477 if (!IsTailCall) { 10478 // Add a register mask operand representing the call-preserved registers. 10479 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10480 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10481 assert(Mask && "Missing call preserved mask for calling convention"); 10482 Ops.push_back(DAG.getRegisterMask(Mask)); 10483 } 10484 10485 // Glue the call to the argument copies, if any. 10486 if (Glue.getNode()) 10487 Ops.push_back(Glue); 10488 10489 // Emit the call. 10490 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10491 10492 if (IsTailCall) { 10493 MF.getFrameInfo().setHasTailCall(); 10494 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10495 } 10496 10497 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10498 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10499 Glue = Chain.getValue(1); 10500 10501 // Mark the end of the call, which is glued to the call itself. 10502 Chain = DAG.getCALLSEQ_END(Chain, 10503 DAG.getConstant(NumBytes, DL, PtrVT, true), 10504 DAG.getConstant(0, DL, PtrVT, true), 10505 Glue, DL); 10506 Glue = Chain.getValue(1); 10507 10508 // Assign locations to each value returned by this call. 10509 SmallVector<CCValAssign, 16> RVLocs; 10510 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10511 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10512 10513 // Copy all of the result registers out of their specified physreg. 10514 for (auto &VA : RVLocs) { 10515 // Copy the value out 10516 SDValue RetValue = 10517 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10518 // Glue the RetValue to the end of the call sequence 10519 Chain = RetValue.getValue(1); 10520 Glue = RetValue.getValue(2); 10521 10522 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10523 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10524 SDValue RetValue2 = 10525 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10526 Chain = RetValue2.getValue(1); 10527 Glue = RetValue2.getValue(2); 10528 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10529 RetValue2); 10530 } 10531 10532 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10533 10534 InVals.push_back(RetValue); 10535 } 10536 10537 return Chain; 10538 } 10539 10540 bool RISCVTargetLowering::CanLowerReturn( 10541 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10542 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10543 SmallVector<CCValAssign, 16> RVLocs; 10544 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10545 10546 Optional<unsigned> FirstMaskArgument; 10547 if (Subtarget.hasVInstructions()) 10548 FirstMaskArgument = preAssignMask(Outs); 10549 10550 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10551 MVT VT = Outs[i].VT; 10552 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10553 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10554 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10555 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10556 *this, FirstMaskArgument)) 10557 return false; 10558 } 10559 return true; 10560 } 10561 10562 SDValue 10563 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10564 bool IsVarArg, 10565 const SmallVectorImpl<ISD::OutputArg> &Outs, 10566 const SmallVectorImpl<SDValue> &OutVals, 10567 const SDLoc &DL, SelectionDAG &DAG) const { 10568 const MachineFunction &MF = DAG.getMachineFunction(); 10569 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10570 10571 // Stores the assignment of the return value to a location. 10572 SmallVector<CCValAssign, 16> RVLocs; 10573 10574 // Info about the registers and stack slot. 10575 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10576 *DAG.getContext()); 10577 10578 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10579 nullptr, CC_RISCV); 10580 10581 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10582 report_fatal_error("GHC functions return void only"); 10583 10584 SDValue Glue; 10585 SmallVector<SDValue, 4> RetOps(1, Chain); 10586 10587 // Copy the result values into the output registers. 10588 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10589 SDValue Val = OutVals[i]; 10590 CCValAssign &VA = RVLocs[i]; 10591 assert(VA.isRegLoc() && "Can only return in registers!"); 10592 10593 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10594 // Handle returning f64 on RV32D with a soft float ABI. 10595 assert(VA.isRegLoc() && "Expected return via registers"); 10596 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10597 DAG.getVTList(MVT::i32, MVT::i32), Val); 10598 SDValue Lo = SplitF64.getValue(0); 10599 SDValue Hi = SplitF64.getValue(1); 10600 Register RegLo = VA.getLocReg(); 10601 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10602 Register RegHi = RegLo + 1; 10603 10604 if (STI.isRegisterReservedByUser(RegLo) || 10605 STI.isRegisterReservedByUser(RegHi)) 10606 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10607 MF.getFunction(), 10608 "Return value register required, but has been reserved."}); 10609 10610 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10611 Glue = Chain.getValue(1); 10612 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10613 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10614 Glue = Chain.getValue(1); 10615 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10616 } else { 10617 // Handle a 'normal' return. 10618 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10619 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10620 10621 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10622 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10623 MF.getFunction(), 10624 "Return value register required, but has been reserved."}); 10625 10626 // Guarantee that all emitted copies are stuck together. 10627 Glue = Chain.getValue(1); 10628 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10629 } 10630 } 10631 10632 RetOps[0] = Chain; // Update chain. 10633 10634 // Add the glue node if we have it. 10635 if (Glue.getNode()) { 10636 RetOps.push_back(Glue); 10637 } 10638 10639 unsigned RetOpc = RISCVISD::RET_FLAG; 10640 // Interrupt service routines use different return instructions. 10641 const Function &Func = DAG.getMachineFunction().getFunction(); 10642 if (Func.hasFnAttribute("interrupt")) { 10643 if (!Func.getReturnType()->isVoidTy()) 10644 report_fatal_error( 10645 "Functions with the interrupt attribute must have void return type!"); 10646 10647 MachineFunction &MF = DAG.getMachineFunction(); 10648 StringRef Kind = 10649 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10650 10651 if (Kind == "user") 10652 RetOpc = RISCVISD::URET_FLAG; 10653 else if (Kind == "supervisor") 10654 RetOpc = RISCVISD::SRET_FLAG; 10655 else 10656 RetOpc = RISCVISD::MRET_FLAG; 10657 } 10658 10659 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10660 } 10661 10662 void RISCVTargetLowering::validateCCReservedRegs( 10663 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10664 MachineFunction &MF) const { 10665 const Function &F = MF.getFunction(); 10666 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10667 10668 if (llvm::any_of(Regs, [&STI](auto Reg) { 10669 return STI.isRegisterReservedByUser(Reg.first); 10670 })) 10671 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10672 F, "Argument register required, but has been reserved."}); 10673 } 10674 10675 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10676 return CI->isTailCall(); 10677 } 10678 10679 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10680 #define NODE_NAME_CASE(NODE) \ 10681 case RISCVISD::NODE: \ 10682 return "RISCVISD::" #NODE; 10683 // clang-format off 10684 switch ((RISCVISD::NodeType)Opcode) { 10685 case RISCVISD::FIRST_NUMBER: 10686 break; 10687 NODE_NAME_CASE(RET_FLAG) 10688 NODE_NAME_CASE(URET_FLAG) 10689 NODE_NAME_CASE(SRET_FLAG) 10690 NODE_NAME_CASE(MRET_FLAG) 10691 NODE_NAME_CASE(CALL) 10692 NODE_NAME_CASE(SELECT_CC) 10693 NODE_NAME_CASE(BR_CC) 10694 NODE_NAME_CASE(BuildPairF64) 10695 NODE_NAME_CASE(SplitF64) 10696 NODE_NAME_CASE(TAIL) 10697 NODE_NAME_CASE(MULHSU) 10698 NODE_NAME_CASE(SLLW) 10699 NODE_NAME_CASE(SRAW) 10700 NODE_NAME_CASE(SRLW) 10701 NODE_NAME_CASE(DIVW) 10702 NODE_NAME_CASE(DIVUW) 10703 NODE_NAME_CASE(REMUW) 10704 NODE_NAME_CASE(ROLW) 10705 NODE_NAME_CASE(RORW) 10706 NODE_NAME_CASE(CLZW) 10707 NODE_NAME_CASE(CTZW) 10708 NODE_NAME_CASE(FSLW) 10709 NODE_NAME_CASE(FSRW) 10710 NODE_NAME_CASE(FSL) 10711 NODE_NAME_CASE(FSR) 10712 NODE_NAME_CASE(FMV_H_X) 10713 NODE_NAME_CASE(FMV_X_ANYEXTH) 10714 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10715 NODE_NAME_CASE(FMV_W_X_RV64) 10716 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10717 NODE_NAME_CASE(FCVT_X) 10718 NODE_NAME_CASE(FCVT_XU) 10719 NODE_NAME_CASE(FCVT_W_RV64) 10720 NODE_NAME_CASE(FCVT_WU_RV64) 10721 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10722 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10723 NODE_NAME_CASE(READ_CYCLE_WIDE) 10724 NODE_NAME_CASE(GREV) 10725 NODE_NAME_CASE(GREVW) 10726 NODE_NAME_CASE(GORC) 10727 NODE_NAME_CASE(GORCW) 10728 NODE_NAME_CASE(SHFL) 10729 NODE_NAME_CASE(SHFLW) 10730 NODE_NAME_CASE(UNSHFL) 10731 NODE_NAME_CASE(UNSHFLW) 10732 NODE_NAME_CASE(BFP) 10733 NODE_NAME_CASE(BFPW) 10734 NODE_NAME_CASE(BCOMPRESS) 10735 NODE_NAME_CASE(BCOMPRESSW) 10736 NODE_NAME_CASE(BDECOMPRESS) 10737 NODE_NAME_CASE(BDECOMPRESSW) 10738 NODE_NAME_CASE(VMV_V_X_VL) 10739 NODE_NAME_CASE(VFMV_V_F_VL) 10740 NODE_NAME_CASE(VMV_X_S) 10741 NODE_NAME_CASE(VMV_S_X_VL) 10742 NODE_NAME_CASE(VFMV_S_F_VL) 10743 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10744 NODE_NAME_CASE(READ_VLENB) 10745 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10746 NODE_NAME_CASE(VSLIDEUP_VL) 10747 NODE_NAME_CASE(VSLIDE1UP_VL) 10748 NODE_NAME_CASE(VSLIDEDOWN_VL) 10749 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10750 NODE_NAME_CASE(VID_VL) 10751 NODE_NAME_CASE(VFNCVT_ROD_VL) 10752 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10753 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10754 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10755 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10756 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10757 NODE_NAME_CASE(VECREDUCE_AND_VL) 10758 NODE_NAME_CASE(VECREDUCE_OR_VL) 10759 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10760 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10761 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10762 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10763 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10764 NODE_NAME_CASE(ADD_VL) 10765 NODE_NAME_CASE(AND_VL) 10766 NODE_NAME_CASE(MUL_VL) 10767 NODE_NAME_CASE(OR_VL) 10768 NODE_NAME_CASE(SDIV_VL) 10769 NODE_NAME_CASE(SHL_VL) 10770 NODE_NAME_CASE(SREM_VL) 10771 NODE_NAME_CASE(SRA_VL) 10772 NODE_NAME_CASE(SRL_VL) 10773 NODE_NAME_CASE(SUB_VL) 10774 NODE_NAME_CASE(UDIV_VL) 10775 NODE_NAME_CASE(UREM_VL) 10776 NODE_NAME_CASE(XOR_VL) 10777 NODE_NAME_CASE(SADDSAT_VL) 10778 NODE_NAME_CASE(UADDSAT_VL) 10779 NODE_NAME_CASE(SSUBSAT_VL) 10780 NODE_NAME_CASE(USUBSAT_VL) 10781 NODE_NAME_CASE(FADD_VL) 10782 NODE_NAME_CASE(FSUB_VL) 10783 NODE_NAME_CASE(FMUL_VL) 10784 NODE_NAME_CASE(FDIV_VL) 10785 NODE_NAME_CASE(FNEG_VL) 10786 NODE_NAME_CASE(FABS_VL) 10787 NODE_NAME_CASE(FSQRT_VL) 10788 NODE_NAME_CASE(FMA_VL) 10789 NODE_NAME_CASE(FCOPYSIGN_VL) 10790 NODE_NAME_CASE(SMIN_VL) 10791 NODE_NAME_CASE(SMAX_VL) 10792 NODE_NAME_CASE(UMIN_VL) 10793 NODE_NAME_CASE(UMAX_VL) 10794 NODE_NAME_CASE(FMINNUM_VL) 10795 NODE_NAME_CASE(FMAXNUM_VL) 10796 NODE_NAME_CASE(MULHS_VL) 10797 NODE_NAME_CASE(MULHU_VL) 10798 NODE_NAME_CASE(FP_TO_SINT_VL) 10799 NODE_NAME_CASE(FP_TO_UINT_VL) 10800 NODE_NAME_CASE(SINT_TO_FP_VL) 10801 NODE_NAME_CASE(UINT_TO_FP_VL) 10802 NODE_NAME_CASE(FP_EXTEND_VL) 10803 NODE_NAME_CASE(FP_ROUND_VL) 10804 NODE_NAME_CASE(VWMUL_VL) 10805 NODE_NAME_CASE(VWMULU_VL) 10806 NODE_NAME_CASE(VWMULSU_VL) 10807 NODE_NAME_CASE(VWADD_VL) 10808 NODE_NAME_CASE(VWADDU_VL) 10809 NODE_NAME_CASE(VWSUB_VL) 10810 NODE_NAME_CASE(VWSUBU_VL) 10811 NODE_NAME_CASE(VWADD_W_VL) 10812 NODE_NAME_CASE(VWADDU_W_VL) 10813 NODE_NAME_CASE(VWSUB_W_VL) 10814 NODE_NAME_CASE(VWSUBU_W_VL) 10815 NODE_NAME_CASE(SETCC_VL) 10816 NODE_NAME_CASE(VSELECT_VL) 10817 NODE_NAME_CASE(VP_MERGE_VL) 10818 NODE_NAME_CASE(VMAND_VL) 10819 NODE_NAME_CASE(VMOR_VL) 10820 NODE_NAME_CASE(VMXOR_VL) 10821 NODE_NAME_CASE(VMCLR_VL) 10822 NODE_NAME_CASE(VMSET_VL) 10823 NODE_NAME_CASE(VRGATHER_VX_VL) 10824 NODE_NAME_CASE(VRGATHER_VV_VL) 10825 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10826 NODE_NAME_CASE(VSEXT_VL) 10827 NODE_NAME_CASE(VZEXT_VL) 10828 NODE_NAME_CASE(VCPOP_VL) 10829 NODE_NAME_CASE(VLE_VL) 10830 NODE_NAME_CASE(VSE_VL) 10831 NODE_NAME_CASE(READ_CSR) 10832 NODE_NAME_CASE(WRITE_CSR) 10833 NODE_NAME_CASE(SWAP_CSR) 10834 } 10835 // clang-format on 10836 return nullptr; 10837 #undef NODE_NAME_CASE 10838 } 10839 10840 /// getConstraintType - Given a constraint letter, return the type of 10841 /// constraint it is for this target. 10842 RISCVTargetLowering::ConstraintType 10843 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10844 if (Constraint.size() == 1) { 10845 switch (Constraint[0]) { 10846 default: 10847 break; 10848 case 'f': 10849 return C_RegisterClass; 10850 case 'I': 10851 case 'J': 10852 case 'K': 10853 return C_Immediate; 10854 case 'A': 10855 return C_Memory; 10856 case 'S': // A symbolic address 10857 return C_Other; 10858 } 10859 } else { 10860 if (Constraint == "vr" || Constraint == "vm") 10861 return C_RegisterClass; 10862 } 10863 return TargetLowering::getConstraintType(Constraint); 10864 } 10865 10866 std::pair<unsigned, const TargetRegisterClass *> 10867 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10868 StringRef Constraint, 10869 MVT VT) const { 10870 // First, see if this is a constraint that directly corresponds to a 10871 // RISCV register class. 10872 if (Constraint.size() == 1) { 10873 switch (Constraint[0]) { 10874 case 'r': 10875 // TODO: Support fixed vectors up to XLen for P extension? 10876 if (VT.isVector()) 10877 break; 10878 return std::make_pair(0U, &RISCV::GPRRegClass); 10879 case 'f': 10880 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10881 return std::make_pair(0U, &RISCV::FPR16RegClass); 10882 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10883 return std::make_pair(0U, &RISCV::FPR32RegClass); 10884 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10885 return std::make_pair(0U, &RISCV::FPR64RegClass); 10886 break; 10887 default: 10888 break; 10889 } 10890 } else if (Constraint == "vr") { 10891 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10892 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10893 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10894 return std::make_pair(0U, RC); 10895 } 10896 } else if (Constraint == "vm") { 10897 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10898 return std::make_pair(0U, &RISCV::VMV0RegClass); 10899 } 10900 10901 // Clang will correctly decode the usage of register name aliases into their 10902 // official names. However, other frontends like `rustc` do not. This allows 10903 // users of these frontends to use the ABI names for registers in LLVM-style 10904 // register constraints. 10905 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10906 .Case("{zero}", RISCV::X0) 10907 .Case("{ra}", RISCV::X1) 10908 .Case("{sp}", RISCV::X2) 10909 .Case("{gp}", RISCV::X3) 10910 .Case("{tp}", RISCV::X4) 10911 .Case("{t0}", RISCV::X5) 10912 .Case("{t1}", RISCV::X6) 10913 .Case("{t2}", RISCV::X7) 10914 .Cases("{s0}", "{fp}", RISCV::X8) 10915 .Case("{s1}", RISCV::X9) 10916 .Case("{a0}", RISCV::X10) 10917 .Case("{a1}", RISCV::X11) 10918 .Case("{a2}", RISCV::X12) 10919 .Case("{a3}", RISCV::X13) 10920 .Case("{a4}", RISCV::X14) 10921 .Case("{a5}", RISCV::X15) 10922 .Case("{a6}", RISCV::X16) 10923 .Case("{a7}", RISCV::X17) 10924 .Case("{s2}", RISCV::X18) 10925 .Case("{s3}", RISCV::X19) 10926 .Case("{s4}", RISCV::X20) 10927 .Case("{s5}", RISCV::X21) 10928 .Case("{s6}", RISCV::X22) 10929 .Case("{s7}", RISCV::X23) 10930 .Case("{s8}", RISCV::X24) 10931 .Case("{s9}", RISCV::X25) 10932 .Case("{s10}", RISCV::X26) 10933 .Case("{s11}", RISCV::X27) 10934 .Case("{t3}", RISCV::X28) 10935 .Case("{t4}", RISCV::X29) 10936 .Case("{t5}", RISCV::X30) 10937 .Case("{t6}", RISCV::X31) 10938 .Default(RISCV::NoRegister); 10939 if (XRegFromAlias != RISCV::NoRegister) 10940 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10941 10942 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10943 // TableGen record rather than the AsmName to choose registers for InlineAsm 10944 // constraints, plus we want to match those names to the widest floating point 10945 // register type available, manually select floating point registers here. 10946 // 10947 // The second case is the ABI name of the register, so that frontends can also 10948 // use the ABI names in register constraint lists. 10949 if (Subtarget.hasStdExtF()) { 10950 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10951 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10952 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10953 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10954 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10955 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10956 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10957 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10958 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10959 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10960 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10961 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10962 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10963 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10964 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10965 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10966 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10967 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10968 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10969 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10970 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10971 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10972 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10973 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10974 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10975 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10976 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10977 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10978 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10979 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10980 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10981 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10982 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10983 .Default(RISCV::NoRegister); 10984 if (FReg != RISCV::NoRegister) { 10985 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10986 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10987 unsigned RegNo = FReg - RISCV::F0_F; 10988 unsigned DReg = RISCV::F0_D + RegNo; 10989 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10990 } 10991 if (VT == MVT::f32 || VT == MVT::Other) 10992 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10993 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10994 unsigned RegNo = FReg - RISCV::F0_F; 10995 unsigned HReg = RISCV::F0_H + RegNo; 10996 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10997 } 10998 } 10999 } 11000 11001 if (Subtarget.hasVInstructions()) { 11002 Register VReg = StringSwitch<Register>(Constraint.lower()) 11003 .Case("{v0}", RISCV::V0) 11004 .Case("{v1}", RISCV::V1) 11005 .Case("{v2}", RISCV::V2) 11006 .Case("{v3}", RISCV::V3) 11007 .Case("{v4}", RISCV::V4) 11008 .Case("{v5}", RISCV::V5) 11009 .Case("{v6}", RISCV::V6) 11010 .Case("{v7}", RISCV::V7) 11011 .Case("{v8}", RISCV::V8) 11012 .Case("{v9}", RISCV::V9) 11013 .Case("{v10}", RISCV::V10) 11014 .Case("{v11}", RISCV::V11) 11015 .Case("{v12}", RISCV::V12) 11016 .Case("{v13}", RISCV::V13) 11017 .Case("{v14}", RISCV::V14) 11018 .Case("{v15}", RISCV::V15) 11019 .Case("{v16}", RISCV::V16) 11020 .Case("{v17}", RISCV::V17) 11021 .Case("{v18}", RISCV::V18) 11022 .Case("{v19}", RISCV::V19) 11023 .Case("{v20}", RISCV::V20) 11024 .Case("{v21}", RISCV::V21) 11025 .Case("{v22}", RISCV::V22) 11026 .Case("{v23}", RISCV::V23) 11027 .Case("{v24}", RISCV::V24) 11028 .Case("{v25}", RISCV::V25) 11029 .Case("{v26}", RISCV::V26) 11030 .Case("{v27}", RISCV::V27) 11031 .Case("{v28}", RISCV::V28) 11032 .Case("{v29}", RISCV::V29) 11033 .Case("{v30}", RISCV::V30) 11034 .Case("{v31}", RISCV::V31) 11035 .Default(RISCV::NoRegister); 11036 if (VReg != RISCV::NoRegister) { 11037 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11038 return std::make_pair(VReg, &RISCV::VMRegClass); 11039 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11040 return std::make_pair(VReg, &RISCV::VRRegClass); 11041 for (const auto *RC : 11042 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11043 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11044 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11045 return std::make_pair(VReg, RC); 11046 } 11047 } 11048 } 11049 } 11050 11051 std::pair<Register, const TargetRegisterClass *> Res = 11052 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11053 11054 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11055 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11056 // Subtarget into account. 11057 if (Res.second == &RISCV::GPRF16RegClass || 11058 Res.second == &RISCV::GPRF32RegClass || 11059 Res.second == &RISCV::GPRF64RegClass) 11060 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11061 11062 return Res; 11063 } 11064 11065 unsigned 11066 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11067 // Currently only support length 1 constraints. 11068 if (ConstraintCode.size() == 1) { 11069 switch (ConstraintCode[0]) { 11070 case 'A': 11071 return InlineAsm::Constraint_A; 11072 default: 11073 break; 11074 } 11075 } 11076 11077 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11078 } 11079 11080 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11081 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11082 SelectionDAG &DAG) const { 11083 // Currently only support length 1 constraints. 11084 if (Constraint.length() == 1) { 11085 switch (Constraint[0]) { 11086 case 'I': 11087 // Validate & create a 12-bit signed immediate operand. 11088 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11089 uint64_t CVal = C->getSExtValue(); 11090 if (isInt<12>(CVal)) 11091 Ops.push_back( 11092 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11093 } 11094 return; 11095 case 'J': 11096 // Validate & create an integer zero operand. 11097 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11098 if (C->getZExtValue() == 0) 11099 Ops.push_back( 11100 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11101 return; 11102 case 'K': 11103 // Validate & create a 5-bit unsigned immediate operand. 11104 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11105 uint64_t CVal = C->getZExtValue(); 11106 if (isUInt<5>(CVal)) 11107 Ops.push_back( 11108 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11109 } 11110 return; 11111 case 'S': 11112 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11113 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11114 GA->getValueType(0))); 11115 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11116 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11117 BA->getValueType(0))); 11118 } 11119 return; 11120 default: 11121 break; 11122 } 11123 } 11124 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11125 } 11126 11127 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11128 Instruction *Inst, 11129 AtomicOrdering Ord) const { 11130 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11131 return Builder.CreateFence(Ord); 11132 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11133 return Builder.CreateFence(AtomicOrdering::Release); 11134 return nullptr; 11135 } 11136 11137 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11138 Instruction *Inst, 11139 AtomicOrdering Ord) const { 11140 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11141 return Builder.CreateFence(AtomicOrdering::Acquire); 11142 return nullptr; 11143 } 11144 11145 TargetLowering::AtomicExpansionKind 11146 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11147 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11148 // point operations can't be used in an lr/sc sequence without breaking the 11149 // forward-progress guarantee. 11150 if (AI->isFloatingPointOperation()) 11151 return AtomicExpansionKind::CmpXChg; 11152 11153 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11154 if (Size == 8 || Size == 16) 11155 return AtomicExpansionKind::MaskedIntrinsic; 11156 return AtomicExpansionKind::None; 11157 } 11158 11159 static Intrinsic::ID 11160 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11161 if (XLen == 32) { 11162 switch (BinOp) { 11163 default: 11164 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11165 case AtomicRMWInst::Xchg: 11166 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11167 case AtomicRMWInst::Add: 11168 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11169 case AtomicRMWInst::Sub: 11170 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11171 case AtomicRMWInst::Nand: 11172 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11173 case AtomicRMWInst::Max: 11174 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11175 case AtomicRMWInst::Min: 11176 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11177 case AtomicRMWInst::UMax: 11178 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11179 case AtomicRMWInst::UMin: 11180 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11181 } 11182 } 11183 11184 if (XLen == 64) { 11185 switch (BinOp) { 11186 default: 11187 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11188 case AtomicRMWInst::Xchg: 11189 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11190 case AtomicRMWInst::Add: 11191 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11192 case AtomicRMWInst::Sub: 11193 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11194 case AtomicRMWInst::Nand: 11195 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11196 case AtomicRMWInst::Max: 11197 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11198 case AtomicRMWInst::Min: 11199 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11200 case AtomicRMWInst::UMax: 11201 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11202 case AtomicRMWInst::UMin: 11203 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11204 } 11205 } 11206 11207 llvm_unreachable("Unexpected XLen\n"); 11208 } 11209 11210 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11211 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11212 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11213 unsigned XLen = Subtarget.getXLen(); 11214 Value *Ordering = 11215 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11216 Type *Tys[] = {AlignedAddr->getType()}; 11217 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11218 AI->getModule(), 11219 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11220 11221 if (XLen == 64) { 11222 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11223 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11224 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11225 } 11226 11227 Value *Result; 11228 11229 // Must pass the shift amount needed to sign extend the loaded value prior 11230 // to performing a signed comparison for min/max. ShiftAmt is the number of 11231 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11232 // is the number of bits to left+right shift the value in order to 11233 // sign-extend. 11234 if (AI->getOperation() == AtomicRMWInst::Min || 11235 AI->getOperation() == AtomicRMWInst::Max) { 11236 const DataLayout &DL = AI->getModule()->getDataLayout(); 11237 unsigned ValWidth = 11238 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11239 Value *SextShamt = 11240 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11241 Result = Builder.CreateCall(LrwOpScwLoop, 11242 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11243 } else { 11244 Result = 11245 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11246 } 11247 11248 if (XLen == 64) 11249 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11250 return Result; 11251 } 11252 11253 TargetLowering::AtomicExpansionKind 11254 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11255 AtomicCmpXchgInst *CI) const { 11256 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11257 if (Size == 8 || Size == 16) 11258 return AtomicExpansionKind::MaskedIntrinsic; 11259 return AtomicExpansionKind::None; 11260 } 11261 11262 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11263 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11264 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11265 unsigned XLen = Subtarget.getXLen(); 11266 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11267 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11268 if (XLen == 64) { 11269 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11270 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11271 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11272 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11273 } 11274 Type *Tys[] = {AlignedAddr->getType()}; 11275 Function *MaskedCmpXchg = 11276 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11277 Value *Result = Builder.CreateCall( 11278 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11279 if (XLen == 64) 11280 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11281 return Result; 11282 } 11283 11284 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11285 return false; 11286 } 11287 11288 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11289 EVT VT) const { 11290 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11291 return false; 11292 11293 switch (FPVT.getSimpleVT().SimpleTy) { 11294 case MVT::f16: 11295 return Subtarget.hasStdExtZfh(); 11296 case MVT::f32: 11297 return Subtarget.hasStdExtF(); 11298 case MVT::f64: 11299 return Subtarget.hasStdExtD(); 11300 default: 11301 return false; 11302 } 11303 } 11304 11305 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11306 // If we are using the small code model, we can reduce size of jump table 11307 // entry to 4 bytes. 11308 if (Subtarget.is64Bit() && !isPositionIndependent() && 11309 getTargetMachine().getCodeModel() == CodeModel::Small) { 11310 return MachineJumpTableInfo::EK_Custom32; 11311 } 11312 return TargetLowering::getJumpTableEncoding(); 11313 } 11314 11315 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11316 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11317 unsigned uid, MCContext &Ctx) const { 11318 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11319 getTargetMachine().getCodeModel() == CodeModel::Small); 11320 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11321 } 11322 11323 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11324 EVT VT) const { 11325 VT = VT.getScalarType(); 11326 11327 if (!VT.isSimple()) 11328 return false; 11329 11330 switch (VT.getSimpleVT().SimpleTy) { 11331 case MVT::f16: 11332 return Subtarget.hasStdExtZfh(); 11333 case MVT::f32: 11334 return Subtarget.hasStdExtF(); 11335 case MVT::f64: 11336 return Subtarget.hasStdExtD(); 11337 default: 11338 break; 11339 } 11340 11341 return false; 11342 } 11343 11344 Register RISCVTargetLowering::getExceptionPointerRegister( 11345 const Constant *PersonalityFn) const { 11346 return RISCV::X10; 11347 } 11348 11349 Register RISCVTargetLowering::getExceptionSelectorRegister( 11350 const Constant *PersonalityFn) const { 11351 return RISCV::X11; 11352 } 11353 11354 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11355 // Return false to suppress the unnecessary extensions if the LibCall 11356 // arguments or return value is f32 type for LP64 ABI. 11357 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11358 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11359 return false; 11360 11361 return true; 11362 } 11363 11364 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11365 if (Subtarget.is64Bit() && Type == MVT::i32) 11366 return true; 11367 11368 return IsSigned; 11369 } 11370 11371 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11372 SDValue C) const { 11373 // Check integral scalar types. 11374 if (VT.isScalarInteger()) { 11375 // Omit the optimization if the sub target has the M extension and the data 11376 // size exceeds XLen. 11377 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11378 return false; 11379 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11380 // Break the MUL to a SLLI and an ADD/SUB. 11381 const APInt &Imm = ConstNode->getAPIntValue(); 11382 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11383 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11384 return true; 11385 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11386 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11387 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11388 (Imm - 8).isPowerOf2())) 11389 return true; 11390 // Omit the following optimization if the sub target has the M extension 11391 // and the data size >= XLen. 11392 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11393 return false; 11394 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11395 // a pair of LUI/ADDI. 11396 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11397 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11398 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11399 (1 - ImmS).isPowerOf2()) 11400 return true; 11401 } 11402 } 11403 } 11404 11405 return false; 11406 } 11407 11408 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11409 SDValue ConstNode) const { 11410 // Let the DAGCombiner decide for vectors. 11411 EVT VT = AddNode.getValueType(); 11412 if (VT.isVector()) 11413 return true; 11414 11415 // Let the DAGCombiner decide for larger types. 11416 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11417 return true; 11418 11419 // It is worse if c1 is simm12 while c1*c2 is not. 11420 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11421 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11422 const APInt &C1 = C1Node->getAPIntValue(); 11423 const APInt &C2 = C2Node->getAPIntValue(); 11424 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11425 return false; 11426 11427 // Default to true and let the DAGCombiner decide. 11428 return true; 11429 } 11430 11431 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11432 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11433 bool *Fast) const { 11434 if (!VT.isVector()) 11435 return false; 11436 11437 EVT ElemVT = VT.getVectorElementType(); 11438 if (Alignment >= ElemVT.getStoreSize()) { 11439 if (Fast) 11440 *Fast = true; 11441 return true; 11442 } 11443 11444 return false; 11445 } 11446 11447 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11448 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11449 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11450 bool IsABIRegCopy = CC.hasValue(); 11451 EVT ValueVT = Val.getValueType(); 11452 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11453 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11454 // and cast to f32. 11455 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11456 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11457 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11458 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11459 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11460 Parts[0] = Val; 11461 return true; 11462 } 11463 11464 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11465 LLVMContext &Context = *DAG.getContext(); 11466 EVT ValueEltVT = ValueVT.getVectorElementType(); 11467 EVT PartEltVT = PartVT.getVectorElementType(); 11468 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11469 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11470 if (PartVTBitSize % ValueVTBitSize == 0) { 11471 assert(PartVTBitSize >= ValueVTBitSize); 11472 // If the element types are different, bitcast to the same element type of 11473 // PartVT first. 11474 // Give an example here, we want copy a <vscale x 1 x i8> value to 11475 // <vscale x 4 x i16>. 11476 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11477 // subvector, then we can bitcast to <vscale x 4 x i16>. 11478 if (ValueEltVT != PartEltVT) { 11479 if (PartVTBitSize > ValueVTBitSize) { 11480 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11481 assert(Count != 0 && "The number of element should not be zero."); 11482 EVT SameEltTypeVT = 11483 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11484 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11485 DAG.getUNDEF(SameEltTypeVT), Val, 11486 DAG.getVectorIdxConstant(0, DL)); 11487 } 11488 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11489 } else { 11490 Val = 11491 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11492 Val, DAG.getVectorIdxConstant(0, DL)); 11493 } 11494 Parts[0] = Val; 11495 return true; 11496 } 11497 } 11498 return false; 11499 } 11500 11501 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11502 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11503 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11504 bool IsABIRegCopy = CC.hasValue(); 11505 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11506 SDValue Val = Parts[0]; 11507 11508 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11509 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11510 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11511 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11512 return Val; 11513 } 11514 11515 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11516 LLVMContext &Context = *DAG.getContext(); 11517 SDValue Val = Parts[0]; 11518 EVT ValueEltVT = ValueVT.getVectorElementType(); 11519 EVT PartEltVT = PartVT.getVectorElementType(); 11520 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11521 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11522 if (PartVTBitSize % ValueVTBitSize == 0) { 11523 assert(PartVTBitSize >= ValueVTBitSize); 11524 EVT SameEltTypeVT = ValueVT; 11525 // If the element types are different, convert it to the same element type 11526 // of PartVT. 11527 // Give an example here, we want copy a <vscale x 1 x i8> value from 11528 // <vscale x 4 x i16>. 11529 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11530 // then we can extract <vscale x 1 x i8>. 11531 if (ValueEltVT != PartEltVT) { 11532 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11533 assert(Count != 0 && "The number of element should not be zero."); 11534 SameEltTypeVT = 11535 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11536 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11537 } 11538 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11539 DAG.getVectorIdxConstant(0, DL)); 11540 return Val; 11541 } 11542 } 11543 return SDValue(); 11544 } 11545 11546 SDValue 11547 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11548 SelectionDAG &DAG, 11549 SmallVectorImpl<SDNode *> &Created) const { 11550 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11551 if (isIntDivCheap(N->getValueType(0), Attr)) 11552 return SDValue(N, 0); // Lower SDIV as SDIV 11553 11554 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11555 "Unexpected divisor!"); 11556 11557 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11558 if (!Subtarget.hasStdExtZbt()) 11559 return SDValue(); 11560 11561 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11562 // Besides, more critical path instructions will be generated when dividing 11563 // by 2. So we keep using the original DAGs for these cases. 11564 unsigned Lg2 = Divisor.countTrailingZeros(); 11565 if (Lg2 == 1 || Lg2 >= 12) 11566 return SDValue(); 11567 11568 // fold (sdiv X, pow2) 11569 EVT VT = N->getValueType(0); 11570 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11571 return SDValue(); 11572 11573 SDLoc DL(N); 11574 SDValue N0 = N->getOperand(0); 11575 SDValue Zero = DAG.getConstant(0, DL, VT); 11576 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11577 11578 // Add (N0 < 0) ? Pow2 - 1 : 0; 11579 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11580 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11581 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11582 11583 Created.push_back(Cmp.getNode()); 11584 Created.push_back(Add.getNode()); 11585 Created.push_back(Sel.getNode()); 11586 11587 // Divide by pow2. 11588 SDValue SRA = 11589 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11590 11591 // If we're dividing by a positive value, we're done. Otherwise, we must 11592 // negate the result. 11593 if (Divisor.isNonNegative()) 11594 return SRA; 11595 11596 Created.push_back(SRA.getNode()); 11597 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11598 } 11599 11600 #define GET_REGISTER_MATCHER 11601 #include "RISCVGenAsmMatcher.inc" 11602 11603 Register 11604 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11605 const MachineFunction &MF) const { 11606 Register Reg = MatchRegisterAltName(RegName); 11607 if (Reg == RISCV::NoRegister) 11608 Reg = MatchRegisterName(RegName); 11609 if (Reg == RISCV::NoRegister) 11610 report_fatal_error( 11611 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11612 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11613 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11614 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11615 StringRef(RegName) + "\".")); 11616 return Reg; 11617 } 11618 11619 namespace llvm { 11620 namespace RISCVVIntrinsicsTable { 11621 11622 #define GET_RISCVVIntrinsicsTable_IMPL 11623 #include "RISCVGenSearchableTables.inc" 11624 11625 } // namespace RISCVVIntrinsicsTable 11626 11627 } // namespace llvm 11628