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->hasSplatOperand()) 4576 return SDValue(); 4577 4578 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4579 assert(SplatOp < Op.getNumOperands()); 4580 4581 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4582 SDValue &ScalarOp = Operands[SplatOp]; 4583 MVT OpVT = ScalarOp.getSimpleValueType(); 4584 MVT XLenVT = Subtarget.getXLenVT(); 4585 4586 // If this isn't a scalar, or its type is XLenVT we're done. 4587 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4588 return SDValue(); 4589 4590 // Simplest case is that the operand needs to be promoted to XLenVT. 4591 if (OpVT.bitsLT(XLenVT)) { 4592 // If the operand is a constant, sign extend to increase our chances 4593 // of being able to use a .vi instruction. ANY_EXTEND would become a 4594 // a zero extend and the simm5 check in isel would fail. 4595 // FIXME: Should we ignore the upper bits in isel instead? 4596 unsigned ExtOpc = 4597 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4598 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4599 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4600 } 4601 4602 // Use the previous operand to get the vXi64 VT. The result might be a mask 4603 // VT for compares. Using the previous operand assumes that the previous 4604 // operand will never have a smaller element size than a scalar operand and 4605 // that a widening operation never uses SEW=64. 4606 // NOTE: If this fails the below assert, we can probably just find the 4607 // element count from any operand or result and use it to construct the VT. 4608 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4609 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4610 4611 // The more complex case is when the scalar is larger than XLenVT. 4612 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4613 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4614 4615 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4616 // on the instruction to sign-extend since SEW>XLEN. 4617 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4618 if (isInt<32>(CVal->getSExtValue())) { 4619 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4620 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4621 } 4622 } 4623 4624 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::FMV_X_ANYEXTH: 8211 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8212 SDLoc DL(N); 8213 SDValue Op0 = N->getOperand(0); 8214 MVT VT = N->getSimpleValueType(0); 8215 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8216 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8217 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8218 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8219 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8220 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8221 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8222 assert(Op0.getOperand(0).getValueType() == VT && 8223 "Unexpected value type!"); 8224 return Op0.getOperand(0); 8225 } 8226 8227 // This is a target-specific version of a DAGCombine performed in 8228 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8229 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8230 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8231 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8232 !Op0.getNode()->hasOneUse()) 8233 break; 8234 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8235 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8236 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8237 if (Op0.getOpcode() == ISD::FNEG) 8238 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8239 DAG.getConstant(SignBit, DL, VT)); 8240 8241 assert(Op0.getOpcode() == ISD::FABS); 8242 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8243 DAG.getConstant(~SignBit, DL, VT)); 8244 } 8245 case ISD::ADD: 8246 return performADDCombine(N, DAG, Subtarget); 8247 case ISD::SUB: 8248 return performSUBCombine(N, DAG); 8249 case ISD::AND: 8250 return performANDCombine(N, DAG); 8251 case ISD::OR: 8252 return performORCombine(N, DAG, Subtarget); 8253 case ISD::XOR: 8254 return performXORCombine(N, DAG); 8255 case ISD::SIGN_EXTEND_INREG: 8256 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8257 case ISD::ANY_EXTEND: 8258 return performANY_EXTENDCombine(N, DCI, Subtarget); 8259 case ISD::ZERO_EXTEND: 8260 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8261 // type legalization. This is safe because fp_to_uint produces poison if 8262 // it overflows. 8263 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8264 SDValue Src = N->getOperand(0); 8265 if (Src.getOpcode() == ISD::FP_TO_UINT && 8266 isTypeLegal(Src.getOperand(0).getValueType())) 8267 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8268 Src.getOperand(0)); 8269 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8270 isTypeLegal(Src.getOperand(1).getValueType())) { 8271 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8272 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8273 Src.getOperand(0), Src.getOperand(1)); 8274 DCI.CombineTo(N, Res); 8275 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8276 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8277 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8278 } 8279 } 8280 return SDValue(); 8281 case RISCVISD::SELECT_CC: { 8282 // Transform 8283 SDValue LHS = N->getOperand(0); 8284 SDValue RHS = N->getOperand(1); 8285 SDValue TrueV = N->getOperand(3); 8286 SDValue FalseV = N->getOperand(4); 8287 8288 // If the True and False values are the same, we don't need a select_cc. 8289 if (TrueV == FalseV) 8290 return TrueV; 8291 8292 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8293 if (!ISD::isIntEqualitySetCC(CCVal)) 8294 break; 8295 8296 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8297 // (select_cc X, Y, lt, trueV, falseV) 8298 // Sometimes the setcc is introduced after select_cc has been formed. 8299 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8300 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8301 // If we're looking for eq 0 instead of ne 0, we need to invert the 8302 // condition. 8303 bool Invert = CCVal == ISD::SETEQ; 8304 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8305 if (Invert) 8306 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8307 8308 SDLoc DL(N); 8309 RHS = LHS.getOperand(1); 8310 LHS = LHS.getOperand(0); 8311 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8312 8313 SDValue TargetCC = DAG.getCondCode(CCVal); 8314 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8315 {LHS, RHS, TargetCC, TrueV, FalseV}); 8316 } 8317 8318 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8319 // (select_cc X, Y, eq/ne, trueV, falseV) 8320 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8321 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8322 {LHS.getOperand(0), LHS.getOperand(1), 8323 N->getOperand(2), TrueV, FalseV}); 8324 // (select_cc X, 1, setne, trueV, falseV) -> 8325 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8326 // This can occur when legalizing some floating point comparisons. 8327 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8328 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8329 SDLoc DL(N); 8330 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8331 SDValue TargetCC = DAG.getCondCode(CCVal); 8332 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8333 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8334 {LHS, RHS, TargetCC, TrueV, FalseV}); 8335 } 8336 8337 break; 8338 } 8339 case RISCVISD::BR_CC: { 8340 SDValue LHS = N->getOperand(1); 8341 SDValue RHS = N->getOperand(2); 8342 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8343 if (!ISD::isIntEqualitySetCC(CCVal)) 8344 break; 8345 8346 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8347 // (br_cc X, Y, lt, dest) 8348 // Sometimes the setcc is introduced after br_cc has been formed. 8349 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8350 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8351 // If we're looking for eq 0 instead of ne 0, we need to invert the 8352 // condition. 8353 bool Invert = CCVal == ISD::SETEQ; 8354 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8355 if (Invert) 8356 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8357 8358 SDLoc DL(N); 8359 RHS = LHS.getOperand(1); 8360 LHS = LHS.getOperand(0); 8361 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8362 8363 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8364 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8365 N->getOperand(4)); 8366 } 8367 8368 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8369 // (br_cc X, Y, eq/ne, trueV, falseV) 8370 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8371 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8372 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8373 N->getOperand(3), N->getOperand(4)); 8374 8375 // (br_cc X, 1, setne, br_cc) -> 8376 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8377 // This can occur when legalizing some floating point comparisons. 8378 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8379 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8380 SDLoc DL(N); 8381 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8382 SDValue TargetCC = DAG.getCondCode(CCVal); 8383 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8384 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8385 N->getOperand(0), LHS, RHS, TargetCC, 8386 N->getOperand(4)); 8387 } 8388 break; 8389 } 8390 case ISD::FP_TO_SINT: 8391 case ISD::FP_TO_UINT: 8392 return performFP_TO_INTCombine(N, DCI, Subtarget); 8393 case ISD::FP_TO_SINT_SAT: 8394 case ISD::FP_TO_UINT_SAT: 8395 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8396 case ISD::FCOPYSIGN: { 8397 EVT VT = N->getValueType(0); 8398 if (!VT.isVector()) 8399 break; 8400 // There is a form of VFSGNJ which injects the negated sign of its second 8401 // operand. Try and bubble any FNEG up after the extend/round to produce 8402 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8403 // TRUNC=1. 8404 SDValue In2 = N->getOperand(1); 8405 // Avoid cases where the extend/round has multiple uses, as duplicating 8406 // those is typically more expensive than removing a fneg. 8407 if (!In2.hasOneUse()) 8408 break; 8409 if (In2.getOpcode() != ISD::FP_EXTEND && 8410 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8411 break; 8412 In2 = In2.getOperand(0); 8413 if (In2.getOpcode() != ISD::FNEG) 8414 break; 8415 SDLoc DL(N); 8416 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8417 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8418 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8419 } 8420 case ISD::MGATHER: 8421 case ISD::MSCATTER: 8422 case ISD::VP_GATHER: 8423 case ISD::VP_SCATTER: { 8424 if (!DCI.isBeforeLegalize()) 8425 break; 8426 SDValue Index, ScaleOp; 8427 bool IsIndexScaled = false; 8428 bool IsIndexSigned = false; 8429 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8430 Index = VPGSN->getIndex(); 8431 ScaleOp = VPGSN->getScale(); 8432 IsIndexScaled = VPGSN->isIndexScaled(); 8433 IsIndexSigned = VPGSN->isIndexSigned(); 8434 } else { 8435 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8436 Index = MGSN->getIndex(); 8437 ScaleOp = MGSN->getScale(); 8438 IsIndexScaled = MGSN->isIndexScaled(); 8439 IsIndexSigned = MGSN->isIndexSigned(); 8440 } 8441 EVT IndexVT = Index.getValueType(); 8442 MVT XLenVT = Subtarget.getXLenVT(); 8443 // RISCV indexed loads only support the "unsigned unscaled" addressing 8444 // mode, so anything else must be manually legalized. 8445 bool NeedsIdxLegalization = 8446 IsIndexScaled || 8447 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8448 if (!NeedsIdxLegalization) 8449 break; 8450 8451 SDLoc DL(N); 8452 8453 // Any index legalization should first promote to XLenVT, so we don't lose 8454 // bits when scaling. This may create an illegal index type so we let 8455 // LLVM's legalization take care of the splitting. 8456 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8457 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8458 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8459 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8460 DL, IndexVT, Index); 8461 } 8462 8463 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8464 if (IsIndexScaled && Scale != 1) { 8465 // Manually scale the indices by the element size. 8466 // TODO: Sanitize the scale operand here? 8467 // TODO: For VP nodes, should we use VP_SHL here? 8468 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8469 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8470 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8471 } 8472 8473 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8474 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8475 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8476 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8477 VPGN->getScale(), VPGN->getMask(), 8478 VPGN->getVectorLength()}, 8479 VPGN->getMemOperand(), NewIndexTy); 8480 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8481 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8482 {VPSN->getChain(), VPSN->getValue(), 8483 VPSN->getBasePtr(), Index, VPSN->getScale(), 8484 VPSN->getMask(), VPSN->getVectorLength()}, 8485 VPSN->getMemOperand(), NewIndexTy); 8486 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8487 return DAG.getMaskedGather( 8488 N->getVTList(), MGN->getMemoryVT(), DL, 8489 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8490 MGN->getBasePtr(), Index, MGN->getScale()}, 8491 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8492 const auto *MSN = cast<MaskedScatterSDNode>(N); 8493 return DAG.getMaskedScatter( 8494 N->getVTList(), MSN->getMemoryVT(), DL, 8495 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8496 Index, MSN->getScale()}, 8497 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8498 } 8499 case RISCVISD::SRA_VL: 8500 case RISCVISD::SRL_VL: 8501 case RISCVISD::SHL_VL: { 8502 SDValue ShAmt = N->getOperand(1); 8503 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8504 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8505 SDLoc DL(N); 8506 SDValue VL = N->getOperand(3); 8507 EVT VT = N->getValueType(0); 8508 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8509 ShAmt.getOperand(1), VL); 8510 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8511 N->getOperand(2), N->getOperand(3)); 8512 } 8513 break; 8514 } 8515 case ISD::SRA: 8516 case ISD::SRL: 8517 case ISD::SHL: { 8518 SDValue ShAmt = N->getOperand(1); 8519 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8520 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8521 SDLoc DL(N); 8522 EVT VT = N->getValueType(0); 8523 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8524 ShAmt.getOperand(1), 8525 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8526 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8527 } 8528 break; 8529 } 8530 case RISCVISD::ADD_VL: 8531 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8532 return V; 8533 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8534 case RISCVISD::SUB_VL: 8535 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8536 case RISCVISD::VWADD_W_VL: 8537 case RISCVISD::VWADDU_W_VL: 8538 case RISCVISD::VWSUB_W_VL: 8539 case RISCVISD::VWSUBU_W_VL: 8540 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8541 case RISCVISD::MUL_VL: 8542 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8543 return V; 8544 // Mul is commutative. 8545 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8546 case ISD::STORE: { 8547 auto *Store = cast<StoreSDNode>(N); 8548 SDValue Val = Store->getValue(); 8549 // Combine store of vmv.x.s to vse with VL of 1. 8550 // FIXME: Support FP. 8551 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8552 SDValue Src = Val.getOperand(0); 8553 EVT VecVT = Src.getValueType(); 8554 EVT MemVT = Store->getMemoryVT(); 8555 // The memory VT and the element type must match. 8556 if (VecVT.getVectorElementType() == MemVT) { 8557 SDLoc DL(N); 8558 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8559 return DAG.getStoreVP( 8560 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8561 DAG.getConstant(1, DL, MaskVT), 8562 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8563 Store->getMemOperand(), Store->getAddressingMode(), 8564 Store->isTruncatingStore(), /*IsCompress*/ false); 8565 } 8566 } 8567 8568 break; 8569 } 8570 case ISD::SPLAT_VECTOR: { 8571 EVT VT = N->getValueType(0); 8572 // Only perform this combine on legal MVT types. 8573 if (!isTypeLegal(VT)) 8574 break; 8575 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8576 DAG, Subtarget)) 8577 return Gather; 8578 break; 8579 } 8580 case RISCVISD::VMV_V_X_VL: { 8581 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8582 // scalar input. 8583 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8584 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8585 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8586 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8587 return SDValue(N, 0); 8588 8589 break; 8590 } 8591 case ISD::INTRINSIC_WO_CHAIN: { 8592 unsigned IntNo = N->getConstantOperandVal(0); 8593 switch (IntNo) { 8594 // By default we do not combine any intrinsic. 8595 default: 8596 return SDValue(); 8597 case Intrinsic::riscv_vcpop: 8598 case Intrinsic::riscv_vcpop_mask: 8599 case Intrinsic::riscv_vfirst: 8600 case Intrinsic::riscv_vfirst_mask: { 8601 SDValue VL = N->getOperand(2); 8602 if (IntNo == Intrinsic::riscv_vcpop_mask || 8603 IntNo == Intrinsic::riscv_vfirst_mask) 8604 VL = N->getOperand(3); 8605 if (!isNullConstant(VL)) 8606 return SDValue(); 8607 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8608 SDLoc DL(N); 8609 EVT VT = N->getValueType(0); 8610 if (IntNo == Intrinsic::riscv_vfirst || 8611 IntNo == Intrinsic::riscv_vfirst_mask) 8612 return DAG.getConstant(-1, DL, VT); 8613 return DAG.getConstant(0, DL, VT); 8614 } 8615 } 8616 } 8617 } 8618 8619 return SDValue(); 8620 } 8621 8622 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8623 const SDNode *N, CombineLevel Level) const { 8624 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8625 // materialised in fewer instructions than `(OP _, c1)`: 8626 // 8627 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8628 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8629 SDValue N0 = N->getOperand(0); 8630 EVT Ty = N0.getValueType(); 8631 if (Ty.isScalarInteger() && 8632 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8633 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8634 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8635 if (C1 && C2) { 8636 const APInt &C1Int = C1->getAPIntValue(); 8637 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8638 8639 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8640 // and the combine should happen, to potentially allow further combines 8641 // later. 8642 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8643 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8644 return true; 8645 8646 // We can materialise `c1` in an add immediate, so it's "free", and the 8647 // combine should be prevented. 8648 if (C1Int.getMinSignedBits() <= 64 && 8649 isLegalAddImmediate(C1Int.getSExtValue())) 8650 return false; 8651 8652 // Neither constant will fit into an immediate, so find materialisation 8653 // costs. 8654 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8655 Subtarget.getFeatureBits(), 8656 /*CompressionCost*/true); 8657 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8658 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8659 /*CompressionCost*/true); 8660 8661 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8662 // combine should be prevented. 8663 if (C1Cost < ShiftedC1Cost) 8664 return false; 8665 } 8666 } 8667 return true; 8668 } 8669 8670 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8671 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8672 TargetLoweringOpt &TLO) const { 8673 // Delay this optimization as late as possible. 8674 if (!TLO.LegalOps) 8675 return false; 8676 8677 EVT VT = Op.getValueType(); 8678 if (VT.isVector()) 8679 return false; 8680 8681 // Only handle AND for now. 8682 if (Op.getOpcode() != ISD::AND) 8683 return false; 8684 8685 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8686 if (!C) 8687 return false; 8688 8689 const APInt &Mask = C->getAPIntValue(); 8690 8691 // Clear all non-demanded bits initially. 8692 APInt ShrunkMask = Mask & DemandedBits; 8693 8694 // Try to make a smaller immediate by setting undemanded bits. 8695 8696 APInt ExpandedMask = Mask | ~DemandedBits; 8697 8698 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8699 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8700 }; 8701 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8702 if (NewMask == Mask) 8703 return true; 8704 SDLoc DL(Op); 8705 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8706 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8707 return TLO.CombineTo(Op, NewOp); 8708 }; 8709 8710 // If the shrunk mask fits in sign extended 12 bits, let the target 8711 // independent code apply it. 8712 if (ShrunkMask.isSignedIntN(12)) 8713 return false; 8714 8715 // Preserve (and X, 0xffff) when zext.h is supported. 8716 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8717 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8718 if (IsLegalMask(NewMask)) 8719 return UseMask(NewMask); 8720 } 8721 8722 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8723 if (VT == MVT::i64) { 8724 APInt NewMask = APInt(64, 0xffffffff); 8725 if (IsLegalMask(NewMask)) 8726 return UseMask(NewMask); 8727 } 8728 8729 // For the remaining optimizations, we need to be able to make a negative 8730 // number through a combination of mask and undemanded bits. 8731 if (!ExpandedMask.isNegative()) 8732 return false; 8733 8734 // What is the fewest number of bits we need to represent the negative number. 8735 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8736 8737 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8738 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8739 APInt NewMask = ShrunkMask; 8740 if (MinSignedBits <= 12) 8741 NewMask.setBitsFrom(11); 8742 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8743 NewMask.setBitsFrom(31); 8744 else 8745 return false; 8746 8747 // Check that our new mask is a subset of the demanded mask. 8748 assert(IsLegalMask(NewMask)); 8749 return UseMask(NewMask); 8750 } 8751 8752 static void computeGREV(APInt &Src, unsigned ShAmt) { 8753 ShAmt &= Src.getBitWidth() - 1; 8754 uint64_t x = Src.getZExtValue(); 8755 if (ShAmt & 1) 8756 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8757 if (ShAmt & 2) 8758 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8759 if (ShAmt & 4) 8760 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8761 if (ShAmt & 8) 8762 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8763 if (ShAmt & 16) 8764 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8765 if (ShAmt & 32) 8766 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8767 Src = x; 8768 } 8769 8770 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8771 KnownBits &Known, 8772 const APInt &DemandedElts, 8773 const SelectionDAG &DAG, 8774 unsigned Depth) const { 8775 unsigned BitWidth = Known.getBitWidth(); 8776 unsigned Opc = Op.getOpcode(); 8777 assert((Opc >= ISD::BUILTIN_OP_END || 8778 Opc == ISD::INTRINSIC_WO_CHAIN || 8779 Opc == ISD::INTRINSIC_W_CHAIN || 8780 Opc == ISD::INTRINSIC_VOID) && 8781 "Should use MaskedValueIsZero if you don't know whether Op" 8782 " is a target node!"); 8783 8784 Known.resetAll(); 8785 switch (Opc) { 8786 default: break; 8787 case RISCVISD::SELECT_CC: { 8788 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8789 // If we don't know any bits, early out. 8790 if (Known.isUnknown()) 8791 break; 8792 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8793 8794 // Only known if known in both the LHS and RHS. 8795 Known = KnownBits::commonBits(Known, Known2); 8796 break; 8797 } 8798 case RISCVISD::REMUW: { 8799 KnownBits Known2; 8800 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8801 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8802 // We only care about the lower 32 bits. 8803 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8804 // Restore the original width by sign extending. 8805 Known = Known.sext(BitWidth); 8806 break; 8807 } 8808 case RISCVISD::DIVUW: { 8809 KnownBits Known2; 8810 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8811 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8812 // We only care about the lower 32 bits. 8813 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8814 // Restore the original width by sign extending. 8815 Known = Known.sext(BitWidth); 8816 break; 8817 } 8818 case RISCVISD::CTZW: { 8819 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8820 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8821 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8822 Known.Zero.setBitsFrom(LowBits); 8823 break; 8824 } 8825 case RISCVISD::CLZW: { 8826 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8827 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8828 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8829 Known.Zero.setBitsFrom(LowBits); 8830 break; 8831 } 8832 case RISCVISD::GREV: 8833 case RISCVISD::GREVW: { 8834 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8835 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8836 if (Opc == RISCVISD::GREVW) 8837 Known = Known.trunc(32); 8838 unsigned ShAmt = C->getZExtValue(); 8839 computeGREV(Known.Zero, ShAmt); 8840 computeGREV(Known.One, ShAmt); 8841 if (Opc == RISCVISD::GREVW) 8842 Known = Known.sext(BitWidth); 8843 } 8844 break; 8845 } 8846 case RISCVISD::READ_VLENB: { 8847 // If we know the minimum VLen from Zvl extensions, we can use that to 8848 // determine the trailing zeros of VLENB. 8849 // FIXME: Limit to 128 bit vectors until we have more testing. 8850 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8851 if (MinVLenB > 0) 8852 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8853 // We assume VLENB is no more than 65536 / 8 bytes. 8854 Known.Zero.setBitsFrom(14); 8855 break; 8856 } 8857 case ISD::INTRINSIC_W_CHAIN: 8858 case ISD::INTRINSIC_WO_CHAIN: { 8859 unsigned IntNo = 8860 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8861 switch (IntNo) { 8862 default: 8863 // We can't do anything for most intrinsics. 8864 break; 8865 case Intrinsic::riscv_vsetvli: 8866 case Intrinsic::riscv_vsetvlimax: 8867 case Intrinsic::riscv_vsetvli_opt: 8868 case Intrinsic::riscv_vsetvlimax_opt: 8869 // Assume that VL output is positive and would fit in an int32_t. 8870 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8871 if (BitWidth >= 32) 8872 Known.Zero.setBitsFrom(31); 8873 break; 8874 } 8875 break; 8876 } 8877 } 8878 } 8879 8880 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8881 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8882 unsigned Depth) const { 8883 switch (Op.getOpcode()) { 8884 default: 8885 break; 8886 case RISCVISD::SELECT_CC: { 8887 unsigned Tmp = 8888 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8889 if (Tmp == 1) return 1; // Early out. 8890 unsigned Tmp2 = 8891 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8892 return std::min(Tmp, Tmp2); 8893 } 8894 case RISCVISD::SLLW: 8895 case RISCVISD::SRAW: 8896 case RISCVISD::SRLW: 8897 case RISCVISD::DIVW: 8898 case RISCVISD::DIVUW: 8899 case RISCVISD::REMUW: 8900 case RISCVISD::ROLW: 8901 case RISCVISD::RORW: 8902 case RISCVISD::GREVW: 8903 case RISCVISD::GORCW: 8904 case RISCVISD::FSLW: 8905 case RISCVISD::FSRW: 8906 case RISCVISD::SHFLW: 8907 case RISCVISD::UNSHFLW: 8908 case RISCVISD::BCOMPRESSW: 8909 case RISCVISD::BDECOMPRESSW: 8910 case RISCVISD::BFPW: 8911 case RISCVISD::FCVT_W_RV64: 8912 case RISCVISD::FCVT_WU_RV64: 8913 case RISCVISD::STRICT_FCVT_W_RV64: 8914 case RISCVISD::STRICT_FCVT_WU_RV64: 8915 // TODO: As the result is sign-extended, this is conservatively correct. A 8916 // more precise answer could be calculated for SRAW depending on known 8917 // bits in the shift amount. 8918 return 33; 8919 case RISCVISD::SHFL: 8920 case RISCVISD::UNSHFL: { 8921 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8922 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8923 // will stay within the upper 32 bits. If there were more than 32 sign bits 8924 // before there will be at least 33 sign bits after. 8925 if (Op.getValueType() == MVT::i64 && 8926 isa<ConstantSDNode>(Op.getOperand(1)) && 8927 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8928 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8929 if (Tmp > 32) 8930 return 33; 8931 } 8932 break; 8933 } 8934 case RISCVISD::VMV_X_S: { 8935 // The number of sign bits of the scalar result is computed by obtaining the 8936 // element type of the input vector operand, subtracting its width from the 8937 // XLEN, and then adding one (sign bit within the element type). If the 8938 // element type is wider than XLen, the least-significant XLEN bits are 8939 // taken. 8940 unsigned XLen = Subtarget.getXLen(); 8941 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8942 if (EltBits <= XLen) 8943 return XLen - EltBits + 1; 8944 break; 8945 } 8946 } 8947 8948 return 1; 8949 } 8950 8951 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8952 MachineBasicBlock *BB) { 8953 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8954 8955 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8956 // Should the count have wrapped while it was being read, we need to try 8957 // again. 8958 // ... 8959 // read: 8960 // rdcycleh x3 # load high word of cycle 8961 // rdcycle x2 # load low word of cycle 8962 // rdcycleh x4 # load high word of cycle 8963 // bne x3, x4, read # check if high word reads match, otherwise try again 8964 // ... 8965 8966 MachineFunction &MF = *BB->getParent(); 8967 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8968 MachineFunction::iterator It = ++BB->getIterator(); 8969 8970 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8971 MF.insert(It, LoopMBB); 8972 8973 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8974 MF.insert(It, DoneMBB); 8975 8976 // Transfer the remainder of BB and its successor edges to DoneMBB. 8977 DoneMBB->splice(DoneMBB->begin(), BB, 8978 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8979 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8980 8981 BB->addSuccessor(LoopMBB); 8982 8983 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8984 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8985 Register LoReg = MI.getOperand(0).getReg(); 8986 Register HiReg = MI.getOperand(1).getReg(); 8987 DebugLoc DL = MI.getDebugLoc(); 8988 8989 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8990 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8991 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8992 .addReg(RISCV::X0); 8993 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8994 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8995 .addReg(RISCV::X0); 8996 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8997 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8998 .addReg(RISCV::X0); 8999 9000 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9001 .addReg(HiReg) 9002 .addReg(ReadAgainReg) 9003 .addMBB(LoopMBB); 9004 9005 LoopMBB->addSuccessor(LoopMBB); 9006 LoopMBB->addSuccessor(DoneMBB); 9007 9008 MI.eraseFromParent(); 9009 9010 return DoneMBB; 9011 } 9012 9013 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9014 MachineBasicBlock *BB) { 9015 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9016 9017 MachineFunction &MF = *BB->getParent(); 9018 DebugLoc DL = MI.getDebugLoc(); 9019 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9020 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9021 Register LoReg = MI.getOperand(0).getReg(); 9022 Register HiReg = MI.getOperand(1).getReg(); 9023 Register SrcReg = MI.getOperand(2).getReg(); 9024 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9025 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9026 9027 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9028 RI); 9029 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9030 MachineMemOperand *MMOLo = 9031 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9032 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9033 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9034 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9035 .addFrameIndex(FI) 9036 .addImm(0) 9037 .addMemOperand(MMOLo); 9038 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9039 .addFrameIndex(FI) 9040 .addImm(4) 9041 .addMemOperand(MMOHi); 9042 MI.eraseFromParent(); // The pseudo instruction is gone now. 9043 return BB; 9044 } 9045 9046 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9047 MachineBasicBlock *BB) { 9048 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9049 "Unexpected instruction"); 9050 9051 MachineFunction &MF = *BB->getParent(); 9052 DebugLoc DL = MI.getDebugLoc(); 9053 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9054 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9055 Register DstReg = MI.getOperand(0).getReg(); 9056 Register LoReg = MI.getOperand(1).getReg(); 9057 Register HiReg = MI.getOperand(2).getReg(); 9058 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9059 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9060 9061 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9062 MachineMemOperand *MMOLo = 9063 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9064 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9065 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9066 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9067 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9068 .addFrameIndex(FI) 9069 .addImm(0) 9070 .addMemOperand(MMOLo); 9071 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9072 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9073 .addFrameIndex(FI) 9074 .addImm(4) 9075 .addMemOperand(MMOHi); 9076 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9077 MI.eraseFromParent(); // The pseudo instruction is gone now. 9078 return BB; 9079 } 9080 9081 static bool isSelectPseudo(MachineInstr &MI) { 9082 switch (MI.getOpcode()) { 9083 default: 9084 return false; 9085 case RISCV::Select_GPR_Using_CC_GPR: 9086 case RISCV::Select_FPR16_Using_CC_GPR: 9087 case RISCV::Select_FPR32_Using_CC_GPR: 9088 case RISCV::Select_FPR64_Using_CC_GPR: 9089 return true; 9090 } 9091 } 9092 9093 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9094 unsigned RelOpcode, unsigned EqOpcode, 9095 const RISCVSubtarget &Subtarget) { 9096 DebugLoc DL = MI.getDebugLoc(); 9097 Register DstReg = MI.getOperand(0).getReg(); 9098 Register Src1Reg = MI.getOperand(1).getReg(); 9099 Register Src2Reg = MI.getOperand(2).getReg(); 9100 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9101 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9102 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9103 9104 // Save the current FFLAGS. 9105 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9106 9107 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9108 .addReg(Src1Reg) 9109 .addReg(Src2Reg); 9110 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9111 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9112 9113 // Restore the FFLAGS. 9114 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9115 .addReg(SavedFFlags, RegState::Kill); 9116 9117 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9118 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9119 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9120 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9121 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9122 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9123 9124 // Erase the pseudoinstruction. 9125 MI.eraseFromParent(); 9126 return BB; 9127 } 9128 9129 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9130 MachineBasicBlock *BB, 9131 const RISCVSubtarget &Subtarget) { 9132 // To "insert" Select_* instructions, we actually have to insert the triangle 9133 // control-flow pattern. The incoming instructions know the destination vreg 9134 // to set, the condition code register to branch on, the true/false values to 9135 // select between, and the condcode to use to select the appropriate branch. 9136 // 9137 // We produce the following control flow: 9138 // HeadMBB 9139 // | \ 9140 // | IfFalseMBB 9141 // | / 9142 // TailMBB 9143 // 9144 // When we find a sequence of selects we attempt to optimize their emission 9145 // by sharing the control flow. Currently we only handle cases where we have 9146 // multiple selects with the exact same condition (same LHS, RHS and CC). 9147 // The selects may be interleaved with other instructions if the other 9148 // instructions meet some requirements we deem safe: 9149 // - They are debug instructions. Otherwise, 9150 // - They do not have side-effects, do not access memory and their inputs do 9151 // not depend on the results of the select pseudo-instructions. 9152 // The TrueV/FalseV operands of the selects cannot depend on the result of 9153 // previous selects in the sequence. 9154 // These conditions could be further relaxed. See the X86 target for a 9155 // related approach and more information. 9156 Register LHS = MI.getOperand(1).getReg(); 9157 Register RHS = MI.getOperand(2).getReg(); 9158 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9159 9160 SmallVector<MachineInstr *, 4> SelectDebugValues; 9161 SmallSet<Register, 4> SelectDests; 9162 SelectDests.insert(MI.getOperand(0).getReg()); 9163 9164 MachineInstr *LastSelectPseudo = &MI; 9165 9166 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9167 SequenceMBBI != E; ++SequenceMBBI) { 9168 if (SequenceMBBI->isDebugInstr()) 9169 continue; 9170 else if (isSelectPseudo(*SequenceMBBI)) { 9171 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9172 SequenceMBBI->getOperand(2).getReg() != RHS || 9173 SequenceMBBI->getOperand(3).getImm() != CC || 9174 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9175 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9176 break; 9177 LastSelectPseudo = &*SequenceMBBI; 9178 SequenceMBBI->collectDebugValues(SelectDebugValues); 9179 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9180 } else { 9181 if (SequenceMBBI->hasUnmodeledSideEffects() || 9182 SequenceMBBI->mayLoadOrStore()) 9183 break; 9184 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9185 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9186 })) 9187 break; 9188 } 9189 } 9190 9191 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9192 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9193 DebugLoc DL = MI.getDebugLoc(); 9194 MachineFunction::iterator I = ++BB->getIterator(); 9195 9196 MachineBasicBlock *HeadMBB = BB; 9197 MachineFunction *F = BB->getParent(); 9198 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9199 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9200 9201 F->insert(I, IfFalseMBB); 9202 F->insert(I, TailMBB); 9203 9204 // Transfer debug instructions associated with the selects to TailMBB. 9205 for (MachineInstr *DebugInstr : SelectDebugValues) { 9206 TailMBB->push_back(DebugInstr->removeFromParent()); 9207 } 9208 9209 // Move all instructions after the sequence to TailMBB. 9210 TailMBB->splice(TailMBB->end(), HeadMBB, 9211 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9212 // Update machine-CFG edges by transferring all successors of the current 9213 // block to the new block which will contain the Phi nodes for the selects. 9214 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9215 // Set the successors for HeadMBB. 9216 HeadMBB->addSuccessor(IfFalseMBB); 9217 HeadMBB->addSuccessor(TailMBB); 9218 9219 // Insert appropriate branch. 9220 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9221 .addReg(LHS) 9222 .addReg(RHS) 9223 .addMBB(TailMBB); 9224 9225 // IfFalseMBB just falls through to TailMBB. 9226 IfFalseMBB->addSuccessor(TailMBB); 9227 9228 // Create PHIs for all of the select pseudo-instructions. 9229 auto SelectMBBI = MI.getIterator(); 9230 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9231 auto InsertionPoint = TailMBB->begin(); 9232 while (SelectMBBI != SelectEnd) { 9233 auto Next = std::next(SelectMBBI); 9234 if (isSelectPseudo(*SelectMBBI)) { 9235 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9236 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9237 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9238 .addReg(SelectMBBI->getOperand(4).getReg()) 9239 .addMBB(HeadMBB) 9240 .addReg(SelectMBBI->getOperand(5).getReg()) 9241 .addMBB(IfFalseMBB); 9242 SelectMBBI->eraseFromParent(); 9243 } 9244 SelectMBBI = Next; 9245 } 9246 9247 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9248 return TailMBB; 9249 } 9250 9251 MachineBasicBlock * 9252 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9253 MachineBasicBlock *BB) const { 9254 switch (MI.getOpcode()) { 9255 default: 9256 llvm_unreachable("Unexpected instr type to insert"); 9257 case RISCV::ReadCycleWide: 9258 assert(!Subtarget.is64Bit() && 9259 "ReadCycleWrite is only to be used on riscv32"); 9260 return emitReadCycleWidePseudo(MI, BB); 9261 case RISCV::Select_GPR_Using_CC_GPR: 9262 case RISCV::Select_FPR16_Using_CC_GPR: 9263 case RISCV::Select_FPR32_Using_CC_GPR: 9264 case RISCV::Select_FPR64_Using_CC_GPR: 9265 return emitSelectPseudo(MI, BB, Subtarget); 9266 case RISCV::BuildPairF64Pseudo: 9267 return emitBuildPairF64Pseudo(MI, BB); 9268 case RISCV::SplitF64Pseudo: 9269 return emitSplitF64Pseudo(MI, BB); 9270 case RISCV::PseudoQuietFLE_H: 9271 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9272 case RISCV::PseudoQuietFLT_H: 9273 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9274 case RISCV::PseudoQuietFLE_S: 9275 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9276 case RISCV::PseudoQuietFLT_S: 9277 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9278 case RISCV::PseudoQuietFLE_D: 9279 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9280 case RISCV::PseudoQuietFLT_D: 9281 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9282 } 9283 } 9284 9285 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9286 SDNode *Node) const { 9287 // Add FRM dependency to any instructions with dynamic rounding mode. 9288 unsigned Opc = MI.getOpcode(); 9289 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9290 if (Idx < 0) 9291 return; 9292 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9293 return; 9294 // If the instruction already reads FRM, don't add another read. 9295 if (MI.readsRegister(RISCV::FRM)) 9296 return; 9297 MI.addOperand( 9298 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9299 } 9300 9301 // Calling Convention Implementation. 9302 // The expectations for frontend ABI lowering vary from target to target. 9303 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9304 // details, but this is a longer term goal. For now, we simply try to keep the 9305 // role of the frontend as simple and well-defined as possible. The rules can 9306 // be summarised as: 9307 // * Never split up large scalar arguments. We handle them here. 9308 // * If a hardfloat calling convention is being used, and the struct may be 9309 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9310 // available, then pass as two separate arguments. If either the GPRs or FPRs 9311 // are exhausted, then pass according to the rule below. 9312 // * If a struct could never be passed in registers or directly in a stack 9313 // slot (as it is larger than 2*XLEN and the floating point rules don't 9314 // apply), then pass it using a pointer with the byval attribute. 9315 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9316 // word-sized array or a 2*XLEN scalar (depending on alignment). 9317 // * The frontend can determine whether a struct is returned by reference or 9318 // not based on its size and fields. If it will be returned by reference, the 9319 // frontend must modify the prototype so a pointer with the sret annotation is 9320 // passed as the first argument. This is not necessary for large scalar 9321 // returns. 9322 // * Struct return values and varargs should be coerced to structs containing 9323 // register-size fields in the same situations they would be for fixed 9324 // arguments. 9325 9326 static const MCPhysReg ArgGPRs[] = { 9327 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9328 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9329 }; 9330 static const MCPhysReg ArgFPR16s[] = { 9331 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9332 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9333 }; 9334 static const MCPhysReg ArgFPR32s[] = { 9335 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9336 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9337 }; 9338 static const MCPhysReg ArgFPR64s[] = { 9339 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9340 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9341 }; 9342 // This is an interim calling convention and it may be changed in the future. 9343 static const MCPhysReg ArgVRs[] = { 9344 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9345 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9346 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9347 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9348 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9349 RISCV::V20M2, RISCV::V22M2}; 9350 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9351 RISCV::V20M4}; 9352 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9353 9354 // Pass a 2*XLEN argument that has been split into two XLEN values through 9355 // registers or the stack as necessary. 9356 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9357 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9358 MVT ValVT2, MVT LocVT2, 9359 ISD::ArgFlagsTy ArgFlags2) { 9360 unsigned XLenInBytes = XLen / 8; 9361 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9362 // At least one half can be passed via register. 9363 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9364 VA1.getLocVT(), CCValAssign::Full)); 9365 } else { 9366 // Both halves must be passed on the stack, with proper alignment. 9367 Align StackAlign = 9368 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9369 State.addLoc( 9370 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9371 State.AllocateStack(XLenInBytes, StackAlign), 9372 VA1.getLocVT(), CCValAssign::Full)); 9373 State.addLoc(CCValAssign::getMem( 9374 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9375 LocVT2, CCValAssign::Full)); 9376 return false; 9377 } 9378 9379 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9380 // The second half can also be passed via register. 9381 State.addLoc( 9382 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9383 } else { 9384 // The second half is passed via the stack, without additional alignment. 9385 State.addLoc(CCValAssign::getMem( 9386 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9387 LocVT2, CCValAssign::Full)); 9388 } 9389 9390 return false; 9391 } 9392 9393 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9394 Optional<unsigned> FirstMaskArgument, 9395 CCState &State, const RISCVTargetLowering &TLI) { 9396 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9397 if (RC == &RISCV::VRRegClass) { 9398 // Assign the first mask argument to V0. 9399 // This is an interim calling convention and it may be changed in the 9400 // future. 9401 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9402 return State.AllocateReg(RISCV::V0); 9403 return State.AllocateReg(ArgVRs); 9404 } 9405 if (RC == &RISCV::VRM2RegClass) 9406 return State.AllocateReg(ArgVRM2s); 9407 if (RC == &RISCV::VRM4RegClass) 9408 return State.AllocateReg(ArgVRM4s); 9409 if (RC == &RISCV::VRM8RegClass) 9410 return State.AllocateReg(ArgVRM8s); 9411 llvm_unreachable("Unhandled register class for ValueType"); 9412 } 9413 9414 // Implements the RISC-V calling convention. Returns true upon failure. 9415 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9416 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9417 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9418 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9419 Optional<unsigned> FirstMaskArgument) { 9420 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9421 assert(XLen == 32 || XLen == 64); 9422 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9423 9424 // Any return value split in to more than two values can't be returned 9425 // directly. Vectors are returned via the available vector registers. 9426 if (!LocVT.isVector() && IsRet && ValNo > 1) 9427 return true; 9428 9429 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9430 // variadic argument, or if no F16/F32 argument registers are available. 9431 bool UseGPRForF16_F32 = true; 9432 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9433 // variadic argument, or if no F64 argument registers are available. 9434 bool UseGPRForF64 = true; 9435 9436 switch (ABI) { 9437 default: 9438 llvm_unreachable("Unexpected ABI"); 9439 case RISCVABI::ABI_ILP32: 9440 case RISCVABI::ABI_LP64: 9441 break; 9442 case RISCVABI::ABI_ILP32F: 9443 case RISCVABI::ABI_LP64F: 9444 UseGPRForF16_F32 = !IsFixed; 9445 break; 9446 case RISCVABI::ABI_ILP32D: 9447 case RISCVABI::ABI_LP64D: 9448 UseGPRForF16_F32 = !IsFixed; 9449 UseGPRForF64 = !IsFixed; 9450 break; 9451 } 9452 9453 // FPR16, FPR32, and FPR64 alias each other. 9454 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9455 UseGPRForF16_F32 = true; 9456 UseGPRForF64 = true; 9457 } 9458 9459 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9460 // similar local variables rather than directly checking against the target 9461 // ABI. 9462 9463 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9464 LocVT = XLenVT; 9465 LocInfo = CCValAssign::BCvt; 9466 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9467 LocVT = MVT::i64; 9468 LocInfo = CCValAssign::BCvt; 9469 } 9470 9471 // If this is a variadic argument, the RISC-V calling convention requires 9472 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9473 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9474 // be used regardless of whether the original argument was split during 9475 // legalisation or not. The argument will not be passed by registers if the 9476 // original type is larger than 2*XLEN, so the register alignment rule does 9477 // not apply. 9478 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9479 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9480 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9481 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9482 // Skip 'odd' register if necessary. 9483 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9484 State.AllocateReg(ArgGPRs); 9485 } 9486 9487 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9488 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9489 State.getPendingArgFlags(); 9490 9491 assert(PendingLocs.size() == PendingArgFlags.size() && 9492 "PendingLocs and PendingArgFlags out of sync"); 9493 9494 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9495 // registers are exhausted. 9496 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9497 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9498 "Can't lower f64 if it is split"); 9499 // Depending on available argument GPRS, f64 may be passed in a pair of 9500 // GPRs, split between a GPR and the stack, or passed completely on the 9501 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9502 // cases. 9503 Register Reg = State.AllocateReg(ArgGPRs); 9504 LocVT = MVT::i32; 9505 if (!Reg) { 9506 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9507 State.addLoc( 9508 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9509 return false; 9510 } 9511 if (!State.AllocateReg(ArgGPRs)) 9512 State.AllocateStack(4, Align(4)); 9513 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9514 return false; 9515 } 9516 9517 // Fixed-length vectors are located in the corresponding scalable-vector 9518 // container types. 9519 if (ValVT.isFixedLengthVector()) 9520 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9521 9522 // Split arguments might be passed indirectly, so keep track of the pending 9523 // values. Split vectors are passed via a mix of registers and indirectly, so 9524 // treat them as we would any other argument. 9525 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9526 LocVT = XLenVT; 9527 LocInfo = CCValAssign::Indirect; 9528 PendingLocs.push_back( 9529 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9530 PendingArgFlags.push_back(ArgFlags); 9531 if (!ArgFlags.isSplitEnd()) { 9532 return false; 9533 } 9534 } 9535 9536 // If the split argument only had two elements, it should be passed directly 9537 // in registers or on the stack. 9538 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9539 PendingLocs.size() <= 2) { 9540 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9541 // Apply the normal calling convention rules to the first half of the 9542 // split argument. 9543 CCValAssign VA = PendingLocs[0]; 9544 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9545 PendingLocs.clear(); 9546 PendingArgFlags.clear(); 9547 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9548 ArgFlags); 9549 } 9550 9551 // Allocate to a register if possible, or else a stack slot. 9552 Register Reg; 9553 unsigned StoreSizeBytes = XLen / 8; 9554 Align StackAlign = Align(XLen / 8); 9555 9556 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9557 Reg = State.AllocateReg(ArgFPR16s); 9558 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9559 Reg = State.AllocateReg(ArgFPR32s); 9560 else if (ValVT == MVT::f64 && !UseGPRForF64) 9561 Reg = State.AllocateReg(ArgFPR64s); 9562 else if (ValVT.isVector()) { 9563 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9564 if (!Reg) { 9565 // For return values, the vector must be passed fully via registers or 9566 // via the stack. 9567 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9568 // but we're using all of them. 9569 if (IsRet) 9570 return true; 9571 // Try using a GPR to pass the address 9572 if ((Reg = State.AllocateReg(ArgGPRs))) { 9573 LocVT = XLenVT; 9574 LocInfo = CCValAssign::Indirect; 9575 } else if (ValVT.isScalableVector()) { 9576 LocVT = XLenVT; 9577 LocInfo = CCValAssign::Indirect; 9578 } else { 9579 // Pass fixed-length vectors on the stack. 9580 LocVT = ValVT; 9581 StoreSizeBytes = ValVT.getStoreSize(); 9582 // Align vectors to their element sizes, being careful for vXi1 9583 // vectors. 9584 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9585 } 9586 } 9587 } else { 9588 Reg = State.AllocateReg(ArgGPRs); 9589 } 9590 9591 unsigned StackOffset = 9592 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9593 9594 // If we reach this point and PendingLocs is non-empty, we must be at the 9595 // end of a split argument that must be passed indirectly. 9596 if (!PendingLocs.empty()) { 9597 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9598 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9599 9600 for (auto &It : PendingLocs) { 9601 if (Reg) 9602 It.convertToReg(Reg); 9603 else 9604 It.convertToMem(StackOffset); 9605 State.addLoc(It); 9606 } 9607 PendingLocs.clear(); 9608 PendingArgFlags.clear(); 9609 return false; 9610 } 9611 9612 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9613 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9614 "Expected an XLenVT or vector types at this stage"); 9615 9616 if (Reg) { 9617 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9618 return false; 9619 } 9620 9621 // When a floating-point value is passed on the stack, no bit-conversion is 9622 // needed. 9623 if (ValVT.isFloatingPoint()) { 9624 LocVT = ValVT; 9625 LocInfo = CCValAssign::Full; 9626 } 9627 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9628 return false; 9629 } 9630 9631 template <typename ArgTy> 9632 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9633 for (const auto &ArgIdx : enumerate(Args)) { 9634 MVT ArgVT = ArgIdx.value().VT; 9635 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9636 return ArgIdx.index(); 9637 } 9638 return None; 9639 } 9640 9641 void RISCVTargetLowering::analyzeInputArgs( 9642 MachineFunction &MF, CCState &CCInfo, 9643 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9644 RISCVCCAssignFn Fn) const { 9645 unsigned NumArgs = Ins.size(); 9646 FunctionType *FType = MF.getFunction().getFunctionType(); 9647 9648 Optional<unsigned> FirstMaskArgument; 9649 if (Subtarget.hasVInstructions()) 9650 FirstMaskArgument = preAssignMask(Ins); 9651 9652 for (unsigned i = 0; i != NumArgs; ++i) { 9653 MVT ArgVT = Ins[i].VT; 9654 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9655 9656 Type *ArgTy = nullptr; 9657 if (IsRet) 9658 ArgTy = FType->getReturnType(); 9659 else if (Ins[i].isOrigArg()) 9660 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9661 9662 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9663 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9664 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9665 FirstMaskArgument)) { 9666 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9667 << EVT(ArgVT).getEVTString() << '\n'); 9668 llvm_unreachable(nullptr); 9669 } 9670 } 9671 } 9672 9673 void RISCVTargetLowering::analyzeOutputArgs( 9674 MachineFunction &MF, CCState &CCInfo, 9675 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9676 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9677 unsigned NumArgs = Outs.size(); 9678 9679 Optional<unsigned> FirstMaskArgument; 9680 if (Subtarget.hasVInstructions()) 9681 FirstMaskArgument = preAssignMask(Outs); 9682 9683 for (unsigned i = 0; i != NumArgs; i++) { 9684 MVT ArgVT = Outs[i].VT; 9685 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9686 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9687 9688 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9689 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9690 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9691 FirstMaskArgument)) { 9692 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9693 << EVT(ArgVT).getEVTString() << "\n"); 9694 llvm_unreachable(nullptr); 9695 } 9696 } 9697 } 9698 9699 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9700 // values. 9701 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9702 const CCValAssign &VA, const SDLoc &DL, 9703 const RISCVSubtarget &Subtarget) { 9704 switch (VA.getLocInfo()) { 9705 default: 9706 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9707 case CCValAssign::Full: 9708 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9709 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9710 break; 9711 case CCValAssign::BCvt: 9712 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9713 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9714 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9715 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9716 else 9717 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9718 break; 9719 } 9720 return Val; 9721 } 9722 9723 // The caller is responsible for loading the full value if the argument is 9724 // passed with CCValAssign::Indirect. 9725 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9726 const CCValAssign &VA, const SDLoc &DL, 9727 const RISCVTargetLowering &TLI) { 9728 MachineFunction &MF = DAG.getMachineFunction(); 9729 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9730 EVT LocVT = VA.getLocVT(); 9731 SDValue Val; 9732 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9733 Register VReg = RegInfo.createVirtualRegister(RC); 9734 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9735 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9736 9737 if (VA.getLocInfo() == CCValAssign::Indirect) 9738 return Val; 9739 9740 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9741 } 9742 9743 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9744 const CCValAssign &VA, const SDLoc &DL, 9745 const RISCVSubtarget &Subtarget) { 9746 EVT LocVT = VA.getLocVT(); 9747 9748 switch (VA.getLocInfo()) { 9749 default: 9750 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9751 case CCValAssign::Full: 9752 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9753 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9754 break; 9755 case CCValAssign::BCvt: 9756 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9757 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9758 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9759 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9760 else 9761 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9762 break; 9763 } 9764 return Val; 9765 } 9766 9767 // The caller is responsible for loading the full value if the argument is 9768 // passed with CCValAssign::Indirect. 9769 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9770 const CCValAssign &VA, const SDLoc &DL) { 9771 MachineFunction &MF = DAG.getMachineFunction(); 9772 MachineFrameInfo &MFI = MF.getFrameInfo(); 9773 EVT LocVT = VA.getLocVT(); 9774 EVT ValVT = VA.getValVT(); 9775 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9776 if (ValVT.isScalableVector()) { 9777 // When the value is a scalable vector, we save the pointer which points to 9778 // the scalable vector value in the stack. The ValVT will be the pointer 9779 // type, instead of the scalable vector type. 9780 ValVT = LocVT; 9781 } 9782 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9783 /*IsImmutable=*/true); 9784 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9785 SDValue Val; 9786 9787 ISD::LoadExtType ExtType; 9788 switch (VA.getLocInfo()) { 9789 default: 9790 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9791 case CCValAssign::Full: 9792 case CCValAssign::Indirect: 9793 case CCValAssign::BCvt: 9794 ExtType = ISD::NON_EXTLOAD; 9795 break; 9796 } 9797 Val = DAG.getExtLoad( 9798 ExtType, DL, LocVT, Chain, FIN, 9799 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9800 return Val; 9801 } 9802 9803 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9804 const CCValAssign &VA, const SDLoc &DL) { 9805 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9806 "Unexpected VA"); 9807 MachineFunction &MF = DAG.getMachineFunction(); 9808 MachineFrameInfo &MFI = MF.getFrameInfo(); 9809 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9810 9811 if (VA.isMemLoc()) { 9812 // f64 is passed on the stack. 9813 int FI = 9814 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9815 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9816 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9817 MachinePointerInfo::getFixedStack(MF, FI)); 9818 } 9819 9820 assert(VA.isRegLoc() && "Expected register VA assignment"); 9821 9822 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9823 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9824 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9825 SDValue Hi; 9826 if (VA.getLocReg() == RISCV::X17) { 9827 // Second half of f64 is passed on the stack. 9828 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9829 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9830 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9831 MachinePointerInfo::getFixedStack(MF, FI)); 9832 } else { 9833 // Second half of f64 is passed in another GPR. 9834 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9835 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9836 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9837 } 9838 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9839 } 9840 9841 // FastCC has less than 1% performance improvement for some particular 9842 // benchmark. But theoretically, it may has benenfit for some cases. 9843 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9844 unsigned ValNo, MVT ValVT, MVT LocVT, 9845 CCValAssign::LocInfo LocInfo, 9846 ISD::ArgFlagsTy ArgFlags, CCState &State, 9847 bool IsFixed, bool IsRet, Type *OrigTy, 9848 const RISCVTargetLowering &TLI, 9849 Optional<unsigned> FirstMaskArgument) { 9850 9851 // X5 and X6 might be used for save-restore libcall. 9852 static const MCPhysReg GPRList[] = { 9853 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9854 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9855 RISCV::X29, RISCV::X30, RISCV::X31}; 9856 9857 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9858 if (unsigned Reg = State.AllocateReg(GPRList)) { 9859 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9860 return false; 9861 } 9862 } 9863 9864 if (LocVT == MVT::f16) { 9865 static const MCPhysReg FPR16List[] = { 9866 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9867 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9868 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9869 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9870 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9871 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9872 return false; 9873 } 9874 } 9875 9876 if (LocVT == MVT::f32) { 9877 static const MCPhysReg FPR32List[] = { 9878 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9879 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9880 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9881 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9882 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9883 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9884 return false; 9885 } 9886 } 9887 9888 if (LocVT == MVT::f64) { 9889 static const MCPhysReg FPR64List[] = { 9890 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9891 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9892 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9893 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9894 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9895 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9896 return false; 9897 } 9898 } 9899 9900 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9901 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9902 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9903 return false; 9904 } 9905 9906 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9907 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9908 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9909 return false; 9910 } 9911 9912 if (LocVT.isVector()) { 9913 if (unsigned Reg = 9914 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9915 // Fixed-length vectors are located in the corresponding scalable-vector 9916 // container types. 9917 if (ValVT.isFixedLengthVector()) 9918 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9919 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9920 } else { 9921 // Try and pass the address via a "fast" GPR. 9922 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9923 LocInfo = CCValAssign::Indirect; 9924 LocVT = TLI.getSubtarget().getXLenVT(); 9925 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9926 } else if (ValVT.isFixedLengthVector()) { 9927 auto StackAlign = 9928 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9929 unsigned StackOffset = 9930 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9931 State.addLoc( 9932 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9933 } else { 9934 // Can't pass scalable vectors on the stack. 9935 return true; 9936 } 9937 } 9938 9939 return false; 9940 } 9941 9942 return true; // CC didn't match. 9943 } 9944 9945 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9946 CCValAssign::LocInfo LocInfo, 9947 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9948 9949 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9950 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9951 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9952 static const MCPhysReg GPRList[] = { 9953 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9954 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9955 if (unsigned Reg = State.AllocateReg(GPRList)) { 9956 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9957 return false; 9958 } 9959 } 9960 9961 if (LocVT == MVT::f32) { 9962 // Pass in STG registers: F1, ..., F6 9963 // fs0 ... fs5 9964 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9965 RISCV::F18_F, RISCV::F19_F, 9966 RISCV::F20_F, RISCV::F21_F}; 9967 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9968 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9969 return false; 9970 } 9971 } 9972 9973 if (LocVT == MVT::f64) { 9974 // Pass in STG registers: D1, ..., D6 9975 // fs6 ... fs11 9976 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9977 RISCV::F24_D, RISCV::F25_D, 9978 RISCV::F26_D, RISCV::F27_D}; 9979 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9980 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9981 return false; 9982 } 9983 } 9984 9985 report_fatal_error("No registers left in GHC calling convention"); 9986 return true; 9987 } 9988 9989 // Transform physical registers into virtual registers. 9990 SDValue RISCVTargetLowering::LowerFormalArguments( 9991 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9992 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9993 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9994 9995 MachineFunction &MF = DAG.getMachineFunction(); 9996 9997 switch (CallConv) { 9998 default: 9999 report_fatal_error("Unsupported calling convention"); 10000 case CallingConv::C: 10001 case CallingConv::Fast: 10002 break; 10003 case CallingConv::GHC: 10004 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10005 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10006 report_fatal_error( 10007 "GHC calling convention requires the F and D instruction set extensions"); 10008 } 10009 10010 const Function &Func = MF.getFunction(); 10011 if (Func.hasFnAttribute("interrupt")) { 10012 if (!Func.arg_empty()) 10013 report_fatal_error( 10014 "Functions with the interrupt attribute cannot have arguments!"); 10015 10016 StringRef Kind = 10017 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10018 10019 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10020 report_fatal_error( 10021 "Function interrupt attribute argument not supported!"); 10022 } 10023 10024 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10025 MVT XLenVT = Subtarget.getXLenVT(); 10026 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10027 // Used with vargs to acumulate store chains. 10028 std::vector<SDValue> OutChains; 10029 10030 // Assign locations to all of the incoming arguments. 10031 SmallVector<CCValAssign, 16> ArgLocs; 10032 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10033 10034 if (CallConv == CallingConv::GHC) 10035 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10036 else 10037 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10038 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10039 : CC_RISCV); 10040 10041 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10042 CCValAssign &VA = ArgLocs[i]; 10043 SDValue ArgValue; 10044 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10045 // case. 10046 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10047 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10048 else if (VA.isRegLoc()) 10049 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10050 else 10051 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10052 10053 if (VA.getLocInfo() == CCValAssign::Indirect) { 10054 // If the original argument was split and passed by reference (e.g. i128 10055 // on RV32), we need to load all parts of it here (using the same 10056 // address). Vectors may be partly split to registers and partly to the 10057 // stack, in which case the base address is partly offset and subsequent 10058 // stores are relative to that. 10059 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10060 MachinePointerInfo())); 10061 unsigned ArgIndex = Ins[i].OrigArgIndex; 10062 unsigned ArgPartOffset = Ins[i].PartOffset; 10063 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10064 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10065 CCValAssign &PartVA = ArgLocs[i + 1]; 10066 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10067 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10068 if (PartVA.getValVT().isScalableVector()) 10069 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10070 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10071 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10072 MachinePointerInfo())); 10073 ++i; 10074 } 10075 continue; 10076 } 10077 InVals.push_back(ArgValue); 10078 } 10079 10080 if (IsVarArg) { 10081 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10082 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10083 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10084 MachineFrameInfo &MFI = MF.getFrameInfo(); 10085 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10086 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10087 10088 // Offset of the first variable argument from stack pointer, and size of 10089 // the vararg save area. For now, the varargs save area is either zero or 10090 // large enough to hold a0-a7. 10091 int VaArgOffset, VarArgsSaveSize; 10092 10093 // If all registers are allocated, then all varargs must be passed on the 10094 // stack and we don't need to save any argregs. 10095 if (ArgRegs.size() == Idx) { 10096 VaArgOffset = CCInfo.getNextStackOffset(); 10097 VarArgsSaveSize = 0; 10098 } else { 10099 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10100 VaArgOffset = -VarArgsSaveSize; 10101 } 10102 10103 // Record the frame index of the first variable argument 10104 // which is a value necessary to VASTART. 10105 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10106 RVFI->setVarArgsFrameIndex(FI); 10107 10108 // If saving an odd number of registers then create an extra stack slot to 10109 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10110 // offsets to even-numbered registered remain 2*XLEN-aligned. 10111 if (Idx % 2) { 10112 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10113 VarArgsSaveSize += XLenInBytes; 10114 } 10115 10116 // Copy the integer registers that may have been used for passing varargs 10117 // to the vararg save area. 10118 for (unsigned I = Idx; I < ArgRegs.size(); 10119 ++I, VaArgOffset += XLenInBytes) { 10120 const Register Reg = RegInfo.createVirtualRegister(RC); 10121 RegInfo.addLiveIn(ArgRegs[I], Reg); 10122 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10123 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10124 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10125 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10126 MachinePointerInfo::getFixedStack(MF, FI)); 10127 cast<StoreSDNode>(Store.getNode()) 10128 ->getMemOperand() 10129 ->setValue((Value *)nullptr); 10130 OutChains.push_back(Store); 10131 } 10132 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10133 } 10134 10135 // All stores are grouped in one node to allow the matching between 10136 // the size of Ins and InVals. This only happens for vararg functions. 10137 if (!OutChains.empty()) { 10138 OutChains.push_back(Chain); 10139 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10140 } 10141 10142 return Chain; 10143 } 10144 10145 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10146 /// for tail call optimization. 10147 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10148 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10149 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10150 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10151 10152 auto &Callee = CLI.Callee; 10153 auto CalleeCC = CLI.CallConv; 10154 auto &Outs = CLI.Outs; 10155 auto &Caller = MF.getFunction(); 10156 auto CallerCC = Caller.getCallingConv(); 10157 10158 // Exception-handling functions need a special set of instructions to 10159 // indicate a return to the hardware. Tail-calling another function would 10160 // probably break this. 10161 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10162 // should be expanded as new function attributes are introduced. 10163 if (Caller.hasFnAttribute("interrupt")) 10164 return false; 10165 10166 // Do not tail call opt if the stack is used to pass parameters. 10167 if (CCInfo.getNextStackOffset() != 0) 10168 return false; 10169 10170 // Do not tail call opt if any parameters need to be passed indirectly. 10171 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10172 // passed indirectly. So the address of the value will be passed in a 10173 // register, or if not available, then the address is put on the stack. In 10174 // order to pass indirectly, space on the stack often needs to be allocated 10175 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10176 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10177 // are passed CCValAssign::Indirect. 10178 for (auto &VA : ArgLocs) 10179 if (VA.getLocInfo() == CCValAssign::Indirect) 10180 return false; 10181 10182 // Do not tail call opt if either caller or callee uses struct return 10183 // semantics. 10184 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10185 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10186 if (IsCallerStructRet || IsCalleeStructRet) 10187 return false; 10188 10189 // Externally-defined functions with weak linkage should not be 10190 // tail-called. The behaviour of branch instructions in this situation (as 10191 // used for tail calls) is implementation-defined, so we cannot rely on the 10192 // linker replacing the tail call with a return. 10193 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10194 const GlobalValue *GV = G->getGlobal(); 10195 if (GV->hasExternalWeakLinkage()) 10196 return false; 10197 } 10198 10199 // The callee has to preserve all registers the caller needs to preserve. 10200 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10201 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10202 if (CalleeCC != CallerCC) { 10203 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10204 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10205 return false; 10206 } 10207 10208 // Byval parameters hand the function a pointer directly into the stack area 10209 // we want to reuse during a tail call. Working around this *is* possible 10210 // but less efficient and uglier in LowerCall. 10211 for (auto &Arg : Outs) 10212 if (Arg.Flags.isByVal()) 10213 return false; 10214 10215 return true; 10216 } 10217 10218 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10219 return DAG.getDataLayout().getPrefTypeAlign( 10220 VT.getTypeForEVT(*DAG.getContext())); 10221 } 10222 10223 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10224 // and output parameter nodes. 10225 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10226 SmallVectorImpl<SDValue> &InVals) const { 10227 SelectionDAG &DAG = CLI.DAG; 10228 SDLoc &DL = CLI.DL; 10229 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10230 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10231 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10232 SDValue Chain = CLI.Chain; 10233 SDValue Callee = CLI.Callee; 10234 bool &IsTailCall = CLI.IsTailCall; 10235 CallingConv::ID CallConv = CLI.CallConv; 10236 bool IsVarArg = CLI.IsVarArg; 10237 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10238 MVT XLenVT = Subtarget.getXLenVT(); 10239 10240 MachineFunction &MF = DAG.getMachineFunction(); 10241 10242 // Analyze the operands of the call, assigning locations to each operand. 10243 SmallVector<CCValAssign, 16> ArgLocs; 10244 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10245 10246 if (CallConv == CallingConv::GHC) 10247 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10248 else 10249 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10250 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10251 : CC_RISCV); 10252 10253 // Check if it's really possible to do a tail call. 10254 if (IsTailCall) 10255 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10256 10257 if (IsTailCall) 10258 ++NumTailCalls; 10259 else if (CLI.CB && CLI.CB->isMustTailCall()) 10260 report_fatal_error("failed to perform tail call elimination on a call " 10261 "site marked musttail"); 10262 10263 // Get a count of how many bytes are to be pushed on the stack. 10264 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10265 10266 // Create local copies for byval args 10267 SmallVector<SDValue, 8> ByValArgs; 10268 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10269 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10270 if (!Flags.isByVal()) 10271 continue; 10272 10273 SDValue Arg = OutVals[i]; 10274 unsigned Size = Flags.getByValSize(); 10275 Align Alignment = Flags.getNonZeroByValAlign(); 10276 10277 int FI = 10278 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10279 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10280 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10281 10282 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10283 /*IsVolatile=*/false, 10284 /*AlwaysInline=*/false, IsTailCall, 10285 MachinePointerInfo(), MachinePointerInfo()); 10286 ByValArgs.push_back(FIPtr); 10287 } 10288 10289 if (!IsTailCall) 10290 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10291 10292 // Copy argument values to their designated locations. 10293 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10294 SmallVector<SDValue, 8> MemOpChains; 10295 SDValue StackPtr; 10296 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10297 CCValAssign &VA = ArgLocs[i]; 10298 SDValue ArgValue = OutVals[i]; 10299 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10300 10301 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10302 bool IsF64OnRV32DSoftABI = 10303 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10304 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10305 SDValue SplitF64 = DAG.getNode( 10306 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10307 SDValue Lo = SplitF64.getValue(0); 10308 SDValue Hi = SplitF64.getValue(1); 10309 10310 Register RegLo = VA.getLocReg(); 10311 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10312 10313 if (RegLo == RISCV::X17) { 10314 // Second half of f64 is passed on the stack. 10315 // Work out the address of the stack slot. 10316 if (!StackPtr.getNode()) 10317 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10318 // Emit the store. 10319 MemOpChains.push_back( 10320 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10321 } else { 10322 // Second half of f64 is passed in another GPR. 10323 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10324 Register RegHigh = RegLo + 1; 10325 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10326 } 10327 continue; 10328 } 10329 10330 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10331 // as any other MemLoc. 10332 10333 // Promote the value if needed. 10334 // For now, only handle fully promoted and indirect arguments. 10335 if (VA.getLocInfo() == CCValAssign::Indirect) { 10336 // Store the argument in a stack slot and pass its address. 10337 Align StackAlign = 10338 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10339 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10340 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10341 // If the original argument was split (e.g. i128), we need 10342 // to store the required parts of it here (and pass just one address). 10343 // Vectors may be partly split to registers and partly to the stack, in 10344 // which case the base address is partly offset and subsequent stores are 10345 // relative to that. 10346 unsigned ArgIndex = Outs[i].OrigArgIndex; 10347 unsigned ArgPartOffset = Outs[i].PartOffset; 10348 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10349 // Calculate the total size to store. We don't have access to what we're 10350 // actually storing other than performing the loop and collecting the 10351 // info. 10352 SmallVector<std::pair<SDValue, SDValue>> Parts; 10353 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10354 SDValue PartValue = OutVals[i + 1]; 10355 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10356 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10357 EVT PartVT = PartValue.getValueType(); 10358 if (PartVT.isScalableVector()) 10359 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10360 StoredSize += PartVT.getStoreSize(); 10361 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10362 Parts.push_back(std::make_pair(PartValue, Offset)); 10363 ++i; 10364 } 10365 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10366 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10367 MemOpChains.push_back( 10368 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10369 MachinePointerInfo::getFixedStack(MF, FI))); 10370 for (const auto &Part : Parts) { 10371 SDValue PartValue = Part.first; 10372 SDValue PartOffset = Part.second; 10373 SDValue Address = 10374 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10375 MemOpChains.push_back( 10376 DAG.getStore(Chain, DL, PartValue, Address, 10377 MachinePointerInfo::getFixedStack(MF, FI))); 10378 } 10379 ArgValue = SpillSlot; 10380 } else { 10381 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10382 } 10383 10384 // Use local copy if it is a byval arg. 10385 if (Flags.isByVal()) 10386 ArgValue = ByValArgs[j++]; 10387 10388 if (VA.isRegLoc()) { 10389 // Queue up the argument copies and emit them at the end. 10390 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10391 } else { 10392 assert(VA.isMemLoc() && "Argument not register or memory"); 10393 assert(!IsTailCall && "Tail call not allowed if stack is used " 10394 "for passing parameters"); 10395 10396 // Work out the address of the stack slot. 10397 if (!StackPtr.getNode()) 10398 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10399 SDValue Address = 10400 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10401 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10402 10403 // Emit the store. 10404 MemOpChains.push_back( 10405 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10406 } 10407 } 10408 10409 // Join the stores, which are independent of one another. 10410 if (!MemOpChains.empty()) 10411 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10412 10413 SDValue Glue; 10414 10415 // Build a sequence of copy-to-reg nodes, chained and glued together. 10416 for (auto &Reg : RegsToPass) { 10417 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10418 Glue = Chain.getValue(1); 10419 } 10420 10421 // Validate that none of the argument registers have been marked as 10422 // reserved, if so report an error. Do the same for the return address if this 10423 // is not a tailcall. 10424 validateCCReservedRegs(RegsToPass, MF); 10425 if (!IsTailCall && 10426 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10427 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10428 MF.getFunction(), 10429 "Return address register required, but has been reserved."}); 10430 10431 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10432 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10433 // split it and then direct call can be matched by PseudoCALL. 10434 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10435 const GlobalValue *GV = S->getGlobal(); 10436 10437 unsigned OpFlags = RISCVII::MO_CALL; 10438 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10439 OpFlags = RISCVII::MO_PLT; 10440 10441 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10442 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10443 unsigned OpFlags = RISCVII::MO_CALL; 10444 10445 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10446 nullptr)) 10447 OpFlags = RISCVII::MO_PLT; 10448 10449 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10450 } 10451 10452 // The first call operand is the chain and the second is the target address. 10453 SmallVector<SDValue, 8> Ops; 10454 Ops.push_back(Chain); 10455 Ops.push_back(Callee); 10456 10457 // Add argument registers to the end of the list so that they are 10458 // known live into the call. 10459 for (auto &Reg : RegsToPass) 10460 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10461 10462 if (!IsTailCall) { 10463 // Add a register mask operand representing the call-preserved registers. 10464 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10465 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10466 assert(Mask && "Missing call preserved mask for calling convention"); 10467 Ops.push_back(DAG.getRegisterMask(Mask)); 10468 } 10469 10470 // Glue the call to the argument copies, if any. 10471 if (Glue.getNode()) 10472 Ops.push_back(Glue); 10473 10474 // Emit the call. 10475 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10476 10477 if (IsTailCall) { 10478 MF.getFrameInfo().setHasTailCall(); 10479 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10480 } 10481 10482 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10483 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10484 Glue = Chain.getValue(1); 10485 10486 // Mark the end of the call, which is glued to the call itself. 10487 Chain = DAG.getCALLSEQ_END(Chain, 10488 DAG.getConstant(NumBytes, DL, PtrVT, true), 10489 DAG.getConstant(0, DL, PtrVT, true), 10490 Glue, DL); 10491 Glue = Chain.getValue(1); 10492 10493 // Assign locations to each value returned by this call. 10494 SmallVector<CCValAssign, 16> RVLocs; 10495 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10496 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10497 10498 // Copy all of the result registers out of their specified physreg. 10499 for (auto &VA : RVLocs) { 10500 // Copy the value out 10501 SDValue RetValue = 10502 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10503 // Glue the RetValue to the end of the call sequence 10504 Chain = RetValue.getValue(1); 10505 Glue = RetValue.getValue(2); 10506 10507 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10508 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10509 SDValue RetValue2 = 10510 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10511 Chain = RetValue2.getValue(1); 10512 Glue = RetValue2.getValue(2); 10513 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10514 RetValue2); 10515 } 10516 10517 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10518 10519 InVals.push_back(RetValue); 10520 } 10521 10522 return Chain; 10523 } 10524 10525 bool RISCVTargetLowering::CanLowerReturn( 10526 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10527 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10528 SmallVector<CCValAssign, 16> RVLocs; 10529 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10530 10531 Optional<unsigned> FirstMaskArgument; 10532 if (Subtarget.hasVInstructions()) 10533 FirstMaskArgument = preAssignMask(Outs); 10534 10535 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10536 MVT VT = Outs[i].VT; 10537 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10538 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10539 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10540 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10541 *this, FirstMaskArgument)) 10542 return false; 10543 } 10544 return true; 10545 } 10546 10547 SDValue 10548 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10549 bool IsVarArg, 10550 const SmallVectorImpl<ISD::OutputArg> &Outs, 10551 const SmallVectorImpl<SDValue> &OutVals, 10552 const SDLoc &DL, SelectionDAG &DAG) const { 10553 const MachineFunction &MF = DAG.getMachineFunction(); 10554 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10555 10556 // Stores the assignment of the return value to a location. 10557 SmallVector<CCValAssign, 16> RVLocs; 10558 10559 // Info about the registers and stack slot. 10560 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10561 *DAG.getContext()); 10562 10563 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10564 nullptr, CC_RISCV); 10565 10566 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10567 report_fatal_error("GHC functions return void only"); 10568 10569 SDValue Glue; 10570 SmallVector<SDValue, 4> RetOps(1, Chain); 10571 10572 // Copy the result values into the output registers. 10573 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10574 SDValue Val = OutVals[i]; 10575 CCValAssign &VA = RVLocs[i]; 10576 assert(VA.isRegLoc() && "Can only return in registers!"); 10577 10578 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10579 // Handle returning f64 on RV32D with a soft float ABI. 10580 assert(VA.isRegLoc() && "Expected return via registers"); 10581 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10582 DAG.getVTList(MVT::i32, MVT::i32), Val); 10583 SDValue Lo = SplitF64.getValue(0); 10584 SDValue Hi = SplitF64.getValue(1); 10585 Register RegLo = VA.getLocReg(); 10586 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10587 Register RegHi = RegLo + 1; 10588 10589 if (STI.isRegisterReservedByUser(RegLo) || 10590 STI.isRegisterReservedByUser(RegHi)) 10591 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10592 MF.getFunction(), 10593 "Return value register required, but has been reserved."}); 10594 10595 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10596 Glue = Chain.getValue(1); 10597 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10598 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10599 Glue = Chain.getValue(1); 10600 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10601 } else { 10602 // Handle a 'normal' return. 10603 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10604 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10605 10606 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10607 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10608 MF.getFunction(), 10609 "Return value register required, but has been reserved."}); 10610 10611 // Guarantee that all emitted copies are stuck together. 10612 Glue = Chain.getValue(1); 10613 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10614 } 10615 } 10616 10617 RetOps[0] = Chain; // Update chain. 10618 10619 // Add the glue node if we have it. 10620 if (Glue.getNode()) { 10621 RetOps.push_back(Glue); 10622 } 10623 10624 unsigned RetOpc = RISCVISD::RET_FLAG; 10625 // Interrupt service routines use different return instructions. 10626 const Function &Func = DAG.getMachineFunction().getFunction(); 10627 if (Func.hasFnAttribute("interrupt")) { 10628 if (!Func.getReturnType()->isVoidTy()) 10629 report_fatal_error( 10630 "Functions with the interrupt attribute must have void return type!"); 10631 10632 MachineFunction &MF = DAG.getMachineFunction(); 10633 StringRef Kind = 10634 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10635 10636 if (Kind == "user") 10637 RetOpc = RISCVISD::URET_FLAG; 10638 else if (Kind == "supervisor") 10639 RetOpc = RISCVISD::SRET_FLAG; 10640 else 10641 RetOpc = RISCVISD::MRET_FLAG; 10642 } 10643 10644 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10645 } 10646 10647 void RISCVTargetLowering::validateCCReservedRegs( 10648 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10649 MachineFunction &MF) const { 10650 const Function &F = MF.getFunction(); 10651 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10652 10653 if (llvm::any_of(Regs, [&STI](auto Reg) { 10654 return STI.isRegisterReservedByUser(Reg.first); 10655 })) 10656 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10657 F, "Argument register required, but has been reserved."}); 10658 } 10659 10660 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10661 return CI->isTailCall(); 10662 } 10663 10664 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10665 #define NODE_NAME_CASE(NODE) \ 10666 case RISCVISD::NODE: \ 10667 return "RISCVISD::" #NODE; 10668 // clang-format off 10669 switch ((RISCVISD::NodeType)Opcode) { 10670 case RISCVISD::FIRST_NUMBER: 10671 break; 10672 NODE_NAME_CASE(RET_FLAG) 10673 NODE_NAME_CASE(URET_FLAG) 10674 NODE_NAME_CASE(SRET_FLAG) 10675 NODE_NAME_CASE(MRET_FLAG) 10676 NODE_NAME_CASE(CALL) 10677 NODE_NAME_CASE(SELECT_CC) 10678 NODE_NAME_CASE(BR_CC) 10679 NODE_NAME_CASE(BuildPairF64) 10680 NODE_NAME_CASE(SplitF64) 10681 NODE_NAME_CASE(TAIL) 10682 NODE_NAME_CASE(MULHSU) 10683 NODE_NAME_CASE(SLLW) 10684 NODE_NAME_CASE(SRAW) 10685 NODE_NAME_CASE(SRLW) 10686 NODE_NAME_CASE(DIVW) 10687 NODE_NAME_CASE(DIVUW) 10688 NODE_NAME_CASE(REMUW) 10689 NODE_NAME_CASE(ROLW) 10690 NODE_NAME_CASE(RORW) 10691 NODE_NAME_CASE(CLZW) 10692 NODE_NAME_CASE(CTZW) 10693 NODE_NAME_CASE(FSLW) 10694 NODE_NAME_CASE(FSRW) 10695 NODE_NAME_CASE(FSL) 10696 NODE_NAME_CASE(FSR) 10697 NODE_NAME_CASE(FMV_H_X) 10698 NODE_NAME_CASE(FMV_X_ANYEXTH) 10699 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10700 NODE_NAME_CASE(FMV_W_X_RV64) 10701 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10702 NODE_NAME_CASE(FCVT_X) 10703 NODE_NAME_CASE(FCVT_XU) 10704 NODE_NAME_CASE(FCVT_W_RV64) 10705 NODE_NAME_CASE(FCVT_WU_RV64) 10706 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10707 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10708 NODE_NAME_CASE(READ_CYCLE_WIDE) 10709 NODE_NAME_CASE(GREV) 10710 NODE_NAME_CASE(GREVW) 10711 NODE_NAME_CASE(GORC) 10712 NODE_NAME_CASE(GORCW) 10713 NODE_NAME_CASE(SHFL) 10714 NODE_NAME_CASE(SHFLW) 10715 NODE_NAME_CASE(UNSHFL) 10716 NODE_NAME_CASE(UNSHFLW) 10717 NODE_NAME_CASE(BFP) 10718 NODE_NAME_CASE(BFPW) 10719 NODE_NAME_CASE(BCOMPRESS) 10720 NODE_NAME_CASE(BCOMPRESSW) 10721 NODE_NAME_CASE(BDECOMPRESS) 10722 NODE_NAME_CASE(BDECOMPRESSW) 10723 NODE_NAME_CASE(VMV_V_X_VL) 10724 NODE_NAME_CASE(VFMV_V_F_VL) 10725 NODE_NAME_CASE(VMV_X_S) 10726 NODE_NAME_CASE(VMV_S_X_VL) 10727 NODE_NAME_CASE(VFMV_S_F_VL) 10728 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10729 NODE_NAME_CASE(READ_VLENB) 10730 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10731 NODE_NAME_CASE(VSLIDEUP_VL) 10732 NODE_NAME_CASE(VSLIDE1UP_VL) 10733 NODE_NAME_CASE(VSLIDEDOWN_VL) 10734 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10735 NODE_NAME_CASE(VID_VL) 10736 NODE_NAME_CASE(VFNCVT_ROD_VL) 10737 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10738 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10739 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10740 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10741 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10742 NODE_NAME_CASE(VECREDUCE_AND_VL) 10743 NODE_NAME_CASE(VECREDUCE_OR_VL) 10744 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10745 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10746 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10747 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10748 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10749 NODE_NAME_CASE(ADD_VL) 10750 NODE_NAME_CASE(AND_VL) 10751 NODE_NAME_CASE(MUL_VL) 10752 NODE_NAME_CASE(OR_VL) 10753 NODE_NAME_CASE(SDIV_VL) 10754 NODE_NAME_CASE(SHL_VL) 10755 NODE_NAME_CASE(SREM_VL) 10756 NODE_NAME_CASE(SRA_VL) 10757 NODE_NAME_CASE(SRL_VL) 10758 NODE_NAME_CASE(SUB_VL) 10759 NODE_NAME_CASE(UDIV_VL) 10760 NODE_NAME_CASE(UREM_VL) 10761 NODE_NAME_CASE(XOR_VL) 10762 NODE_NAME_CASE(SADDSAT_VL) 10763 NODE_NAME_CASE(UADDSAT_VL) 10764 NODE_NAME_CASE(SSUBSAT_VL) 10765 NODE_NAME_CASE(USUBSAT_VL) 10766 NODE_NAME_CASE(FADD_VL) 10767 NODE_NAME_CASE(FSUB_VL) 10768 NODE_NAME_CASE(FMUL_VL) 10769 NODE_NAME_CASE(FDIV_VL) 10770 NODE_NAME_CASE(FNEG_VL) 10771 NODE_NAME_CASE(FABS_VL) 10772 NODE_NAME_CASE(FSQRT_VL) 10773 NODE_NAME_CASE(FMA_VL) 10774 NODE_NAME_CASE(FCOPYSIGN_VL) 10775 NODE_NAME_CASE(SMIN_VL) 10776 NODE_NAME_CASE(SMAX_VL) 10777 NODE_NAME_CASE(UMIN_VL) 10778 NODE_NAME_CASE(UMAX_VL) 10779 NODE_NAME_CASE(FMINNUM_VL) 10780 NODE_NAME_CASE(FMAXNUM_VL) 10781 NODE_NAME_CASE(MULHS_VL) 10782 NODE_NAME_CASE(MULHU_VL) 10783 NODE_NAME_CASE(FP_TO_SINT_VL) 10784 NODE_NAME_CASE(FP_TO_UINT_VL) 10785 NODE_NAME_CASE(SINT_TO_FP_VL) 10786 NODE_NAME_CASE(UINT_TO_FP_VL) 10787 NODE_NAME_CASE(FP_EXTEND_VL) 10788 NODE_NAME_CASE(FP_ROUND_VL) 10789 NODE_NAME_CASE(VWMUL_VL) 10790 NODE_NAME_CASE(VWMULU_VL) 10791 NODE_NAME_CASE(VWMULSU_VL) 10792 NODE_NAME_CASE(VWADD_VL) 10793 NODE_NAME_CASE(VWADDU_VL) 10794 NODE_NAME_CASE(VWSUB_VL) 10795 NODE_NAME_CASE(VWSUBU_VL) 10796 NODE_NAME_CASE(VWADD_W_VL) 10797 NODE_NAME_CASE(VWADDU_W_VL) 10798 NODE_NAME_CASE(VWSUB_W_VL) 10799 NODE_NAME_CASE(VWSUBU_W_VL) 10800 NODE_NAME_CASE(SETCC_VL) 10801 NODE_NAME_CASE(VSELECT_VL) 10802 NODE_NAME_CASE(VP_MERGE_VL) 10803 NODE_NAME_CASE(VMAND_VL) 10804 NODE_NAME_CASE(VMOR_VL) 10805 NODE_NAME_CASE(VMXOR_VL) 10806 NODE_NAME_CASE(VMCLR_VL) 10807 NODE_NAME_CASE(VMSET_VL) 10808 NODE_NAME_CASE(VRGATHER_VX_VL) 10809 NODE_NAME_CASE(VRGATHER_VV_VL) 10810 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10811 NODE_NAME_CASE(VSEXT_VL) 10812 NODE_NAME_CASE(VZEXT_VL) 10813 NODE_NAME_CASE(VCPOP_VL) 10814 NODE_NAME_CASE(VLE_VL) 10815 NODE_NAME_CASE(VSE_VL) 10816 NODE_NAME_CASE(READ_CSR) 10817 NODE_NAME_CASE(WRITE_CSR) 10818 NODE_NAME_CASE(SWAP_CSR) 10819 } 10820 // clang-format on 10821 return nullptr; 10822 #undef NODE_NAME_CASE 10823 } 10824 10825 /// getConstraintType - Given a constraint letter, return the type of 10826 /// constraint it is for this target. 10827 RISCVTargetLowering::ConstraintType 10828 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10829 if (Constraint.size() == 1) { 10830 switch (Constraint[0]) { 10831 default: 10832 break; 10833 case 'f': 10834 return C_RegisterClass; 10835 case 'I': 10836 case 'J': 10837 case 'K': 10838 return C_Immediate; 10839 case 'A': 10840 return C_Memory; 10841 case 'S': // A symbolic address 10842 return C_Other; 10843 } 10844 } else { 10845 if (Constraint == "vr" || Constraint == "vm") 10846 return C_RegisterClass; 10847 } 10848 return TargetLowering::getConstraintType(Constraint); 10849 } 10850 10851 std::pair<unsigned, const TargetRegisterClass *> 10852 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10853 StringRef Constraint, 10854 MVT VT) const { 10855 // First, see if this is a constraint that directly corresponds to a 10856 // RISCV register class. 10857 if (Constraint.size() == 1) { 10858 switch (Constraint[0]) { 10859 case 'r': 10860 // TODO: Support fixed vectors up to XLen for P extension? 10861 if (VT.isVector()) 10862 break; 10863 return std::make_pair(0U, &RISCV::GPRRegClass); 10864 case 'f': 10865 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10866 return std::make_pair(0U, &RISCV::FPR16RegClass); 10867 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10868 return std::make_pair(0U, &RISCV::FPR32RegClass); 10869 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10870 return std::make_pair(0U, &RISCV::FPR64RegClass); 10871 break; 10872 default: 10873 break; 10874 } 10875 } else if (Constraint == "vr") { 10876 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10877 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10878 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10879 return std::make_pair(0U, RC); 10880 } 10881 } else if (Constraint == "vm") { 10882 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10883 return std::make_pair(0U, &RISCV::VMV0RegClass); 10884 } 10885 10886 // Clang will correctly decode the usage of register name aliases into their 10887 // official names. However, other frontends like `rustc` do not. This allows 10888 // users of these frontends to use the ABI names for registers in LLVM-style 10889 // register constraints. 10890 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10891 .Case("{zero}", RISCV::X0) 10892 .Case("{ra}", RISCV::X1) 10893 .Case("{sp}", RISCV::X2) 10894 .Case("{gp}", RISCV::X3) 10895 .Case("{tp}", RISCV::X4) 10896 .Case("{t0}", RISCV::X5) 10897 .Case("{t1}", RISCV::X6) 10898 .Case("{t2}", RISCV::X7) 10899 .Cases("{s0}", "{fp}", RISCV::X8) 10900 .Case("{s1}", RISCV::X9) 10901 .Case("{a0}", RISCV::X10) 10902 .Case("{a1}", RISCV::X11) 10903 .Case("{a2}", RISCV::X12) 10904 .Case("{a3}", RISCV::X13) 10905 .Case("{a4}", RISCV::X14) 10906 .Case("{a5}", RISCV::X15) 10907 .Case("{a6}", RISCV::X16) 10908 .Case("{a7}", RISCV::X17) 10909 .Case("{s2}", RISCV::X18) 10910 .Case("{s3}", RISCV::X19) 10911 .Case("{s4}", RISCV::X20) 10912 .Case("{s5}", RISCV::X21) 10913 .Case("{s6}", RISCV::X22) 10914 .Case("{s7}", RISCV::X23) 10915 .Case("{s8}", RISCV::X24) 10916 .Case("{s9}", RISCV::X25) 10917 .Case("{s10}", RISCV::X26) 10918 .Case("{s11}", RISCV::X27) 10919 .Case("{t3}", RISCV::X28) 10920 .Case("{t4}", RISCV::X29) 10921 .Case("{t5}", RISCV::X30) 10922 .Case("{t6}", RISCV::X31) 10923 .Default(RISCV::NoRegister); 10924 if (XRegFromAlias != RISCV::NoRegister) 10925 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10926 10927 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10928 // TableGen record rather than the AsmName to choose registers for InlineAsm 10929 // constraints, plus we want to match those names to the widest floating point 10930 // register type available, manually select floating point registers here. 10931 // 10932 // The second case is the ABI name of the register, so that frontends can also 10933 // use the ABI names in register constraint lists. 10934 if (Subtarget.hasStdExtF()) { 10935 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10936 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10937 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10938 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10939 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10940 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10941 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10942 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10943 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10944 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10945 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10946 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10947 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10948 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10949 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10950 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10951 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10952 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10953 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10954 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10955 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10956 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10957 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10958 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10959 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10960 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10961 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10962 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10963 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10964 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10965 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10966 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10967 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10968 .Default(RISCV::NoRegister); 10969 if (FReg != RISCV::NoRegister) { 10970 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10971 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10972 unsigned RegNo = FReg - RISCV::F0_F; 10973 unsigned DReg = RISCV::F0_D + RegNo; 10974 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10975 } 10976 if (VT == MVT::f32 || VT == MVT::Other) 10977 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10978 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10979 unsigned RegNo = FReg - RISCV::F0_F; 10980 unsigned HReg = RISCV::F0_H + RegNo; 10981 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10982 } 10983 } 10984 } 10985 10986 if (Subtarget.hasVInstructions()) { 10987 Register VReg = StringSwitch<Register>(Constraint.lower()) 10988 .Case("{v0}", RISCV::V0) 10989 .Case("{v1}", RISCV::V1) 10990 .Case("{v2}", RISCV::V2) 10991 .Case("{v3}", RISCV::V3) 10992 .Case("{v4}", RISCV::V4) 10993 .Case("{v5}", RISCV::V5) 10994 .Case("{v6}", RISCV::V6) 10995 .Case("{v7}", RISCV::V7) 10996 .Case("{v8}", RISCV::V8) 10997 .Case("{v9}", RISCV::V9) 10998 .Case("{v10}", RISCV::V10) 10999 .Case("{v11}", RISCV::V11) 11000 .Case("{v12}", RISCV::V12) 11001 .Case("{v13}", RISCV::V13) 11002 .Case("{v14}", RISCV::V14) 11003 .Case("{v15}", RISCV::V15) 11004 .Case("{v16}", RISCV::V16) 11005 .Case("{v17}", RISCV::V17) 11006 .Case("{v18}", RISCV::V18) 11007 .Case("{v19}", RISCV::V19) 11008 .Case("{v20}", RISCV::V20) 11009 .Case("{v21}", RISCV::V21) 11010 .Case("{v22}", RISCV::V22) 11011 .Case("{v23}", RISCV::V23) 11012 .Case("{v24}", RISCV::V24) 11013 .Case("{v25}", RISCV::V25) 11014 .Case("{v26}", RISCV::V26) 11015 .Case("{v27}", RISCV::V27) 11016 .Case("{v28}", RISCV::V28) 11017 .Case("{v29}", RISCV::V29) 11018 .Case("{v30}", RISCV::V30) 11019 .Case("{v31}", RISCV::V31) 11020 .Default(RISCV::NoRegister); 11021 if (VReg != RISCV::NoRegister) { 11022 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11023 return std::make_pair(VReg, &RISCV::VMRegClass); 11024 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11025 return std::make_pair(VReg, &RISCV::VRRegClass); 11026 for (const auto *RC : 11027 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11028 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11029 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11030 return std::make_pair(VReg, RC); 11031 } 11032 } 11033 } 11034 } 11035 11036 std::pair<Register, const TargetRegisterClass *> Res = 11037 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11038 11039 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11040 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11041 // Subtarget into account. 11042 if (Res.second == &RISCV::GPRF16RegClass || 11043 Res.second == &RISCV::GPRF32RegClass || 11044 Res.second == &RISCV::GPRF64RegClass) 11045 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11046 11047 return Res; 11048 } 11049 11050 unsigned 11051 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11052 // Currently only support length 1 constraints. 11053 if (ConstraintCode.size() == 1) { 11054 switch (ConstraintCode[0]) { 11055 case 'A': 11056 return InlineAsm::Constraint_A; 11057 default: 11058 break; 11059 } 11060 } 11061 11062 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11063 } 11064 11065 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11066 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11067 SelectionDAG &DAG) const { 11068 // Currently only support length 1 constraints. 11069 if (Constraint.length() == 1) { 11070 switch (Constraint[0]) { 11071 case 'I': 11072 // Validate & create a 12-bit signed immediate operand. 11073 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11074 uint64_t CVal = C->getSExtValue(); 11075 if (isInt<12>(CVal)) 11076 Ops.push_back( 11077 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11078 } 11079 return; 11080 case 'J': 11081 // Validate & create an integer zero operand. 11082 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11083 if (C->getZExtValue() == 0) 11084 Ops.push_back( 11085 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11086 return; 11087 case 'K': 11088 // Validate & create a 5-bit unsigned immediate operand. 11089 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11090 uint64_t CVal = C->getZExtValue(); 11091 if (isUInt<5>(CVal)) 11092 Ops.push_back( 11093 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11094 } 11095 return; 11096 case 'S': 11097 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11098 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11099 GA->getValueType(0))); 11100 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11101 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11102 BA->getValueType(0))); 11103 } 11104 return; 11105 default: 11106 break; 11107 } 11108 } 11109 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11110 } 11111 11112 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11113 Instruction *Inst, 11114 AtomicOrdering Ord) const { 11115 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11116 return Builder.CreateFence(Ord); 11117 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11118 return Builder.CreateFence(AtomicOrdering::Release); 11119 return nullptr; 11120 } 11121 11122 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11123 Instruction *Inst, 11124 AtomicOrdering Ord) const { 11125 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11126 return Builder.CreateFence(AtomicOrdering::Acquire); 11127 return nullptr; 11128 } 11129 11130 TargetLowering::AtomicExpansionKind 11131 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11132 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11133 // point operations can't be used in an lr/sc sequence without breaking the 11134 // forward-progress guarantee. 11135 if (AI->isFloatingPointOperation()) 11136 return AtomicExpansionKind::CmpXChg; 11137 11138 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11139 if (Size == 8 || Size == 16) 11140 return AtomicExpansionKind::MaskedIntrinsic; 11141 return AtomicExpansionKind::None; 11142 } 11143 11144 static Intrinsic::ID 11145 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11146 if (XLen == 32) { 11147 switch (BinOp) { 11148 default: 11149 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11150 case AtomicRMWInst::Xchg: 11151 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11152 case AtomicRMWInst::Add: 11153 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11154 case AtomicRMWInst::Sub: 11155 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11156 case AtomicRMWInst::Nand: 11157 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11158 case AtomicRMWInst::Max: 11159 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11160 case AtomicRMWInst::Min: 11161 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11162 case AtomicRMWInst::UMax: 11163 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11164 case AtomicRMWInst::UMin: 11165 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11166 } 11167 } 11168 11169 if (XLen == 64) { 11170 switch (BinOp) { 11171 default: 11172 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11173 case AtomicRMWInst::Xchg: 11174 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11175 case AtomicRMWInst::Add: 11176 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11177 case AtomicRMWInst::Sub: 11178 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11179 case AtomicRMWInst::Nand: 11180 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11181 case AtomicRMWInst::Max: 11182 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11183 case AtomicRMWInst::Min: 11184 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11185 case AtomicRMWInst::UMax: 11186 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11187 case AtomicRMWInst::UMin: 11188 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11189 } 11190 } 11191 11192 llvm_unreachable("Unexpected XLen\n"); 11193 } 11194 11195 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11196 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11197 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11198 unsigned XLen = Subtarget.getXLen(); 11199 Value *Ordering = 11200 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11201 Type *Tys[] = {AlignedAddr->getType()}; 11202 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11203 AI->getModule(), 11204 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11205 11206 if (XLen == 64) { 11207 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11208 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11209 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11210 } 11211 11212 Value *Result; 11213 11214 // Must pass the shift amount needed to sign extend the loaded value prior 11215 // to performing a signed comparison for min/max. ShiftAmt is the number of 11216 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11217 // is the number of bits to left+right shift the value in order to 11218 // sign-extend. 11219 if (AI->getOperation() == AtomicRMWInst::Min || 11220 AI->getOperation() == AtomicRMWInst::Max) { 11221 const DataLayout &DL = AI->getModule()->getDataLayout(); 11222 unsigned ValWidth = 11223 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11224 Value *SextShamt = 11225 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11226 Result = Builder.CreateCall(LrwOpScwLoop, 11227 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11228 } else { 11229 Result = 11230 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11231 } 11232 11233 if (XLen == 64) 11234 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11235 return Result; 11236 } 11237 11238 TargetLowering::AtomicExpansionKind 11239 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11240 AtomicCmpXchgInst *CI) const { 11241 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11242 if (Size == 8 || Size == 16) 11243 return AtomicExpansionKind::MaskedIntrinsic; 11244 return AtomicExpansionKind::None; 11245 } 11246 11247 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11248 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11249 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11250 unsigned XLen = Subtarget.getXLen(); 11251 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11252 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11253 if (XLen == 64) { 11254 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11255 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11256 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11257 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11258 } 11259 Type *Tys[] = {AlignedAddr->getType()}; 11260 Function *MaskedCmpXchg = 11261 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11262 Value *Result = Builder.CreateCall( 11263 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11264 if (XLen == 64) 11265 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11266 return Result; 11267 } 11268 11269 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11270 return false; 11271 } 11272 11273 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11274 EVT VT) const { 11275 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11276 return false; 11277 11278 switch (FPVT.getSimpleVT().SimpleTy) { 11279 case MVT::f16: 11280 return Subtarget.hasStdExtZfh(); 11281 case MVT::f32: 11282 return Subtarget.hasStdExtF(); 11283 case MVT::f64: 11284 return Subtarget.hasStdExtD(); 11285 default: 11286 return false; 11287 } 11288 } 11289 11290 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11291 // If we are using the small code model, we can reduce size of jump table 11292 // entry to 4 bytes. 11293 if (Subtarget.is64Bit() && !isPositionIndependent() && 11294 getTargetMachine().getCodeModel() == CodeModel::Small) { 11295 return MachineJumpTableInfo::EK_Custom32; 11296 } 11297 return TargetLowering::getJumpTableEncoding(); 11298 } 11299 11300 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11301 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11302 unsigned uid, MCContext &Ctx) const { 11303 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11304 getTargetMachine().getCodeModel() == CodeModel::Small); 11305 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11306 } 11307 11308 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11309 EVT VT) const { 11310 VT = VT.getScalarType(); 11311 11312 if (!VT.isSimple()) 11313 return false; 11314 11315 switch (VT.getSimpleVT().SimpleTy) { 11316 case MVT::f16: 11317 return Subtarget.hasStdExtZfh(); 11318 case MVT::f32: 11319 return Subtarget.hasStdExtF(); 11320 case MVT::f64: 11321 return Subtarget.hasStdExtD(); 11322 default: 11323 break; 11324 } 11325 11326 return false; 11327 } 11328 11329 Register RISCVTargetLowering::getExceptionPointerRegister( 11330 const Constant *PersonalityFn) const { 11331 return RISCV::X10; 11332 } 11333 11334 Register RISCVTargetLowering::getExceptionSelectorRegister( 11335 const Constant *PersonalityFn) const { 11336 return RISCV::X11; 11337 } 11338 11339 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11340 // Return false to suppress the unnecessary extensions if the LibCall 11341 // arguments or return value is f32 type for LP64 ABI. 11342 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11343 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11344 return false; 11345 11346 return true; 11347 } 11348 11349 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11350 if (Subtarget.is64Bit() && Type == MVT::i32) 11351 return true; 11352 11353 return IsSigned; 11354 } 11355 11356 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11357 SDValue C) const { 11358 // Check integral scalar types. 11359 if (VT.isScalarInteger()) { 11360 // Omit the optimization if the sub target has the M extension and the data 11361 // size exceeds XLen. 11362 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11363 return false; 11364 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11365 // Break the MUL to a SLLI and an ADD/SUB. 11366 const APInt &Imm = ConstNode->getAPIntValue(); 11367 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11368 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11369 return true; 11370 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11371 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11372 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11373 (Imm - 8).isPowerOf2())) 11374 return true; 11375 // Omit the following optimization if the sub target has the M extension 11376 // and the data size >= XLen. 11377 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11378 return false; 11379 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11380 // a pair of LUI/ADDI. 11381 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11382 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11383 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11384 (1 - ImmS).isPowerOf2()) 11385 return true; 11386 } 11387 } 11388 } 11389 11390 return false; 11391 } 11392 11393 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11394 SDValue ConstNode) const { 11395 // Let the DAGCombiner decide for vectors. 11396 EVT VT = AddNode.getValueType(); 11397 if (VT.isVector()) 11398 return true; 11399 11400 // Let the DAGCombiner decide for larger types. 11401 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11402 return true; 11403 11404 // It is worse if c1 is simm12 while c1*c2 is not. 11405 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11406 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11407 const APInt &C1 = C1Node->getAPIntValue(); 11408 const APInt &C2 = C2Node->getAPIntValue(); 11409 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11410 return false; 11411 11412 // Default to true and let the DAGCombiner decide. 11413 return true; 11414 } 11415 11416 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11417 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11418 bool *Fast) const { 11419 if (!VT.isVector()) 11420 return false; 11421 11422 EVT ElemVT = VT.getVectorElementType(); 11423 if (Alignment >= ElemVT.getStoreSize()) { 11424 if (Fast) 11425 *Fast = true; 11426 return true; 11427 } 11428 11429 return false; 11430 } 11431 11432 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11433 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11434 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11435 bool IsABIRegCopy = CC.hasValue(); 11436 EVT ValueVT = Val.getValueType(); 11437 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11438 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11439 // and cast to f32. 11440 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11441 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11442 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11443 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11444 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11445 Parts[0] = Val; 11446 return true; 11447 } 11448 11449 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11450 LLVMContext &Context = *DAG.getContext(); 11451 EVT ValueEltVT = ValueVT.getVectorElementType(); 11452 EVT PartEltVT = PartVT.getVectorElementType(); 11453 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11454 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11455 if (PartVTBitSize % ValueVTBitSize == 0) { 11456 assert(PartVTBitSize >= ValueVTBitSize); 11457 // If the element types are different, bitcast to the same element type of 11458 // PartVT first. 11459 // Give an example here, we want copy a <vscale x 1 x i8> value to 11460 // <vscale x 4 x i16>. 11461 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11462 // subvector, then we can bitcast to <vscale x 4 x i16>. 11463 if (ValueEltVT != PartEltVT) { 11464 if (PartVTBitSize > ValueVTBitSize) { 11465 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11466 assert(Count != 0 && "The number of element should not be zero."); 11467 EVT SameEltTypeVT = 11468 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11469 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11470 DAG.getUNDEF(SameEltTypeVT), Val, 11471 DAG.getVectorIdxConstant(0, DL)); 11472 } 11473 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11474 } else { 11475 Val = 11476 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11477 Val, DAG.getVectorIdxConstant(0, DL)); 11478 } 11479 Parts[0] = Val; 11480 return true; 11481 } 11482 } 11483 return false; 11484 } 11485 11486 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11487 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11488 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11489 bool IsABIRegCopy = CC.hasValue(); 11490 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11491 SDValue Val = Parts[0]; 11492 11493 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11494 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11495 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11496 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11497 return Val; 11498 } 11499 11500 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11501 LLVMContext &Context = *DAG.getContext(); 11502 SDValue Val = Parts[0]; 11503 EVT ValueEltVT = ValueVT.getVectorElementType(); 11504 EVT PartEltVT = PartVT.getVectorElementType(); 11505 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11506 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11507 if (PartVTBitSize % ValueVTBitSize == 0) { 11508 assert(PartVTBitSize >= ValueVTBitSize); 11509 EVT SameEltTypeVT = ValueVT; 11510 // If the element types are different, convert it to the same element type 11511 // of PartVT. 11512 // Give an example here, we want copy a <vscale x 1 x i8> value from 11513 // <vscale x 4 x i16>. 11514 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11515 // then we can extract <vscale x 1 x i8>. 11516 if (ValueEltVT != PartEltVT) { 11517 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11518 assert(Count != 0 && "The number of element should not be zero."); 11519 SameEltTypeVT = 11520 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11521 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11522 } 11523 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11524 DAG.getVectorIdxConstant(0, DL)); 11525 return Val; 11526 } 11527 } 11528 return SDValue(); 11529 } 11530 11531 SDValue 11532 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11533 SelectionDAG &DAG, 11534 SmallVectorImpl<SDNode *> &Created) const { 11535 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11536 if (isIntDivCheap(N->getValueType(0), Attr)) 11537 return SDValue(N, 0); // Lower SDIV as SDIV 11538 11539 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11540 "Unexpected divisor!"); 11541 11542 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11543 if (!Subtarget.hasStdExtZbt()) 11544 return SDValue(); 11545 11546 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11547 // Besides, more critical path instructions will be generated when dividing 11548 // by 2. So we keep using the original DAGs for these cases. 11549 unsigned Lg2 = Divisor.countTrailingZeros(); 11550 if (Lg2 == 1 || Lg2 >= 12) 11551 return SDValue(); 11552 11553 // fold (sdiv X, pow2) 11554 EVT VT = N->getValueType(0); 11555 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11556 return SDValue(); 11557 11558 SDLoc DL(N); 11559 SDValue N0 = N->getOperand(0); 11560 SDValue Zero = DAG.getConstant(0, DL, VT); 11561 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11562 11563 // Add (N0 < 0) ? Pow2 - 1 : 0; 11564 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11565 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11566 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11567 11568 Created.push_back(Cmp.getNode()); 11569 Created.push_back(Add.getNode()); 11570 Created.push_back(Sel.getNode()); 11571 11572 // Divide by pow2. 11573 SDValue SRA = 11574 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11575 11576 // If we're dividing by a positive value, we're done. Otherwise, we must 11577 // negate the result. 11578 if (Divisor.isNonNegative()) 11579 return SRA; 11580 11581 Created.push_back(SRA.getNode()); 11582 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11583 } 11584 11585 #define GET_REGISTER_MATCHER 11586 #include "RISCVGenAsmMatcher.inc" 11587 11588 Register 11589 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11590 const MachineFunction &MF) const { 11591 Register Reg = MatchRegisterAltName(RegName); 11592 if (Reg == RISCV::NoRegister) 11593 Reg = MatchRegisterName(RegName); 11594 if (Reg == RISCV::NoRegister) 11595 report_fatal_error( 11596 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11597 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11598 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11599 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11600 StringRef(RegName) + "\".")); 11601 return Reg; 11602 } 11603 11604 namespace llvm { 11605 namespace RISCVVIntrinsicsTable { 11606 11607 #define GET_RISCVVIntrinsicsTable_IMPL 11608 #include "RISCVGenSearchableTables.inc" 11609 11610 } // namespace RISCVVIntrinsicsTable 11611 11612 } // namespace llvm 11613