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/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 29 #include "llvm/CodeGen/ValueTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/IntrinsicsRISCV.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/KnownBits.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Support/raw_ostream.h" 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "riscv-lower" 44 45 STATISTIC(NumTailCalls, "Number of tail calls"); 46 47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 48 const RISCVSubtarget &STI) 49 : TargetLowering(TM), Subtarget(STI) { 50 51 if (Subtarget.isRV32E()) 52 report_fatal_error("Codegen not yet implemented for RV32E"); 53 54 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 55 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 56 57 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 58 !Subtarget.hasStdExtF()) { 59 errs() << "Hard-float 'f' ABI can't be used for a target that " 60 "doesn't support the F instruction set extension (ignoring " 61 "target-abi)\n"; 62 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 63 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 64 !Subtarget.hasStdExtD()) { 65 errs() << "Hard-float 'd' ABI can't be used for a target that " 66 "doesn't support the D instruction set extension (ignoring " 67 "target-abi)\n"; 68 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 69 } 70 71 switch (ABI) { 72 default: 73 report_fatal_error("Don't know how to lower this ABI"); 74 case RISCVABI::ABI_ILP32: 75 case RISCVABI::ABI_ILP32F: 76 case RISCVABI::ABI_ILP32D: 77 case RISCVABI::ABI_LP64: 78 case RISCVABI::ABI_LP64F: 79 case RISCVABI::ABI_LP64D: 80 break; 81 } 82 83 MVT XLenVT = Subtarget.getXLenVT(); 84 85 // Set up the register classes. 86 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 87 88 if (Subtarget.hasStdExtZfh()) 89 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 90 if (Subtarget.hasStdExtF()) 91 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 92 if (Subtarget.hasStdExtD()) 93 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 94 95 static const MVT::SimpleValueType BoolVecVTs[] = { 96 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 97 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 98 static const MVT::SimpleValueType IntVecVTs[] = { 99 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 100 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 101 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 102 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 103 MVT::nxv4i64, MVT::nxv8i64}; 104 static const MVT::SimpleValueType F16VecVTs[] = { 105 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 106 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 107 static const MVT::SimpleValueType F32VecVTs[] = { 108 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 109 static const MVT::SimpleValueType F64VecVTs[] = { 110 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 111 112 if (Subtarget.hasVInstructions()) { 113 auto addRegClassForRVV = [this](MVT VT) { 114 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 115 assert(Size <= 512 && isPowerOf2_32(Size)); 116 const TargetRegisterClass *RC; 117 if (Size <= 64) 118 RC = &RISCV::VRRegClass; 119 else if (Size == 128) 120 RC = &RISCV::VRM2RegClass; 121 else if (Size == 256) 122 RC = &RISCV::VRM4RegClass; 123 else 124 RC = &RISCV::VRM8RegClass; 125 126 addRegisterClass(VT, RC); 127 }; 128 129 for (MVT VT : BoolVecVTs) 130 addRegClassForRVV(VT); 131 for (MVT VT : IntVecVTs) { 132 if (VT.getVectorElementType() == MVT::i64 && 133 !Subtarget.hasVInstructionsI64()) 134 continue; 135 addRegClassForRVV(VT); 136 } 137 138 if (Subtarget.hasVInstructionsF16()) 139 for (MVT VT : F16VecVTs) 140 addRegClassForRVV(VT); 141 142 if (Subtarget.hasVInstructionsF32()) 143 for (MVT VT : F32VecVTs) 144 addRegClassForRVV(VT); 145 146 if (Subtarget.hasVInstructionsF64()) 147 for (MVT VT : F64VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.useRVVForFixedLengthVectors()) { 151 auto addRegClassForFixedVectors = [this](MVT VT) { 152 MVT ContainerVT = getContainerForFixedLengthVector(VT); 153 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 154 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 155 addRegisterClass(VT, TRI.getRegClass(RCID)); 156 }; 157 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 158 if (useRVVForFixedLengthVectorVT(VT)) 159 addRegClassForFixedVectors(VT); 160 161 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 162 if (useRVVForFixedLengthVectorVT(VT)) 163 addRegClassForFixedVectors(VT); 164 } 165 } 166 167 // Compute derived properties from the register classes. 168 computeRegisterProperties(STI.getRegisterInfo()); 169 170 setStackPointerRegisterToSaveRestore(RISCV::X2); 171 172 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 173 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 174 175 // TODO: add all necessary setOperationAction calls. 176 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 177 178 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 179 setOperationAction(ISD::BR_CC, XLenVT, Expand); 180 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 181 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 182 183 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 184 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction(ISD::VAARG, MVT::Other, Expand); 188 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 189 setOperationAction(ISD::VAEND, MVT::Other, Expand); 190 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 192 if (!Subtarget.hasStdExtZbb()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 195 } 196 197 if (Subtarget.is64Bit()) { 198 setOperationAction(ISD::ADD, MVT::i32, Custom); 199 setOperationAction(ISD::SUB, MVT::i32, Custom); 200 setOperationAction(ISD::SHL, MVT::i32, Custom); 201 setOperationAction(ISD::SRA, MVT::i32, Custom); 202 setOperationAction(ISD::SRL, MVT::i32, Custom); 203 204 setOperationAction(ISD::UADDO, MVT::i32, Custom); 205 setOperationAction(ISD::USUBO, MVT::i32, Custom); 206 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 207 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 208 } else { 209 setLibcallName(RTLIB::SHL_I128, nullptr); 210 setLibcallName(RTLIB::SRL_I128, nullptr); 211 setLibcallName(RTLIB::SRA_I128, nullptr); 212 setLibcallName(RTLIB::MUL_I128, nullptr); 213 setLibcallName(RTLIB::MULO_I64, nullptr); 214 } 215 216 if (!Subtarget.hasStdExtM()) { 217 setOperationAction(ISD::MUL, XLenVT, Expand); 218 setOperationAction(ISD::MULHS, XLenVT, Expand); 219 setOperationAction(ISD::MULHU, XLenVT, Expand); 220 setOperationAction(ISD::SDIV, XLenVT, Expand); 221 setOperationAction(ISD::UDIV, XLenVT, Expand); 222 setOperationAction(ISD::SREM, XLenVT, Expand); 223 setOperationAction(ISD::UREM, XLenVT, Expand); 224 } else { 225 if (Subtarget.is64Bit()) { 226 setOperationAction(ISD::MUL, MVT::i32, Custom); 227 setOperationAction(ISD::MUL, MVT::i128, Custom); 228 229 setOperationAction(ISD::SDIV, MVT::i8, Custom); 230 setOperationAction(ISD::UDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UREM, MVT::i8, Custom); 232 setOperationAction(ISD::SDIV, MVT::i16, Custom); 233 setOperationAction(ISD::UDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UREM, MVT::i16, Custom); 235 setOperationAction(ISD::SDIV, MVT::i32, Custom); 236 setOperationAction(ISD::UDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UREM, MVT::i32, Custom); 238 } else { 239 setOperationAction(ISD::MUL, MVT::i64, Custom); 240 } 241 } 242 243 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 244 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 246 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 247 248 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 249 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 251 252 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::ROTL, MVT::i32, Custom); 255 setOperationAction(ISD::ROTR, MVT::i32, Custom); 256 } 257 } else { 258 setOperationAction(ISD::ROTL, XLenVT, Expand); 259 setOperationAction(ISD::ROTR, XLenVT, Expand); 260 } 261 262 if (Subtarget.hasStdExtZbp()) { 263 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 264 // more combining. 265 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 266 setOperationAction(ISD::BSWAP, XLenVT, Custom); 267 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 268 // BSWAP i8 doesn't exist. 269 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 270 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 271 272 if (Subtarget.is64Bit()) { 273 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 274 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 275 } 276 } else { 277 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 278 // pattern match it directly in isel. 279 setOperationAction(ISD::BSWAP, XLenVT, 280 Subtarget.hasStdExtZbb() ? Legal : Expand); 281 } 282 283 if (Subtarget.hasStdExtZbb()) { 284 setOperationAction(ISD::SMIN, XLenVT, Legal); 285 setOperationAction(ISD::SMAX, XLenVT, Legal); 286 setOperationAction(ISD::UMIN, XLenVT, Legal); 287 setOperationAction(ISD::UMAX, XLenVT, Legal); 288 289 if (Subtarget.is64Bit()) { 290 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 291 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 292 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 293 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 294 } 295 } else { 296 setOperationAction(ISD::CTTZ, XLenVT, Expand); 297 setOperationAction(ISD::CTLZ, XLenVT, Expand); 298 setOperationAction(ISD::CTPOP, XLenVT, Expand); 299 } 300 301 if (Subtarget.hasStdExtZbt()) { 302 setOperationAction(ISD::FSHL, XLenVT, Custom); 303 setOperationAction(ISD::FSHR, XLenVT, Custom); 304 setOperationAction(ISD::SELECT, XLenVT, Legal); 305 306 if (Subtarget.is64Bit()) { 307 setOperationAction(ISD::FSHL, MVT::i32, Custom); 308 setOperationAction(ISD::FSHR, MVT::i32, Custom); 309 } 310 } else { 311 setOperationAction(ISD::SELECT, XLenVT, Custom); 312 } 313 314 static const ISD::CondCode FPCCToExpand[] = { 315 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 316 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 317 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 318 319 static const ISD::NodeType FPOpToExpand[] = { 320 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 321 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 322 323 if (Subtarget.hasStdExtZfh()) 324 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 325 326 if (Subtarget.hasStdExtZfh()) { 327 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 328 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 329 setOperationAction(ISD::LRINT, MVT::f16, Legal); 330 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 331 setOperationAction(ISD::LROUND, MVT::f16, Legal); 332 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 333 for (auto CC : FPCCToExpand) 334 setCondCodeAction(CC, MVT::f16, Expand); 335 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 336 setOperationAction(ISD::SELECT, MVT::f16, Custom); 337 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 338 for (auto Op : FPOpToExpand) 339 setOperationAction(Op, MVT::f16, Expand); 340 341 setOperationAction(ISD::FREM, MVT::f16, Promote); 342 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 343 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 344 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 345 setOperationAction(ISD::FRINT, MVT::f16, Promote); 346 setOperationAction(ISD::FROUND, MVT::f16, Promote); 347 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 348 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 349 } 350 351 if (Subtarget.hasStdExtF()) { 352 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 353 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 354 setOperationAction(ISD::LRINT, MVT::f32, Legal); 355 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 356 setOperationAction(ISD::LROUND, MVT::f32, Legal); 357 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 358 for (auto CC : FPCCToExpand) 359 setCondCodeAction(CC, MVT::f32, Expand); 360 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 361 setOperationAction(ISD::SELECT, MVT::f32, Custom); 362 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 363 for (auto Op : FPOpToExpand) 364 setOperationAction(Op, MVT::f32, Expand); 365 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 366 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 367 } 368 369 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 370 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 371 372 if (Subtarget.hasStdExtD()) { 373 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 374 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 375 setOperationAction(ISD::LRINT, MVT::f64, Legal); 376 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 377 setOperationAction(ISD::LROUND, MVT::f64, Legal); 378 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 379 for (auto CC : FPCCToExpand) 380 setCondCodeAction(CC, MVT::f64, Expand); 381 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 382 setOperationAction(ISD::SELECT, MVT::f64, Custom); 383 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 384 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 385 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 386 for (auto Op : FPOpToExpand) 387 setOperationAction(Op, MVT::f64, Expand); 388 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 389 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 390 } 391 392 if (Subtarget.is64Bit()) { 393 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 394 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 395 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 396 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 397 } 398 399 if (Subtarget.hasStdExtF()) { 400 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 401 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 402 403 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 404 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 405 } 406 407 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 408 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 409 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 410 setOperationAction(ISD::JumpTable, XLenVT, Custom); 411 412 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 413 414 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 415 // Unfortunately this can't be determined just from the ISA naming string. 416 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 417 Subtarget.is64Bit() ? Legal : Custom); 418 419 setOperationAction(ISD::TRAP, MVT::Other, Legal); 420 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 421 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 422 if (Subtarget.is64Bit()) 423 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 424 425 if (Subtarget.hasStdExtA()) { 426 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 427 setMinCmpXchgSizeInBits(32); 428 } else { 429 setMaxAtomicSizeInBitsSupported(0); 430 } 431 432 setBooleanContents(ZeroOrOneBooleanContent); 433 434 if (Subtarget.hasVInstructions()) { 435 setBooleanVectorContents(ZeroOrOneBooleanContent); 436 437 setOperationAction(ISD::VSCALE, XLenVT, Custom); 438 439 // RVV intrinsics may have illegal operands. 440 // We also need to custom legalize vmv.x.s. 441 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 442 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 443 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 444 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 445 if (Subtarget.is64Bit()) { 446 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 447 } else { 448 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 449 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 450 } 451 452 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 453 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 454 455 static const unsigned IntegerVPOps[] = { 456 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 457 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 458 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 459 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 460 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 461 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 462 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}; 463 464 static const unsigned FloatingPointVPOps[] = { 465 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 466 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 467 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX}; 468 469 if (!Subtarget.is64Bit()) { 470 // We must custom-lower certain vXi64 operations on RV32 due to the vector 471 // element type being illegal. 472 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 473 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 474 475 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 476 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 477 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 478 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 479 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 480 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 481 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 482 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 483 484 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 485 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 486 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 487 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 488 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 489 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 490 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 491 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 492 } 493 494 for (MVT VT : BoolVecVTs) { 495 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 496 497 // Mask VTs are custom-expanded into a series of standard nodes 498 setOperationAction(ISD::TRUNCATE, VT, Custom); 499 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 500 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 501 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 502 503 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 504 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 505 506 setOperationAction(ISD::SELECT, VT, Custom); 507 setOperationAction(ISD::SELECT_CC, VT, Expand); 508 setOperationAction(ISD::VSELECT, VT, Expand); 509 510 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 511 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 512 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 513 514 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 515 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 516 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 517 518 // RVV has native int->float & float->int conversions where the 519 // element type sizes are within one power-of-two of each other. Any 520 // wider distances between type sizes have to be lowered as sequences 521 // which progressively narrow the gap in stages. 522 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 523 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 524 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 525 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 526 527 // Expand all extending loads to types larger than this, and truncating 528 // stores from types larger than this. 529 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 530 setTruncStoreAction(OtherVT, VT, Expand); 531 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 532 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 533 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 534 } 535 } 536 537 for (MVT VT : IntVecVTs) { 538 if (VT.getVectorElementType() == MVT::i64 && 539 !Subtarget.hasVInstructionsI64()) 540 continue; 541 542 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 543 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 544 545 // Vectors implement MULHS/MULHU. 546 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 547 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 548 549 setOperationAction(ISD::SMIN, VT, Legal); 550 setOperationAction(ISD::SMAX, VT, Legal); 551 setOperationAction(ISD::UMIN, VT, Legal); 552 setOperationAction(ISD::UMAX, VT, Legal); 553 554 setOperationAction(ISD::ROTL, VT, Expand); 555 setOperationAction(ISD::ROTR, VT, Expand); 556 557 setOperationAction(ISD::CTTZ, VT, Expand); 558 setOperationAction(ISD::CTLZ, VT, Expand); 559 setOperationAction(ISD::CTPOP, VT, Expand); 560 561 setOperationAction(ISD::BSWAP, VT, Expand); 562 563 // Custom-lower extensions and truncations from/to mask types. 564 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 565 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 566 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 567 568 // RVV has native int->float & float->int conversions where the 569 // element type sizes are within one power-of-two of each other. Any 570 // wider distances between type sizes have to be lowered as sequences 571 // which progressively narrow the gap in stages. 572 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 573 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 574 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 575 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 576 577 setOperationAction(ISD::SADDSAT, VT, Legal); 578 setOperationAction(ISD::UADDSAT, VT, Legal); 579 setOperationAction(ISD::SSUBSAT, VT, Legal); 580 setOperationAction(ISD::USUBSAT, VT, Legal); 581 582 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 583 // nodes which truncate by one power of two at a time. 584 setOperationAction(ISD::TRUNCATE, VT, Custom); 585 586 // Custom-lower insert/extract operations to simplify patterns. 587 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 588 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 589 590 // Custom-lower reduction operations to set up the corresponding custom 591 // nodes' operands. 592 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 593 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 594 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 595 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 596 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 597 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 598 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 599 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 600 601 for (unsigned VPOpc : IntegerVPOps) 602 setOperationAction(VPOpc, VT, Custom); 603 604 setOperationAction(ISD::LOAD, VT, Custom); 605 setOperationAction(ISD::STORE, VT, Custom); 606 607 setOperationAction(ISD::MLOAD, VT, Custom); 608 setOperationAction(ISD::MSTORE, VT, Custom); 609 setOperationAction(ISD::MGATHER, VT, Custom); 610 setOperationAction(ISD::MSCATTER, VT, Custom); 611 612 setOperationAction(ISD::VP_LOAD, VT, Custom); 613 setOperationAction(ISD::VP_STORE, VT, Custom); 614 setOperationAction(ISD::VP_GATHER, VT, Custom); 615 setOperationAction(ISD::VP_SCATTER, VT, Custom); 616 617 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 618 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 619 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 620 621 setOperationAction(ISD::SELECT, VT, Custom); 622 setOperationAction(ISD::SELECT_CC, VT, Expand); 623 624 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 625 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 626 627 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 628 setTruncStoreAction(VT, OtherVT, Expand); 629 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 630 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 631 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 632 } 633 634 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 635 // type that can represent the value exactly. 636 if (VT.getVectorElementType() != MVT::i64) { 637 MVT FloatEltVT = 638 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 639 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 640 if (isTypeLegal(FloatVT)) { 641 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 642 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 643 } 644 } 645 } 646 647 // Expand various CCs to best match the RVV ISA, which natively supports UNE 648 // but no other unordered comparisons, and supports all ordered comparisons 649 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 650 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 651 // and we pattern-match those back to the "original", swapping operands once 652 // more. This way we catch both operations and both "vf" and "fv" forms with 653 // fewer patterns. 654 static const ISD::CondCode VFPCCToExpand[] = { 655 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 656 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 657 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 658 }; 659 660 // Sets common operation actions on RVV floating-point vector types. 661 const auto SetCommonVFPActions = [&](MVT VT) { 662 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 663 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 664 // sizes are within one power-of-two of each other. Therefore conversions 665 // between vXf16 and vXf64 must be lowered as sequences which convert via 666 // vXf32. 667 setOperationAction(ISD::FP_ROUND, VT, Custom); 668 setOperationAction(ISD::FP_EXTEND, VT, Custom); 669 // Custom-lower insert/extract operations to simplify patterns. 670 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 672 // Expand various condition codes (explained above). 673 for (auto CC : VFPCCToExpand) 674 setCondCodeAction(CC, VT, Expand); 675 676 setOperationAction(ISD::FMINNUM, VT, Legal); 677 setOperationAction(ISD::FMAXNUM, VT, Legal); 678 679 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 681 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 682 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 683 684 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 685 686 setOperationAction(ISD::LOAD, VT, Custom); 687 setOperationAction(ISD::STORE, VT, Custom); 688 689 setOperationAction(ISD::MLOAD, VT, Custom); 690 setOperationAction(ISD::MSTORE, VT, Custom); 691 setOperationAction(ISD::MGATHER, VT, Custom); 692 setOperationAction(ISD::MSCATTER, VT, Custom); 693 694 setOperationAction(ISD::VP_LOAD, VT, Custom); 695 setOperationAction(ISD::VP_STORE, VT, Custom); 696 setOperationAction(ISD::VP_GATHER, VT, Custom); 697 setOperationAction(ISD::VP_SCATTER, VT, Custom); 698 699 setOperationAction(ISD::SELECT, VT, Custom); 700 setOperationAction(ISD::SELECT_CC, VT, Expand); 701 702 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 703 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 704 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 705 706 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 707 708 for (unsigned VPOpc : FloatingPointVPOps) 709 setOperationAction(VPOpc, VT, Custom); 710 }; 711 712 // Sets common extload/truncstore actions on RVV floating-point vector 713 // types. 714 const auto SetCommonVFPExtLoadTruncStoreActions = 715 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 716 for (auto SmallVT : SmallerVTs) { 717 setTruncStoreAction(VT, SmallVT, Expand); 718 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 719 } 720 }; 721 722 if (Subtarget.hasVInstructionsF16()) 723 for (MVT VT : F16VecVTs) 724 SetCommonVFPActions(VT); 725 726 for (MVT VT : F32VecVTs) { 727 if (Subtarget.hasVInstructionsF32()) 728 SetCommonVFPActions(VT); 729 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 730 } 731 732 for (MVT VT : F64VecVTs) { 733 if (Subtarget.hasVInstructionsF64()) 734 SetCommonVFPActions(VT); 735 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 736 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 737 } 738 739 if (Subtarget.useRVVForFixedLengthVectors()) { 740 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 741 if (!useRVVForFixedLengthVectorVT(VT)) 742 continue; 743 744 // By default everything must be expanded. 745 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 746 setOperationAction(Op, VT, Expand); 747 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 748 setTruncStoreAction(VT, OtherVT, Expand); 749 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 750 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 751 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 752 } 753 754 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 755 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 756 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 757 758 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 759 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 760 761 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 763 764 setOperationAction(ISD::LOAD, VT, Custom); 765 setOperationAction(ISD::STORE, VT, Custom); 766 767 setOperationAction(ISD::SETCC, VT, Custom); 768 769 setOperationAction(ISD::SELECT, VT, Custom); 770 771 setOperationAction(ISD::TRUNCATE, VT, Custom); 772 773 setOperationAction(ISD::BITCAST, VT, Custom); 774 775 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 776 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 777 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 778 779 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 780 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 781 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 782 783 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 784 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 785 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 786 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 787 788 // Operations below are different for between masks and other vectors. 789 if (VT.getVectorElementType() == MVT::i1) { 790 setOperationAction(ISD::AND, VT, Custom); 791 setOperationAction(ISD::OR, VT, Custom); 792 setOperationAction(ISD::XOR, VT, Custom); 793 continue; 794 } 795 796 // Use SPLAT_VECTOR to prevent type legalization from destroying the 797 // splats when type legalizing i64 scalar on RV32. 798 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 799 // improvements first. 800 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 801 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 802 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 803 } 804 805 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 806 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 807 808 setOperationAction(ISD::MLOAD, VT, Custom); 809 setOperationAction(ISD::MSTORE, VT, Custom); 810 setOperationAction(ISD::MGATHER, VT, Custom); 811 setOperationAction(ISD::MSCATTER, VT, Custom); 812 813 setOperationAction(ISD::VP_LOAD, VT, Custom); 814 setOperationAction(ISD::VP_STORE, VT, Custom); 815 setOperationAction(ISD::VP_GATHER, VT, Custom); 816 setOperationAction(ISD::VP_SCATTER, VT, Custom); 817 818 setOperationAction(ISD::ADD, VT, Custom); 819 setOperationAction(ISD::MUL, VT, Custom); 820 setOperationAction(ISD::SUB, VT, Custom); 821 setOperationAction(ISD::AND, VT, Custom); 822 setOperationAction(ISD::OR, VT, Custom); 823 setOperationAction(ISD::XOR, VT, Custom); 824 setOperationAction(ISD::SDIV, VT, Custom); 825 setOperationAction(ISD::SREM, VT, Custom); 826 setOperationAction(ISD::UDIV, VT, Custom); 827 setOperationAction(ISD::UREM, VT, Custom); 828 setOperationAction(ISD::SHL, VT, Custom); 829 setOperationAction(ISD::SRA, VT, Custom); 830 setOperationAction(ISD::SRL, VT, Custom); 831 832 setOperationAction(ISD::SMIN, VT, Custom); 833 setOperationAction(ISD::SMAX, VT, Custom); 834 setOperationAction(ISD::UMIN, VT, Custom); 835 setOperationAction(ISD::UMAX, VT, Custom); 836 setOperationAction(ISD::ABS, VT, Custom); 837 838 setOperationAction(ISD::MULHS, VT, Custom); 839 setOperationAction(ISD::MULHU, VT, Custom); 840 841 setOperationAction(ISD::SADDSAT, VT, Custom); 842 setOperationAction(ISD::UADDSAT, VT, Custom); 843 setOperationAction(ISD::SSUBSAT, VT, Custom); 844 setOperationAction(ISD::USUBSAT, VT, Custom); 845 846 setOperationAction(ISD::VSELECT, VT, Custom); 847 setOperationAction(ISD::SELECT_CC, VT, Expand); 848 849 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 850 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 851 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 852 853 // Custom-lower reduction operations to set up the corresponding custom 854 // nodes' operands. 855 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 856 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 857 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 858 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 859 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 860 861 for (unsigned VPOpc : IntegerVPOps) 862 setOperationAction(VPOpc, VT, Custom); 863 864 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 865 // type that can represent the value exactly. 866 if (VT.getVectorElementType() != MVT::i64) { 867 MVT FloatEltVT = 868 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 869 EVT FloatVT = 870 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 871 if (isTypeLegal(FloatVT)) { 872 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 874 } 875 } 876 } 877 878 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 879 if (!useRVVForFixedLengthVectorVT(VT)) 880 continue; 881 882 // By default everything must be expanded. 883 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 884 setOperationAction(Op, VT, Expand); 885 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 886 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 887 setTruncStoreAction(VT, OtherVT, Expand); 888 } 889 890 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 891 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 892 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 893 894 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 895 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 896 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 897 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 899 900 setOperationAction(ISD::LOAD, VT, Custom); 901 setOperationAction(ISD::STORE, VT, Custom); 902 setOperationAction(ISD::MLOAD, VT, Custom); 903 setOperationAction(ISD::MSTORE, VT, Custom); 904 setOperationAction(ISD::MGATHER, VT, Custom); 905 setOperationAction(ISD::MSCATTER, VT, Custom); 906 907 setOperationAction(ISD::VP_LOAD, VT, Custom); 908 setOperationAction(ISD::VP_STORE, VT, Custom); 909 setOperationAction(ISD::VP_GATHER, VT, Custom); 910 setOperationAction(ISD::VP_SCATTER, VT, Custom); 911 912 setOperationAction(ISD::FADD, VT, Custom); 913 setOperationAction(ISD::FSUB, VT, Custom); 914 setOperationAction(ISD::FMUL, VT, Custom); 915 setOperationAction(ISD::FDIV, VT, Custom); 916 setOperationAction(ISD::FNEG, VT, Custom); 917 setOperationAction(ISD::FABS, VT, Custom); 918 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 919 setOperationAction(ISD::FSQRT, VT, Custom); 920 setOperationAction(ISD::FMA, VT, Custom); 921 setOperationAction(ISD::FMINNUM, VT, Custom); 922 setOperationAction(ISD::FMAXNUM, VT, Custom); 923 924 setOperationAction(ISD::FP_ROUND, VT, Custom); 925 setOperationAction(ISD::FP_EXTEND, VT, Custom); 926 927 for (auto CC : VFPCCToExpand) 928 setCondCodeAction(CC, VT, Expand); 929 930 setOperationAction(ISD::VSELECT, VT, Custom); 931 setOperationAction(ISD::SELECT, VT, Custom); 932 setOperationAction(ISD::SELECT_CC, VT, Expand); 933 934 setOperationAction(ISD::BITCAST, VT, Custom); 935 936 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 937 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 938 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 939 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 940 941 for (unsigned VPOpc : FloatingPointVPOps) 942 setOperationAction(VPOpc, VT, Custom); 943 } 944 945 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 946 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 947 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 948 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 949 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 950 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 951 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 952 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 953 } 954 } 955 956 // Function alignments. 957 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 958 setMinFunctionAlignment(FunctionAlignment); 959 setPrefFunctionAlignment(FunctionAlignment); 960 961 setMinimumJumpTableEntries(5); 962 963 // Jumps are expensive, compared to logic 964 setJumpIsExpensive(); 965 966 // We can use any register for comparisons 967 setHasMultipleConditionRegisters(); 968 969 setTargetDAGCombine(ISD::ADD); 970 setTargetDAGCombine(ISD::SUB); 971 setTargetDAGCombine(ISD::AND); 972 setTargetDAGCombine(ISD::OR); 973 setTargetDAGCombine(ISD::XOR); 974 setTargetDAGCombine(ISD::ANY_EXTEND); 975 setTargetDAGCombine(ISD::ZERO_EXTEND); 976 if (Subtarget.hasVInstructions()) { 977 setTargetDAGCombine(ISD::FCOPYSIGN); 978 setTargetDAGCombine(ISD::MGATHER); 979 setTargetDAGCombine(ISD::MSCATTER); 980 setTargetDAGCombine(ISD::VP_GATHER); 981 setTargetDAGCombine(ISD::VP_SCATTER); 982 setTargetDAGCombine(ISD::SRA); 983 setTargetDAGCombine(ISD::SRL); 984 setTargetDAGCombine(ISD::SHL); 985 setTargetDAGCombine(ISD::STORE); 986 } 987 } 988 989 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 990 LLVMContext &Context, 991 EVT VT) const { 992 if (!VT.isVector()) 993 return getPointerTy(DL); 994 if (Subtarget.hasVInstructions() && 995 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 996 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 997 return VT.changeVectorElementTypeToInteger(); 998 } 999 1000 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1001 return Subtarget.getXLenVT(); 1002 } 1003 1004 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1005 const CallInst &I, 1006 MachineFunction &MF, 1007 unsigned Intrinsic) const { 1008 auto &DL = I.getModule()->getDataLayout(); 1009 switch (Intrinsic) { 1010 default: 1011 return false; 1012 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1013 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1014 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1015 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1016 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1017 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1018 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1019 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1020 case Intrinsic::riscv_masked_cmpxchg_i32: { 1021 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 1022 Info.opc = ISD::INTRINSIC_W_CHAIN; 1023 Info.memVT = MVT::getVT(PtrTy->getElementType()); 1024 Info.ptrVal = I.getArgOperand(0); 1025 Info.offset = 0; 1026 Info.align = Align(4); 1027 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1028 MachineMemOperand::MOVolatile; 1029 return true; 1030 } 1031 case Intrinsic::riscv_masked_strided_load: 1032 Info.opc = ISD::INTRINSIC_W_CHAIN; 1033 Info.ptrVal = I.getArgOperand(1); 1034 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1035 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1036 Info.size = MemoryLocation::UnknownSize; 1037 Info.flags |= MachineMemOperand::MOLoad; 1038 return true; 1039 case Intrinsic::riscv_masked_strided_store: 1040 Info.opc = ISD::INTRINSIC_VOID; 1041 Info.ptrVal = I.getArgOperand(1); 1042 Info.memVT = 1043 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1044 Info.align = Align( 1045 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1046 8); 1047 Info.size = MemoryLocation::UnknownSize; 1048 Info.flags |= MachineMemOperand::MOStore; 1049 return true; 1050 } 1051 } 1052 1053 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1054 const AddrMode &AM, Type *Ty, 1055 unsigned AS, 1056 Instruction *I) const { 1057 // No global is ever allowed as a base. 1058 if (AM.BaseGV) 1059 return false; 1060 1061 // Require a 12-bit signed offset. 1062 if (!isInt<12>(AM.BaseOffs)) 1063 return false; 1064 1065 switch (AM.Scale) { 1066 case 0: // "r+i" or just "i", depending on HasBaseReg. 1067 break; 1068 case 1: 1069 if (!AM.HasBaseReg) // allow "r+i". 1070 break; 1071 return false; // disallow "r+r" or "r+r+i". 1072 default: 1073 return false; 1074 } 1075 1076 return true; 1077 } 1078 1079 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1080 return isInt<12>(Imm); 1081 } 1082 1083 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1084 return isInt<12>(Imm); 1085 } 1086 1087 // On RV32, 64-bit integers are split into their high and low parts and held 1088 // in two different registers, so the trunc is free since the low register can 1089 // just be used. 1090 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1091 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1092 return false; 1093 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1094 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1095 return (SrcBits == 64 && DestBits == 32); 1096 } 1097 1098 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1099 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1100 !SrcVT.isInteger() || !DstVT.isInteger()) 1101 return false; 1102 unsigned SrcBits = SrcVT.getSizeInBits(); 1103 unsigned DestBits = DstVT.getSizeInBits(); 1104 return (SrcBits == 64 && DestBits == 32); 1105 } 1106 1107 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1108 // Zexts are free if they can be combined with a load. 1109 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1110 EVT MemVT = LD->getMemoryVT(); 1111 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1112 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1113 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1114 LD->getExtensionType() == ISD::ZEXTLOAD)) 1115 return true; 1116 } 1117 1118 return TargetLowering::isZExtFree(Val, VT2); 1119 } 1120 1121 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1122 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1123 } 1124 1125 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1126 return Subtarget.hasStdExtZbb(); 1127 } 1128 1129 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1130 return Subtarget.hasStdExtZbb(); 1131 } 1132 1133 bool RISCVTargetLowering::hasAndNot(SDValue Y) const { 1134 EVT VT = Y.getValueType(); 1135 1136 // FIXME: Support vectors once we have tests. 1137 if (VT.isVector()) 1138 return false; 1139 1140 return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y); 1141 } 1142 1143 /// Check if sinking \p I's operands to I's basic block is profitable, because 1144 /// the operands can be folded into a target instruction, e.g. 1145 /// splats of scalars can fold into vector instructions. 1146 bool RISCVTargetLowering::shouldSinkOperands( 1147 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1148 using namespace llvm::PatternMatch; 1149 1150 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1151 return false; 1152 1153 auto IsSinker = [&](Instruction *I, int Operand) { 1154 switch (I->getOpcode()) { 1155 case Instruction::Add: 1156 case Instruction::Sub: 1157 case Instruction::Mul: 1158 case Instruction::And: 1159 case Instruction::Or: 1160 case Instruction::Xor: 1161 case Instruction::FAdd: 1162 case Instruction::FSub: 1163 case Instruction::FMul: 1164 case Instruction::FDiv: 1165 case Instruction::ICmp: 1166 case Instruction::FCmp: 1167 return true; 1168 case Instruction::Shl: 1169 case Instruction::LShr: 1170 case Instruction::AShr: 1171 return Operand == 1; 1172 case Instruction::Call: 1173 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1174 switch (II->getIntrinsicID()) { 1175 case Intrinsic::fma: 1176 return Operand == 0 || Operand == 1; 1177 default: 1178 return false; 1179 } 1180 } 1181 return false; 1182 default: 1183 return false; 1184 } 1185 }; 1186 1187 for (auto OpIdx : enumerate(I->operands())) { 1188 if (!IsSinker(I, OpIdx.index())) 1189 continue; 1190 1191 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1192 // Make sure we are not already sinking this operand 1193 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1194 continue; 1195 1196 // We are looking for a splat that can be sunk. 1197 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1198 m_Undef(), m_ZeroMask()))) 1199 continue; 1200 1201 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1202 // and vector registers 1203 for (Use &U : Op->uses()) { 1204 Instruction *Insn = cast<Instruction>(U.getUser()); 1205 if (!IsSinker(Insn, U.getOperandNo())) 1206 return false; 1207 } 1208 1209 Ops.push_back(&Op->getOperandUse(0)); 1210 Ops.push_back(&OpIdx.value()); 1211 } 1212 return true; 1213 } 1214 1215 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1216 bool ForCodeSize) const { 1217 if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin()) 1218 return false; 1219 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1220 return false; 1221 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1222 return false; 1223 if (Imm.isNegZero()) 1224 return false; 1225 return Imm.isZero(); 1226 } 1227 1228 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1229 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1230 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1231 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1232 } 1233 1234 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1235 CallingConv::ID CC, 1236 EVT VT) const { 1237 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1238 // We might still end up using a GPR but that will be decided based on ABI. 1239 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1240 return MVT::f32; 1241 1242 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1243 } 1244 1245 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1246 CallingConv::ID CC, 1247 EVT VT) const { 1248 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1249 // We might still end up using a GPR but that will be decided based on ABI. 1250 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1251 return 1; 1252 1253 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1254 } 1255 1256 // Changes the condition code and swaps operands if necessary, so the SetCC 1257 // operation matches one of the comparisons supported directly by branches 1258 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1259 // with 1/-1. 1260 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1261 ISD::CondCode &CC, SelectionDAG &DAG) { 1262 // Convert X > -1 to X >= 0. 1263 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1264 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1265 CC = ISD::SETGE; 1266 return; 1267 } 1268 // Convert X < 1 to 0 >= X. 1269 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1270 RHS = LHS; 1271 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1272 CC = ISD::SETGE; 1273 return; 1274 } 1275 1276 switch (CC) { 1277 default: 1278 break; 1279 case ISD::SETGT: 1280 case ISD::SETLE: 1281 case ISD::SETUGT: 1282 case ISD::SETULE: 1283 CC = ISD::getSetCCSwappedOperands(CC); 1284 std::swap(LHS, RHS); 1285 break; 1286 } 1287 } 1288 1289 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1290 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1291 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1292 if (VT.getVectorElementType() == MVT::i1) 1293 KnownSize *= 8; 1294 1295 switch (KnownSize) { 1296 default: 1297 llvm_unreachable("Invalid LMUL."); 1298 case 8: 1299 return RISCVII::VLMUL::LMUL_F8; 1300 case 16: 1301 return RISCVII::VLMUL::LMUL_F4; 1302 case 32: 1303 return RISCVII::VLMUL::LMUL_F2; 1304 case 64: 1305 return RISCVII::VLMUL::LMUL_1; 1306 case 128: 1307 return RISCVII::VLMUL::LMUL_2; 1308 case 256: 1309 return RISCVII::VLMUL::LMUL_4; 1310 case 512: 1311 return RISCVII::VLMUL::LMUL_8; 1312 } 1313 } 1314 1315 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1316 switch (LMul) { 1317 default: 1318 llvm_unreachable("Invalid LMUL."); 1319 case RISCVII::VLMUL::LMUL_F8: 1320 case RISCVII::VLMUL::LMUL_F4: 1321 case RISCVII::VLMUL::LMUL_F2: 1322 case RISCVII::VLMUL::LMUL_1: 1323 return RISCV::VRRegClassID; 1324 case RISCVII::VLMUL::LMUL_2: 1325 return RISCV::VRM2RegClassID; 1326 case RISCVII::VLMUL::LMUL_4: 1327 return RISCV::VRM4RegClassID; 1328 case RISCVII::VLMUL::LMUL_8: 1329 return RISCV::VRM8RegClassID; 1330 } 1331 } 1332 1333 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1334 RISCVII::VLMUL LMUL = getLMUL(VT); 1335 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1336 LMUL == RISCVII::VLMUL::LMUL_F4 || 1337 LMUL == RISCVII::VLMUL::LMUL_F2 || 1338 LMUL == RISCVII::VLMUL::LMUL_1) { 1339 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1340 "Unexpected subreg numbering"); 1341 return RISCV::sub_vrm1_0 + Index; 1342 } 1343 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1344 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1345 "Unexpected subreg numbering"); 1346 return RISCV::sub_vrm2_0 + Index; 1347 } 1348 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1349 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1350 "Unexpected subreg numbering"); 1351 return RISCV::sub_vrm4_0 + Index; 1352 } 1353 llvm_unreachable("Invalid vector type."); 1354 } 1355 1356 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1357 if (VT.getVectorElementType() == MVT::i1) 1358 return RISCV::VRRegClassID; 1359 return getRegClassIDForLMUL(getLMUL(VT)); 1360 } 1361 1362 // Attempt to decompose a subvector insert/extract between VecVT and 1363 // SubVecVT via subregister indices. Returns the subregister index that 1364 // can perform the subvector insert/extract with the given element index, as 1365 // well as the index corresponding to any leftover subvectors that must be 1366 // further inserted/extracted within the register class for SubVecVT. 1367 std::pair<unsigned, unsigned> 1368 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1369 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1370 const RISCVRegisterInfo *TRI) { 1371 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1372 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1373 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1374 "Register classes not ordered"); 1375 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1376 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1377 // Try to compose a subregister index that takes us from the incoming 1378 // LMUL>1 register class down to the outgoing one. At each step we half 1379 // the LMUL: 1380 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1381 // Note that this is not guaranteed to find a subregister index, such as 1382 // when we are extracting from one VR type to another. 1383 unsigned SubRegIdx = RISCV::NoSubRegister; 1384 for (const unsigned RCID : 1385 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1386 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1387 VecVT = VecVT.getHalfNumVectorElementsVT(); 1388 bool IsHi = 1389 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1390 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1391 getSubregIndexByMVT(VecVT, IsHi)); 1392 if (IsHi) 1393 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1394 } 1395 return {SubRegIdx, InsertExtractIdx}; 1396 } 1397 1398 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1399 // stores for those types. 1400 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1401 return !Subtarget.useRVVForFixedLengthVectors() || 1402 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1403 } 1404 1405 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1406 if (ScalarTy->isPointerTy()) 1407 return true; 1408 1409 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1410 ScalarTy->isIntegerTy(32)) 1411 return true; 1412 1413 if (ScalarTy->isIntegerTy(64)) 1414 return Subtarget.hasVInstructionsI64(); 1415 1416 if (ScalarTy->isHalfTy()) 1417 return Subtarget.hasVInstructionsF16(); 1418 if (ScalarTy->isFloatTy()) 1419 return Subtarget.hasVInstructionsF32(); 1420 if (ScalarTy->isDoubleTy()) 1421 return Subtarget.hasVInstructionsF64(); 1422 1423 return false; 1424 } 1425 1426 static bool useRVVForFixedLengthVectorVT(MVT VT, 1427 const RISCVSubtarget &Subtarget) { 1428 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1429 if (!Subtarget.useRVVForFixedLengthVectors()) 1430 return false; 1431 1432 // We only support a set of vector types with a consistent maximum fixed size 1433 // across all supported vector element types to avoid legalization issues. 1434 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1435 // fixed-length vector type we support is 1024 bytes. 1436 if (VT.getFixedSizeInBits() > 1024 * 8) 1437 return false; 1438 1439 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1440 1441 MVT EltVT = VT.getVectorElementType(); 1442 1443 // Don't use RVV for vectors we cannot scalarize if required. 1444 switch (EltVT.SimpleTy) { 1445 // i1 is supported but has different rules. 1446 default: 1447 return false; 1448 case MVT::i1: 1449 // Masks can only use a single register. 1450 if (VT.getVectorNumElements() > MinVLen) 1451 return false; 1452 MinVLen /= 8; 1453 break; 1454 case MVT::i8: 1455 case MVT::i16: 1456 case MVT::i32: 1457 break; 1458 case MVT::i64: 1459 if (!Subtarget.hasVInstructionsI64()) 1460 return false; 1461 break; 1462 case MVT::f16: 1463 if (!Subtarget.hasVInstructionsF16()) 1464 return false; 1465 break; 1466 case MVT::f32: 1467 if (!Subtarget.hasVInstructionsF32()) 1468 return false; 1469 break; 1470 case MVT::f64: 1471 if (!Subtarget.hasVInstructionsF64()) 1472 return false; 1473 break; 1474 } 1475 1476 // Reject elements larger than ELEN. 1477 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1478 return false; 1479 1480 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1481 // Don't use RVV for types that don't fit. 1482 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1483 return false; 1484 1485 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1486 // the base fixed length RVV support in place. 1487 if (!VT.isPow2VectorType()) 1488 return false; 1489 1490 return true; 1491 } 1492 1493 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1494 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1495 } 1496 1497 // Return the largest legal scalable vector type that matches VT's element type. 1498 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1499 const RISCVSubtarget &Subtarget) { 1500 // This may be called before legal types are setup. 1501 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1502 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1503 "Expected legal fixed length vector!"); 1504 1505 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1506 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1507 1508 MVT EltVT = VT.getVectorElementType(); 1509 switch (EltVT.SimpleTy) { 1510 default: 1511 llvm_unreachable("unexpected element type for RVV container"); 1512 case MVT::i1: 1513 case MVT::i8: 1514 case MVT::i16: 1515 case MVT::i32: 1516 case MVT::i64: 1517 case MVT::f16: 1518 case MVT::f32: 1519 case MVT::f64: { 1520 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1521 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1522 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1523 unsigned NumElts = 1524 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1525 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1526 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1527 return MVT::getScalableVectorVT(EltVT, NumElts); 1528 } 1529 } 1530 } 1531 1532 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1533 const RISCVSubtarget &Subtarget) { 1534 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1535 Subtarget); 1536 } 1537 1538 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1539 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1540 } 1541 1542 // Grow V to consume an entire RVV register. 1543 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1544 const RISCVSubtarget &Subtarget) { 1545 assert(VT.isScalableVector() && 1546 "Expected to convert into a scalable vector!"); 1547 assert(V.getValueType().isFixedLengthVector() && 1548 "Expected a fixed length vector operand!"); 1549 SDLoc DL(V); 1550 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1551 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1552 } 1553 1554 // Shrink V so it's just big enough to maintain a VT's worth of data. 1555 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1556 const RISCVSubtarget &Subtarget) { 1557 assert(VT.isFixedLengthVector() && 1558 "Expected to convert into a fixed length vector!"); 1559 assert(V.getValueType().isScalableVector() && 1560 "Expected a scalable vector operand!"); 1561 SDLoc DL(V); 1562 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1563 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1564 } 1565 1566 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1567 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1568 // the vector type that it is contained in. 1569 static std::pair<SDValue, SDValue> 1570 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1571 const RISCVSubtarget &Subtarget) { 1572 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1573 MVT XLenVT = Subtarget.getXLenVT(); 1574 SDValue VL = VecVT.isFixedLengthVector() 1575 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1576 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1577 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1578 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1579 return {Mask, VL}; 1580 } 1581 1582 // As above but assuming the given type is a scalable vector type. 1583 static std::pair<SDValue, SDValue> 1584 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1585 const RISCVSubtarget &Subtarget) { 1586 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1587 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1588 } 1589 1590 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1591 // of either is (currently) supported. This can get us into an infinite loop 1592 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1593 // as a ..., etc. 1594 // Until either (or both) of these can reliably lower any node, reporting that 1595 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1596 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1597 // which is not desirable. 1598 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1599 EVT VT, unsigned DefinedValues) const { 1600 return false; 1601 } 1602 1603 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1604 // Only splats are currently supported. 1605 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1606 return true; 1607 1608 return false; 1609 } 1610 1611 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1612 // RISCV FP-to-int conversions saturate to the destination register size, but 1613 // don't produce 0 for nan. We can use a conversion instruction and fix the 1614 // nan case with a compare and a select. 1615 SDValue Src = Op.getOperand(0); 1616 1617 EVT DstVT = Op.getValueType(); 1618 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1619 1620 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1621 unsigned Opc; 1622 if (SatVT == DstVT) 1623 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1624 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1625 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1626 else 1627 return SDValue(); 1628 // FIXME: Support other SatVTs by clamping before or after the conversion. 1629 1630 SDLoc DL(Op); 1631 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1632 1633 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1634 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1635 } 1636 1637 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1638 const RISCVSubtarget &Subtarget) { 1639 MVT VT = Op.getSimpleValueType(); 1640 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1641 1642 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1643 1644 SDLoc DL(Op); 1645 SDValue Mask, VL; 1646 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1647 1648 unsigned Opc = 1649 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1650 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1651 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1652 } 1653 1654 struct VIDSequence { 1655 int64_t StepNumerator; 1656 unsigned StepDenominator; 1657 int64_t Addend; 1658 }; 1659 1660 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1661 // to the (non-zero) step S and start value X. This can be then lowered as the 1662 // RVV sequence (VID * S) + X, for example. 1663 // The step S is represented as an integer numerator divided by a positive 1664 // denominator. Note that the implementation currently only identifies 1665 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1666 // cannot detect 2/3, for example. 1667 // Note that this method will also match potentially unappealing index 1668 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1669 // determine whether this is worth generating code for. 1670 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1671 unsigned NumElts = Op.getNumOperands(); 1672 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1673 if (!Op.getValueType().isInteger()) 1674 return None; 1675 1676 Optional<unsigned> SeqStepDenom; 1677 Optional<int64_t> SeqStepNum, SeqAddend; 1678 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1679 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1680 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1681 // Assume undef elements match the sequence; we just have to be careful 1682 // when interpolating across them. 1683 if (Op.getOperand(Idx).isUndef()) 1684 continue; 1685 // The BUILD_VECTOR must be all constants. 1686 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1687 return None; 1688 1689 uint64_t Val = Op.getConstantOperandVal(Idx) & 1690 maskTrailingOnes<uint64_t>(EltSizeInBits); 1691 1692 if (PrevElt) { 1693 // Calculate the step since the last non-undef element, and ensure 1694 // it's consistent across the entire sequence. 1695 unsigned IdxDiff = Idx - PrevElt->second; 1696 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1697 1698 // A zero-value value difference means that we're somewhere in the middle 1699 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1700 // step change before evaluating the sequence. 1701 if (ValDiff != 0) { 1702 int64_t Remainder = ValDiff % IdxDiff; 1703 // Normalize the step if it's greater than 1. 1704 if (Remainder != ValDiff) { 1705 // The difference must cleanly divide the element span. 1706 if (Remainder != 0) 1707 return None; 1708 ValDiff /= IdxDiff; 1709 IdxDiff = 1; 1710 } 1711 1712 if (!SeqStepNum) 1713 SeqStepNum = ValDiff; 1714 else if (ValDiff != SeqStepNum) 1715 return None; 1716 1717 if (!SeqStepDenom) 1718 SeqStepDenom = IdxDiff; 1719 else if (IdxDiff != *SeqStepDenom) 1720 return None; 1721 } 1722 } 1723 1724 // Record and/or check any addend. 1725 if (SeqStepNum && SeqStepDenom) { 1726 uint64_t ExpectedVal = 1727 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1728 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1729 if (!SeqAddend) 1730 SeqAddend = Addend; 1731 else if (SeqAddend != Addend) 1732 return None; 1733 } 1734 1735 // Record this non-undef element for later. 1736 if (!PrevElt || PrevElt->first != Val) 1737 PrevElt = std::make_pair(Val, Idx); 1738 } 1739 // We need to have logged both a step and an addend for this to count as 1740 // a legal index sequence. 1741 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1742 return None; 1743 1744 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1745 } 1746 1747 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1748 const RISCVSubtarget &Subtarget) { 1749 MVT VT = Op.getSimpleValueType(); 1750 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1751 1752 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1753 1754 SDLoc DL(Op); 1755 SDValue Mask, VL; 1756 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1757 1758 MVT XLenVT = Subtarget.getXLenVT(); 1759 unsigned NumElts = Op.getNumOperands(); 1760 1761 if (VT.getVectorElementType() == MVT::i1) { 1762 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1763 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1764 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1765 } 1766 1767 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1768 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1769 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1770 } 1771 1772 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1773 // scalar integer chunks whose bit-width depends on the number of mask 1774 // bits and XLEN. 1775 // First, determine the most appropriate scalar integer type to use. This 1776 // is at most XLenVT, but may be shrunk to a smaller vector element type 1777 // according to the size of the final vector - use i8 chunks rather than 1778 // XLenVT if we're producing a v8i1. This results in more consistent 1779 // codegen across RV32 and RV64. 1780 unsigned NumViaIntegerBits = 1781 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1782 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1783 // If we have to use more than one INSERT_VECTOR_ELT then this 1784 // optimization is likely to increase code size; avoid peforming it in 1785 // such a case. We can use a load from a constant pool in this case. 1786 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1787 return SDValue(); 1788 // Now we can create our integer vector type. Note that it may be larger 1789 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1790 MVT IntegerViaVecVT = 1791 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1792 divideCeil(NumElts, NumViaIntegerBits)); 1793 1794 uint64_t Bits = 0; 1795 unsigned BitPos = 0, IntegerEltIdx = 0; 1796 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1797 1798 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1799 // Once we accumulate enough bits to fill our scalar type, insert into 1800 // our vector and clear our accumulated data. 1801 if (I != 0 && I % NumViaIntegerBits == 0) { 1802 if (NumViaIntegerBits <= 32) 1803 Bits = SignExtend64(Bits, 32); 1804 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1805 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1806 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1807 Bits = 0; 1808 BitPos = 0; 1809 IntegerEltIdx++; 1810 } 1811 SDValue V = Op.getOperand(I); 1812 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1813 Bits |= ((uint64_t)BitValue << BitPos); 1814 } 1815 1816 // Insert the (remaining) scalar value into position in our integer 1817 // vector type. 1818 if (NumViaIntegerBits <= 32) 1819 Bits = SignExtend64(Bits, 32); 1820 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1821 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1822 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1823 1824 if (NumElts < NumViaIntegerBits) { 1825 // If we're producing a smaller vector than our minimum legal integer 1826 // type, bitcast to the equivalent (known-legal) mask type, and extract 1827 // our final mask. 1828 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1829 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1830 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1831 DAG.getConstant(0, DL, XLenVT)); 1832 } else { 1833 // Else we must have produced an integer type with the same size as the 1834 // mask type; bitcast for the final result. 1835 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1836 Vec = DAG.getBitcast(VT, Vec); 1837 } 1838 1839 return Vec; 1840 } 1841 1842 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1843 // vector type, we have a legal equivalently-sized i8 type, so we can use 1844 // that. 1845 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1846 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1847 1848 SDValue WideVec; 1849 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1850 // For a splat, perform a scalar truncate before creating the wider 1851 // vector. 1852 assert(Splat.getValueType() == XLenVT && 1853 "Unexpected type for i1 splat value"); 1854 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1855 DAG.getConstant(1, DL, XLenVT)); 1856 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1857 } else { 1858 SmallVector<SDValue, 8> Ops(Op->op_values()); 1859 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1860 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1861 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1862 } 1863 1864 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1865 } 1866 1867 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1868 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1869 : RISCVISD::VMV_V_X_VL; 1870 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1871 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1872 } 1873 1874 // Try and match index sequences, which we can lower to the vid instruction 1875 // with optional modifications. An all-undef vector is matched by 1876 // getSplatValue, above. 1877 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1878 int64_t StepNumerator = SimpleVID->StepNumerator; 1879 unsigned StepDenominator = SimpleVID->StepDenominator; 1880 int64_t Addend = SimpleVID->Addend; 1881 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 1882 // threshold since it's the immediate value many RVV instructions accept. 1883 if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) && 1884 isInt<5>(Addend)) { 1885 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1886 // Convert right out of the scalable type so we can use standard ISD 1887 // nodes for the rest of the computation. If we used scalable types with 1888 // these, we'd lose the fixed-length vector info and generate worse 1889 // vsetvli code. 1890 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 1891 assert(StepNumerator != 0 && "Invalid step"); 1892 bool Negate = false; 1893 if (StepNumerator != 1) { 1894 int64_t SplatStepVal = StepNumerator; 1895 unsigned Opcode = ISD::MUL; 1896 if (isPowerOf2_64(std::abs(StepNumerator))) { 1897 Negate = StepNumerator < 0; 1898 Opcode = ISD::SHL; 1899 SplatStepVal = Log2_64(std::abs(StepNumerator)); 1900 } 1901 SDValue SplatStep = DAG.getSplatVector( 1902 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 1903 VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep); 1904 } 1905 if (StepDenominator != 1) { 1906 SDValue SplatStep = DAG.getSplatVector( 1907 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 1908 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 1909 } 1910 if (Addend != 0 || Negate) { 1911 SDValue SplatAddend = 1912 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 1913 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 1914 } 1915 return VID; 1916 } 1917 } 1918 1919 // Attempt to detect "hidden" splats, which only reveal themselves as splats 1920 // when re-interpreted as a vector with a larger element type. For example, 1921 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 1922 // could be instead splat as 1923 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 1924 // TODO: This optimization could also work on non-constant splats, but it 1925 // would require bit-manipulation instructions to construct the splat value. 1926 SmallVector<SDValue> Sequence; 1927 unsigned EltBitSize = VT.getScalarSizeInBits(); 1928 const auto *BV = cast<BuildVectorSDNode>(Op); 1929 if (VT.isInteger() && EltBitSize < 64 && 1930 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1931 BV->getRepeatedSequence(Sequence) && 1932 (Sequence.size() * EltBitSize) <= 64) { 1933 unsigned SeqLen = Sequence.size(); 1934 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 1935 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 1936 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 1937 ViaIntVT == MVT::i64) && 1938 "Unexpected sequence type"); 1939 1940 unsigned EltIdx = 0; 1941 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 1942 uint64_t SplatValue = 0; 1943 // Construct the amalgamated value which can be splatted as this larger 1944 // vector type. 1945 for (const auto &SeqV : Sequence) { 1946 if (!SeqV.isUndef()) 1947 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 1948 << (EltIdx * EltBitSize)); 1949 EltIdx++; 1950 } 1951 1952 // On RV64, sign-extend from 32 to 64 bits where possible in order to 1953 // achieve better constant materializion. 1954 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 1955 SplatValue = SignExtend64(SplatValue, 32); 1956 1957 // Since we can't introduce illegal i64 types at this stage, we can only 1958 // perform an i64 splat on RV32 if it is its own sign-extended value. That 1959 // way we can use RVV instructions to splat. 1960 assert((ViaIntVT.bitsLE(XLenVT) || 1961 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 1962 "Unexpected bitcast sequence"); 1963 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 1964 SDValue ViaVL = 1965 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 1966 MVT ViaContainerVT = 1967 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 1968 SDValue Splat = 1969 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 1970 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 1971 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 1972 return DAG.getBitcast(VT, Splat); 1973 } 1974 } 1975 1976 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1977 // which constitute a large proportion of the elements. In such cases we can 1978 // splat a vector with the dominant element and make up the shortfall with 1979 // INSERT_VECTOR_ELTs. 1980 // Note that this includes vectors of 2 elements by association. The 1981 // upper-most element is the "dominant" one, allowing us to use a splat to 1982 // "insert" the upper element, and an insert of the lower element at position 1983 // 0, which improves codegen. 1984 SDValue DominantValue; 1985 unsigned MostCommonCount = 0; 1986 DenseMap<SDValue, unsigned> ValueCounts; 1987 unsigned NumUndefElts = 1988 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1989 1990 // Track the number of scalar loads we know we'd be inserting, estimated as 1991 // any non-zero floating-point constant. Other kinds of element are either 1992 // already in registers or are materialized on demand. The threshold at which 1993 // a vector load is more desirable than several scalar materializion and 1994 // vector-insertion instructions is not known. 1995 unsigned NumScalarLoads = 0; 1996 1997 for (SDValue V : Op->op_values()) { 1998 if (V.isUndef()) 1999 continue; 2000 2001 ValueCounts.insert(std::make_pair(V, 0)); 2002 unsigned &Count = ValueCounts[V]; 2003 2004 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2005 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2006 2007 // Is this value dominant? In case of a tie, prefer the highest element as 2008 // it's cheaper to insert near the beginning of a vector than it is at the 2009 // end. 2010 if (++Count >= MostCommonCount) { 2011 DominantValue = V; 2012 MostCommonCount = Count; 2013 } 2014 } 2015 2016 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2017 unsigned NumDefElts = NumElts - NumUndefElts; 2018 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2019 2020 // Don't perform this optimization when optimizing for size, since 2021 // materializing elements and inserting them tends to cause code bloat. 2022 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2023 ((MostCommonCount > DominantValueCountThreshold) || 2024 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2025 // Start by splatting the most common element. 2026 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2027 2028 DenseSet<SDValue> Processed{DominantValue}; 2029 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2030 for (const auto &OpIdx : enumerate(Op->ops())) { 2031 const SDValue &V = OpIdx.value(); 2032 if (V.isUndef() || !Processed.insert(V).second) 2033 continue; 2034 if (ValueCounts[V] == 1) { 2035 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2036 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2037 } else { 2038 // Blend in all instances of this value using a VSELECT, using a 2039 // mask where each bit signals whether that element is the one 2040 // we're after. 2041 SmallVector<SDValue> Ops; 2042 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2043 return DAG.getConstant(V == V1, DL, XLenVT); 2044 }); 2045 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2046 DAG.getBuildVector(SelMaskTy, DL, Ops), 2047 DAG.getSplatBuildVector(VT, DL, V), Vec); 2048 } 2049 } 2050 2051 return Vec; 2052 } 2053 2054 return SDValue(); 2055 } 2056 2057 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2058 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2059 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2060 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2061 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2062 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2063 // node in order to try and match RVV vector/scalar instructions. 2064 if ((LoC >> 31) == HiC) 2065 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2066 } 2067 2068 // Fall back to a stack store and stride x0 vector load. 2069 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2070 } 2071 2072 // Called by type legalization to handle splat of i64 on RV32. 2073 // FIXME: We can optimize this when the type has sign or zero bits in one 2074 // of the halves. 2075 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2076 SDValue VL, SelectionDAG &DAG) { 2077 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2078 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2079 DAG.getConstant(0, DL, MVT::i32)); 2080 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2081 DAG.getConstant(1, DL, MVT::i32)); 2082 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2083 } 2084 2085 // This function lowers a splat of a scalar operand Splat with the vector 2086 // length VL. It ensures the final sequence is type legal, which is useful when 2087 // lowering a splat after type legalization. 2088 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2089 SelectionDAG &DAG, 2090 const RISCVSubtarget &Subtarget) { 2091 if (VT.isFloatingPoint()) 2092 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2093 2094 MVT XLenVT = Subtarget.getXLenVT(); 2095 2096 // Simplest case is that the operand needs to be promoted to XLenVT. 2097 if (Scalar.getValueType().bitsLE(XLenVT)) { 2098 // If the operand is a constant, sign extend to increase our chances 2099 // of being able to use a .vi instruction. ANY_EXTEND would become a 2100 // a zero extend and the simm5 check in isel would fail. 2101 // FIXME: Should we ignore the upper bits in isel instead? 2102 unsigned ExtOpc = 2103 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2104 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2105 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2106 } 2107 2108 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2109 "Unexpected scalar for splat lowering!"); 2110 2111 // Otherwise use the more complicated splatting algorithm. 2112 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2113 } 2114 2115 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2116 const RISCVSubtarget &Subtarget) { 2117 SDValue V1 = Op.getOperand(0); 2118 SDValue V2 = Op.getOperand(1); 2119 SDLoc DL(Op); 2120 MVT XLenVT = Subtarget.getXLenVT(); 2121 MVT VT = Op.getSimpleValueType(); 2122 unsigned NumElts = VT.getVectorNumElements(); 2123 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2124 2125 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2126 2127 SDValue TrueMask, VL; 2128 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2129 2130 if (SVN->isSplat()) { 2131 const int Lane = SVN->getSplatIndex(); 2132 if (Lane >= 0) { 2133 MVT SVT = VT.getVectorElementType(); 2134 2135 // Turn splatted vector load into a strided load with an X0 stride. 2136 SDValue V = V1; 2137 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2138 // with undef. 2139 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2140 int Offset = Lane; 2141 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2142 int OpElements = 2143 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2144 V = V.getOperand(Offset / OpElements); 2145 Offset %= OpElements; 2146 } 2147 2148 // We need to ensure the load isn't atomic or volatile. 2149 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2150 auto *Ld = cast<LoadSDNode>(V); 2151 Offset *= SVT.getStoreSize(); 2152 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2153 TypeSize::Fixed(Offset), DL); 2154 2155 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2156 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2157 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2158 SDValue IntID = 2159 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2160 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2161 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2162 SDValue NewLoad = DAG.getMemIntrinsicNode( 2163 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2164 DAG.getMachineFunction().getMachineMemOperand( 2165 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2166 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2167 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2168 } 2169 2170 // Otherwise use a scalar load and splat. This will give the best 2171 // opportunity to fold a splat into the operation. ISel can turn it into 2172 // the x0 strided load if we aren't able to fold away the select. 2173 if (SVT.isFloatingPoint()) 2174 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2175 Ld->getPointerInfo().getWithOffset(Offset), 2176 Ld->getOriginalAlign(), 2177 Ld->getMemOperand()->getFlags()); 2178 else 2179 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2180 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2181 Ld->getOriginalAlign(), 2182 Ld->getMemOperand()->getFlags()); 2183 DAG.makeEquivalentMemoryOrdering(Ld, V); 2184 2185 unsigned Opc = 2186 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2187 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2188 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2189 } 2190 2191 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2192 assert(Lane < (int)NumElts && "Unexpected lane!"); 2193 SDValue Gather = 2194 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2195 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2196 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2197 } 2198 } 2199 2200 // Detect shuffles which can be re-expressed as vector selects; these are 2201 // shuffles in which each element in the destination is taken from an element 2202 // at the corresponding index in either source vectors. 2203 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2204 int MaskIndex = MaskIdx.value(); 2205 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2206 }); 2207 2208 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2209 2210 SmallVector<SDValue> MaskVals; 2211 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2212 // merged with a second vrgather. 2213 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2214 2215 // By default we preserve the original operand order, and use a mask to 2216 // select LHS as true and RHS as false. However, since RVV vector selects may 2217 // feature splats but only on the LHS, we may choose to invert our mask and 2218 // instead select between RHS and LHS. 2219 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2220 bool InvertMask = IsSelect == SwapOps; 2221 2222 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2223 // half. 2224 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2225 2226 // Now construct the mask that will be used by the vselect or blended 2227 // vrgather operation. For vrgathers, construct the appropriate indices into 2228 // each vector. 2229 for (int MaskIndex : SVN->getMask()) { 2230 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2231 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2232 if (!IsSelect) { 2233 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2234 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2235 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2236 : DAG.getUNDEF(XLenVT)); 2237 GatherIndicesRHS.push_back( 2238 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2239 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2240 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2241 ++LHSIndexCounts[MaskIndex]; 2242 if (!IsLHSOrUndefIndex) 2243 ++RHSIndexCounts[MaskIndex - NumElts]; 2244 } 2245 } 2246 2247 if (SwapOps) { 2248 std::swap(V1, V2); 2249 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2250 } 2251 2252 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2253 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2254 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2255 2256 if (IsSelect) 2257 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2258 2259 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2260 // On such a large vector we're unable to use i8 as the index type. 2261 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2262 // may involve vector splitting if we're already at LMUL=8, or our 2263 // user-supplied maximum fixed-length LMUL. 2264 return SDValue(); 2265 } 2266 2267 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2268 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2269 MVT IndexVT = VT.changeTypeToInteger(); 2270 // Since we can't introduce illegal index types at this stage, use i16 and 2271 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2272 // than XLenVT. 2273 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2274 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2275 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2276 } 2277 2278 MVT IndexContainerVT = 2279 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2280 2281 SDValue Gather; 2282 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2283 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2284 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2285 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2286 } else { 2287 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2288 // If only one index is used, we can use a "splat" vrgather. 2289 // TODO: We can splat the most-common index and fix-up any stragglers, if 2290 // that's beneficial. 2291 if (LHSIndexCounts.size() == 1) { 2292 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2293 Gather = 2294 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2295 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2296 } else { 2297 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2298 LHSIndices = 2299 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2300 2301 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2302 TrueMask, VL); 2303 } 2304 } 2305 2306 // If a second vector operand is used by this shuffle, blend it in with an 2307 // additional vrgather. 2308 if (!V2.isUndef()) { 2309 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2310 // If only one index is used, we can use a "splat" vrgather. 2311 // TODO: We can splat the most-common index and fix-up any stragglers, if 2312 // that's beneficial. 2313 if (RHSIndexCounts.size() == 1) { 2314 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2315 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2316 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2317 } else { 2318 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2319 RHSIndices = 2320 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2321 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2322 VL); 2323 } 2324 2325 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2326 SelectMask = 2327 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2328 2329 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2330 Gather, VL); 2331 } 2332 2333 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2334 } 2335 2336 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2337 SDLoc DL, SelectionDAG &DAG, 2338 const RISCVSubtarget &Subtarget) { 2339 if (VT.isScalableVector()) 2340 return DAG.getFPExtendOrRound(Op, DL, VT); 2341 assert(VT.isFixedLengthVector() && 2342 "Unexpected value type for RVV FP extend/round lowering"); 2343 SDValue Mask, VL; 2344 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2345 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2346 ? RISCVISD::FP_EXTEND_VL 2347 : RISCVISD::FP_ROUND_VL; 2348 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2349 } 2350 2351 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2352 // the exponent. 2353 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2354 MVT VT = Op.getSimpleValueType(); 2355 unsigned EltSize = VT.getScalarSizeInBits(); 2356 SDValue Src = Op.getOperand(0); 2357 SDLoc DL(Op); 2358 2359 // We need a FP type that can represent the value. 2360 // TODO: Use f16 for i8 when possible? 2361 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2362 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2363 2364 // Legal types should have been checked in the RISCVTargetLowering 2365 // constructor. 2366 // TODO: Splitting may make sense in some cases. 2367 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2368 "Expected legal float type!"); 2369 2370 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2371 // The trailing zero count is equal to log2 of this single bit value. 2372 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2373 SDValue Neg = 2374 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2375 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2376 } 2377 2378 // We have a legal FP type, convert to it. 2379 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2380 // Bitcast to integer and shift the exponent to the LSB. 2381 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2382 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2383 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2384 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2385 DAG.getConstant(ShiftAmt, DL, IntVT)); 2386 // Truncate back to original type to allow vnsrl. 2387 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2388 // The exponent contains log2 of the value in biased form. 2389 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2390 2391 // For trailing zeros, we just need to subtract the bias. 2392 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2393 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2394 DAG.getConstant(ExponentBias, DL, VT)); 2395 2396 // For leading zeros, we need to remove the bias and convert from log2 to 2397 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2398 unsigned Adjust = ExponentBias + (EltSize - 1); 2399 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2400 } 2401 2402 // While RVV has alignment restrictions, we should always be able to load as a 2403 // legal equivalently-sized byte-typed vector instead. This method is 2404 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2405 // the load is already correctly-aligned, it returns SDValue(). 2406 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2407 SelectionDAG &DAG) const { 2408 auto *Load = cast<LoadSDNode>(Op); 2409 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2410 2411 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2412 Load->getMemoryVT(), 2413 *Load->getMemOperand())) 2414 return SDValue(); 2415 2416 SDLoc DL(Op); 2417 MVT VT = Op.getSimpleValueType(); 2418 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2419 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2420 "Unexpected unaligned RVV load type"); 2421 MVT NewVT = 2422 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2423 assert(NewVT.isValid() && 2424 "Expecting equally-sized RVV vector types to be legal"); 2425 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2426 Load->getPointerInfo(), Load->getOriginalAlign(), 2427 Load->getMemOperand()->getFlags()); 2428 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2429 } 2430 2431 // While RVV has alignment restrictions, we should always be able to store as a 2432 // legal equivalently-sized byte-typed vector instead. This method is 2433 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2434 // returns SDValue() if the store is already correctly aligned. 2435 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2436 SelectionDAG &DAG) const { 2437 auto *Store = cast<StoreSDNode>(Op); 2438 assert(Store && Store->getValue().getValueType().isVector() && 2439 "Expected vector store"); 2440 2441 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2442 Store->getMemoryVT(), 2443 *Store->getMemOperand())) 2444 return SDValue(); 2445 2446 SDLoc DL(Op); 2447 SDValue StoredVal = Store->getValue(); 2448 MVT VT = StoredVal.getSimpleValueType(); 2449 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2450 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2451 "Unexpected unaligned RVV store type"); 2452 MVT NewVT = 2453 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2454 assert(NewVT.isValid() && 2455 "Expecting equally-sized RVV vector types to be legal"); 2456 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2457 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2458 Store->getPointerInfo(), Store->getOriginalAlign(), 2459 Store->getMemOperand()->getFlags()); 2460 } 2461 2462 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2463 SelectionDAG &DAG) const { 2464 switch (Op.getOpcode()) { 2465 default: 2466 report_fatal_error("unimplemented operand"); 2467 case ISD::GlobalAddress: 2468 return lowerGlobalAddress(Op, DAG); 2469 case ISD::BlockAddress: 2470 return lowerBlockAddress(Op, DAG); 2471 case ISD::ConstantPool: 2472 return lowerConstantPool(Op, DAG); 2473 case ISD::JumpTable: 2474 return lowerJumpTable(Op, DAG); 2475 case ISD::GlobalTLSAddress: 2476 return lowerGlobalTLSAddress(Op, DAG); 2477 case ISD::SELECT: 2478 return lowerSELECT(Op, DAG); 2479 case ISD::BRCOND: 2480 return lowerBRCOND(Op, DAG); 2481 case ISD::VASTART: 2482 return lowerVASTART(Op, DAG); 2483 case ISD::FRAMEADDR: 2484 return lowerFRAMEADDR(Op, DAG); 2485 case ISD::RETURNADDR: 2486 return lowerRETURNADDR(Op, DAG); 2487 case ISD::SHL_PARTS: 2488 return lowerShiftLeftParts(Op, DAG); 2489 case ISD::SRA_PARTS: 2490 return lowerShiftRightParts(Op, DAG, true); 2491 case ISD::SRL_PARTS: 2492 return lowerShiftRightParts(Op, DAG, false); 2493 case ISD::BITCAST: { 2494 SDLoc DL(Op); 2495 EVT VT = Op.getValueType(); 2496 SDValue Op0 = Op.getOperand(0); 2497 EVT Op0VT = Op0.getValueType(); 2498 MVT XLenVT = Subtarget.getXLenVT(); 2499 if (VT.isFixedLengthVector()) { 2500 // We can handle fixed length vector bitcasts with a simple replacement 2501 // in isel. 2502 if (Op0VT.isFixedLengthVector()) 2503 return Op; 2504 // When bitcasting from scalar to fixed-length vector, insert the scalar 2505 // into a one-element vector of the result type, and perform a vector 2506 // bitcast. 2507 if (!Op0VT.isVector()) { 2508 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2509 if (!isTypeLegal(BVT)) 2510 return SDValue(); 2511 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2512 DAG.getUNDEF(BVT), Op0, 2513 DAG.getConstant(0, DL, XLenVT))); 2514 } 2515 return SDValue(); 2516 } 2517 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2518 // thus: bitcast the vector to a one-element vector type whose element type 2519 // is the same as the result type, and extract the first element. 2520 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2521 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2522 if (!isTypeLegal(BVT)) 2523 return SDValue(); 2524 SDValue BVec = DAG.getBitcast(BVT, Op0); 2525 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2526 DAG.getConstant(0, DL, XLenVT)); 2527 } 2528 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2529 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2530 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2531 return FPConv; 2532 } 2533 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2534 Subtarget.hasStdExtF()) { 2535 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2536 SDValue FPConv = 2537 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2538 return FPConv; 2539 } 2540 return SDValue(); 2541 } 2542 case ISD::INTRINSIC_WO_CHAIN: 2543 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2544 case ISD::INTRINSIC_W_CHAIN: 2545 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2546 case ISD::INTRINSIC_VOID: 2547 return LowerINTRINSIC_VOID(Op, DAG); 2548 case ISD::BSWAP: 2549 case ISD::BITREVERSE: { 2550 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2551 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2552 MVT VT = Op.getSimpleValueType(); 2553 SDLoc DL(Op); 2554 // Start with the maximum immediate value which is the bitwidth - 1. 2555 unsigned Imm = VT.getSizeInBits() - 1; 2556 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2557 if (Op.getOpcode() == ISD::BSWAP) 2558 Imm &= ~0x7U; 2559 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2560 DAG.getConstant(Imm, DL, VT)); 2561 } 2562 case ISD::FSHL: 2563 case ISD::FSHR: { 2564 MVT VT = Op.getSimpleValueType(); 2565 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2566 SDLoc DL(Op); 2567 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2568 return Op; 2569 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2570 // use log(XLen) bits. Mask the shift amount accordingly. 2571 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2572 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2573 DAG.getConstant(ShAmtWidth, DL, VT)); 2574 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2575 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2576 } 2577 case ISD::TRUNCATE: { 2578 SDLoc DL(Op); 2579 MVT VT = Op.getSimpleValueType(); 2580 // Only custom-lower vector truncates 2581 if (!VT.isVector()) 2582 return Op; 2583 2584 // Truncates to mask types are handled differently 2585 if (VT.getVectorElementType() == MVT::i1) 2586 return lowerVectorMaskTrunc(Op, DAG); 2587 2588 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2589 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2590 // truncate by one power of two at a time. 2591 MVT DstEltVT = VT.getVectorElementType(); 2592 2593 SDValue Src = Op.getOperand(0); 2594 MVT SrcVT = Src.getSimpleValueType(); 2595 MVT SrcEltVT = SrcVT.getVectorElementType(); 2596 2597 assert(DstEltVT.bitsLT(SrcEltVT) && 2598 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2599 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2600 "Unexpected vector truncate lowering"); 2601 2602 MVT ContainerVT = SrcVT; 2603 if (SrcVT.isFixedLengthVector()) { 2604 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2605 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2606 } 2607 2608 SDValue Result = Src; 2609 SDValue Mask, VL; 2610 std::tie(Mask, VL) = 2611 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2612 LLVMContext &Context = *DAG.getContext(); 2613 const ElementCount Count = ContainerVT.getVectorElementCount(); 2614 do { 2615 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2616 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2617 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2618 Mask, VL); 2619 } while (SrcEltVT != DstEltVT); 2620 2621 if (SrcVT.isFixedLengthVector()) 2622 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2623 2624 return Result; 2625 } 2626 case ISD::ANY_EXTEND: 2627 case ISD::ZERO_EXTEND: 2628 if (Op.getOperand(0).getValueType().isVector() && 2629 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2630 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2631 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2632 case ISD::SIGN_EXTEND: 2633 if (Op.getOperand(0).getValueType().isVector() && 2634 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2635 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2636 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2637 case ISD::SPLAT_VECTOR_PARTS: 2638 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2639 case ISD::INSERT_VECTOR_ELT: 2640 return lowerINSERT_VECTOR_ELT(Op, DAG); 2641 case ISD::EXTRACT_VECTOR_ELT: 2642 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2643 case ISD::VSCALE: { 2644 MVT VT = Op.getSimpleValueType(); 2645 SDLoc DL(Op); 2646 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2647 // We define our scalable vector types for lmul=1 to use a 64 bit known 2648 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2649 // vscale as VLENB / 8. 2650 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2651 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2652 // We assume VLENB is a multiple of 8. We manually choose the best shift 2653 // here because SimplifyDemandedBits isn't always able to simplify it. 2654 uint64_t Val = Op.getConstantOperandVal(0); 2655 if (isPowerOf2_64(Val)) { 2656 uint64_t Log2 = Log2_64(Val); 2657 if (Log2 < 3) 2658 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2659 DAG.getConstant(3 - Log2, DL, VT)); 2660 if (Log2 > 3) 2661 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2662 DAG.getConstant(Log2 - 3, DL, VT)); 2663 return VLENB; 2664 } 2665 // If the multiplier is a multiple of 8, scale it down to avoid needing 2666 // to shift the VLENB value. 2667 if ((Val % 8) == 0) 2668 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2669 DAG.getConstant(Val / 8, DL, VT)); 2670 } 2671 2672 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2673 DAG.getConstant(3, DL, VT)); 2674 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2675 } 2676 case ISD::FP_EXTEND: { 2677 // RVV can only do fp_extend to types double the size as the source. We 2678 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2679 // via f32. 2680 SDLoc DL(Op); 2681 MVT VT = Op.getSimpleValueType(); 2682 SDValue Src = Op.getOperand(0); 2683 MVT SrcVT = Src.getSimpleValueType(); 2684 2685 // Prepare any fixed-length vector operands. 2686 MVT ContainerVT = VT; 2687 if (SrcVT.isFixedLengthVector()) { 2688 ContainerVT = getContainerForFixedLengthVector(VT); 2689 MVT SrcContainerVT = 2690 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2691 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2692 } 2693 2694 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2695 SrcVT.getVectorElementType() != MVT::f16) { 2696 // For scalable vectors, we only need to close the gap between 2697 // vXf16->vXf64. 2698 if (!VT.isFixedLengthVector()) 2699 return Op; 2700 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2701 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2702 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2703 } 2704 2705 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2706 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2707 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2708 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2709 2710 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2711 DL, DAG, Subtarget); 2712 if (VT.isFixedLengthVector()) 2713 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2714 return Extend; 2715 } 2716 case ISD::FP_ROUND: { 2717 // RVV can only do fp_round to types half the size as the source. We 2718 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2719 // conversion instruction. 2720 SDLoc DL(Op); 2721 MVT VT = Op.getSimpleValueType(); 2722 SDValue Src = Op.getOperand(0); 2723 MVT SrcVT = Src.getSimpleValueType(); 2724 2725 // Prepare any fixed-length vector operands. 2726 MVT ContainerVT = VT; 2727 if (VT.isFixedLengthVector()) { 2728 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2729 ContainerVT = 2730 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2731 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2732 } 2733 2734 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2735 SrcVT.getVectorElementType() != MVT::f64) { 2736 // For scalable vectors, we only need to close the gap between 2737 // vXf64<->vXf16. 2738 if (!VT.isFixedLengthVector()) 2739 return Op; 2740 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2741 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2742 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2743 } 2744 2745 SDValue Mask, VL; 2746 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2747 2748 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2749 SDValue IntermediateRound = 2750 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2751 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2752 DL, DAG, Subtarget); 2753 2754 if (VT.isFixedLengthVector()) 2755 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2756 return Round; 2757 } 2758 case ISD::FP_TO_SINT: 2759 case ISD::FP_TO_UINT: 2760 case ISD::SINT_TO_FP: 2761 case ISD::UINT_TO_FP: { 2762 // RVV can only do fp<->int conversions to types half/double the size as 2763 // the source. We custom-lower any conversions that do two hops into 2764 // sequences. 2765 MVT VT = Op.getSimpleValueType(); 2766 if (!VT.isVector()) 2767 return Op; 2768 SDLoc DL(Op); 2769 SDValue Src = Op.getOperand(0); 2770 MVT EltVT = VT.getVectorElementType(); 2771 MVT SrcVT = Src.getSimpleValueType(); 2772 MVT SrcEltVT = SrcVT.getVectorElementType(); 2773 unsigned EltSize = EltVT.getSizeInBits(); 2774 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2775 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2776 "Unexpected vector element types"); 2777 2778 bool IsInt2FP = SrcEltVT.isInteger(); 2779 // Widening conversions 2780 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2781 if (IsInt2FP) { 2782 // Do a regular integer sign/zero extension then convert to float. 2783 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2784 VT.getVectorElementCount()); 2785 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2786 ? ISD::ZERO_EXTEND 2787 : ISD::SIGN_EXTEND; 2788 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2789 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2790 } 2791 // FP2Int 2792 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2793 // Do one doubling fp_extend then complete the operation by converting 2794 // to int. 2795 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2796 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2797 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2798 } 2799 2800 // Narrowing conversions 2801 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2802 if (IsInt2FP) { 2803 // One narrowing int_to_fp, then an fp_round. 2804 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2805 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2806 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2807 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2808 } 2809 // FP2Int 2810 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2811 // representable by the integer, the result is poison. 2812 MVT IVecVT = 2813 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2814 VT.getVectorElementCount()); 2815 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2816 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2817 } 2818 2819 // Scalable vectors can exit here. Patterns will handle equally-sized 2820 // conversions halving/doubling ones. 2821 if (!VT.isFixedLengthVector()) 2822 return Op; 2823 2824 // For fixed-length vectors we lower to a custom "VL" node. 2825 unsigned RVVOpc = 0; 2826 switch (Op.getOpcode()) { 2827 default: 2828 llvm_unreachable("Impossible opcode"); 2829 case ISD::FP_TO_SINT: 2830 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2831 break; 2832 case ISD::FP_TO_UINT: 2833 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2834 break; 2835 case ISD::SINT_TO_FP: 2836 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2837 break; 2838 case ISD::UINT_TO_FP: 2839 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2840 break; 2841 } 2842 2843 MVT ContainerVT, SrcContainerVT; 2844 // Derive the reference container type from the larger vector type. 2845 if (SrcEltSize > EltSize) { 2846 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2847 ContainerVT = 2848 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2849 } else { 2850 ContainerVT = getContainerForFixedLengthVector(VT); 2851 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2852 } 2853 2854 SDValue Mask, VL; 2855 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2856 2857 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2858 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 2859 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2860 } 2861 case ISD::FP_TO_SINT_SAT: 2862 case ISD::FP_TO_UINT_SAT: 2863 return lowerFP_TO_INT_SAT(Op, DAG); 2864 case ISD::VECREDUCE_ADD: 2865 case ISD::VECREDUCE_UMAX: 2866 case ISD::VECREDUCE_SMAX: 2867 case ISD::VECREDUCE_UMIN: 2868 case ISD::VECREDUCE_SMIN: 2869 return lowerVECREDUCE(Op, DAG); 2870 case ISD::VECREDUCE_AND: 2871 case ISD::VECREDUCE_OR: 2872 case ISD::VECREDUCE_XOR: 2873 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2874 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 2875 return lowerVECREDUCE(Op, DAG); 2876 case ISD::VECREDUCE_FADD: 2877 case ISD::VECREDUCE_SEQ_FADD: 2878 case ISD::VECREDUCE_FMIN: 2879 case ISD::VECREDUCE_FMAX: 2880 return lowerFPVECREDUCE(Op, DAG); 2881 case ISD::VP_REDUCE_ADD: 2882 case ISD::VP_REDUCE_UMAX: 2883 case ISD::VP_REDUCE_SMAX: 2884 case ISD::VP_REDUCE_UMIN: 2885 case ISD::VP_REDUCE_SMIN: 2886 case ISD::VP_REDUCE_FADD: 2887 case ISD::VP_REDUCE_SEQ_FADD: 2888 case ISD::VP_REDUCE_FMIN: 2889 case ISD::VP_REDUCE_FMAX: 2890 return lowerVPREDUCE(Op, DAG); 2891 case ISD::VP_REDUCE_AND: 2892 case ISD::VP_REDUCE_OR: 2893 case ISD::VP_REDUCE_XOR: 2894 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 2895 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 2896 return lowerVPREDUCE(Op, DAG); 2897 case ISD::INSERT_SUBVECTOR: 2898 return lowerINSERT_SUBVECTOR(Op, DAG); 2899 case ISD::EXTRACT_SUBVECTOR: 2900 return lowerEXTRACT_SUBVECTOR(Op, DAG); 2901 case ISD::STEP_VECTOR: 2902 return lowerSTEP_VECTOR(Op, DAG); 2903 case ISD::VECTOR_REVERSE: 2904 return lowerVECTOR_REVERSE(Op, DAG); 2905 case ISD::BUILD_VECTOR: 2906 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 2907 case ISD::SPLAT_VECTOR: 2908 if (Op.getValueType().getVectorElementType() == MVT::i1) 2909 return lowerVectorMaskSplat(Op, DAG); 2910 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 2911 case ISD::VECTOR_SHUFFLE: 2912 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 2913 case ISD::CONCAT_VECTORS: { 2914 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 2915 // better than going through the stack, as the default expansion does. 2916 SDLoc DL(Op); 2917 MVT VT = Op.getSimpleValueType(); 2918 unsigned NumOpElts = 2919 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 2920 SDValue Vec = DAG.getUNDEF(VT); 2921 for (const auto &OpIdx : enumerate(Op->ops())) 2922 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 2923 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 2924 return Vec; 2925 } 2926 case ISD::LOAD: 2927 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 2928 return V; 2929 if (Op.getValueType().isFixedLengthVector()) 2930 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 2931 return Op; 2932 case ISD::STORE: 2933 if (auto V = expandUnalignedRVVStore(Op, DAG)) 2934 return V; 2935 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 2936 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 2937 return Op; 2938 case ISD::MLOAD: 2939 case ISD::VP_LOAD: 2940 return lowerMaskedLoad(Op, DAG); 2941 case ISD::MSTORE: 2942 case ISD::VP_STORE: 2943 return lowerMaskedStore(Op, DAG); 2944 case ISD::SETCC: 2945 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 2946 case ISD::ADD: 2947 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 2948 case ISD::SUB: 2949 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 2950 case ISD::MUL: 2951 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 2952 case ISD::MULHS: 2953 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 2954 case ISD::MULHU: 2955 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 2956 case ISD::AND: 2957 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 2958 RISCVISD::AND_VL); 2959 case ISD::OR: 2960 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 2961 RISCVISD::OR_VL); 2962 case ISD::XOR: 2963 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 2964 RISCVISD::XOR_VL); 2965 case ISD::SDIV: 2966 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 2967 case ISD::SREM: 2968 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 2969 case ISD::UDIV: 2970 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 2971 case ISD::UREM: 2972 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 2973 case ISD::SHL: 2974 case ISD::SRA: 2975 case ISD::SRL: 2976 if (Op.getSimpleValueType().isFixedLengthVector()) 2977 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 2978 // This can be called for an i32 shift amount that needs to be promoted. 2979 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 2980 "Unexpected custom legalisation"); 2981 return SDValue(); 2982 case ISD::SADDSAT: 2983 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 2984 case ISD::UADDSAT: 2985 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 2986 case ISD::SSUBSAT: 2987 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 2988 case ISD::USUBSAT: 2989 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 2990 case ISD::FADD: 2991 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 2992 case ISD::FSUB: 2993 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 2994 case ISD::FMUL: 2995 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 2996 case ISD::FDIV: 2997 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 2998 case ISD::FNEG: 2999 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3000 case ISD::FABS: 3001 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3002 case ISD::FSQRT: 3003 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3004 case ISD::FMA: 3005 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3006 case ISD::SMIN: 3007 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3008 case ISD::SMAX: 3009 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3010 case ISD::UMIN: 3011 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3012 case ISD::UMAX: 3013 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3014 case ISD::FMINNUM: 3015 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3016 case ISD::FMAXNUM: 3017 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3018 case ISD::ABS: 3019 return lowerABS(Op, DAG); 3020 case ISD::CTLZ_ZERO_UNDEF: 3021 case ISD::CTTZ_ZERO_UNDEF: 3022 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3023 case ISD::VSELECT: 3024 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3025 case ISD::FCOPYSIGN: 3026 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3027 case ISD::MGATHER: 3028 case ISD::VP_GATHER: 3029 return lowerMaskedGather(Op, DAG); 3030 case ISD::MSCATTER: 3031 case ISD::VP_SCATTER: 3032 return lowerMaskedScatter(Op, DAG); 3033 case ISD::FLT_ROUNDS_: 3034 return lowerGET_ROUNDING(Op, DAG); 3035 case ISD::SET_ROUNDING: 3036 return lowerSET_ROUNDING(Op, DAG); 3037 case ISD::VP_ADD: 3038 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3039 case ISD::VP_SUB: 3040 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3041 case ISD::VP_MUL: 3042 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3043 case ISD::VP_SDIV: 3044 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3045 case ISD::VP_UDIV: 3046 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3047 case ISD::VP_SREM: 3048 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3049 case ISD::VP_UREM: 3050 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3051 case ISD::VP_AND: 3052 return lowerVPOp(Op, DAG, RISCVISD::AND_VL); 3053 case ISD::VP_OR: 3054 return lowerVPOp(Op, DAG, RISCVISD::OR_VL); 3055 case ISD::VP_XOR: 3056 return lowerVPOp(Op, DAG, RISCVISD::XOR_VL); 3057 case ISD::VP_ASHR: 3058 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3059 case ISD::VP_LSHR: 3060 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3061 case ISD::VP_SHL: 3062 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3063 case ISD::VP_FADD: 3064 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3065 case ISD::VP_FSUB: 3066 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3067 case ISD::VP_FMUL: 3068 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3069 case ISD::VP_FDIV: 3070 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3071 } 3072 } 3073 3074 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3075 SelectionDAG &DAG, unsigned Flags) { 3076 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3077 } 3078 3079 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3080 SelectionDAG &DAG, unsigned Flags) { 3081 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3082 Flags); 3083 } 3084 3085 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3086 SelectionDAG &DAG, unsigned Flags) { 3087 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3088 N->getOffset(), Flags); 3089 } 3090 3091 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3092 SelectionDAG &DAG, unsigned Flags) { 3093 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3094 } 3095 3096 template <class NodeTy> 3097 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3098 bool IsLocal) const { 3099 SDLoc DL(N); 3100 EVT Ty = getPointerTy(DAG.getDataLayout()); 3101 3102 if (isPositionIndependent()) { 3103 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3104 if (IsLocal) 3105 // Use PC-relative addressing to access the symbol. This generates the 3106 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3107 // %pcrel_lo(auipc)). 3108 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3109 3110 // Use PC-relative addressing to access the GOT for this symbol, then load 3111 // the address from the GOT. This generates the pattern (PseudoLA sym), 3112 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3113 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3114 } 3115 3116 switch (getTargetMachine().getCodeModel()) { 3117 default: 3118 report_fatal_error("Unsupported code model for lowering"); 3119 case CodeModel::Small: { 3120 // Generate a sequence for accessing addresses within the first 2 GiB of 3121 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3122 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3123 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3124 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3125 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3126 } 3127 case CodeModel::Medium: { 3128 // Generate a sequence for accessing addresses within any 2GiB range within 3129 // the address space. This generates the pattern (PseudoLLA sym), which 3130 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3131 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3132 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3133 } 3134 } 3135 } 3136 3137 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3138 SelectionDAG &DAG) const { 3139 SDLoc DL(Op); 3140 EVT Ty = Op.getValueType(); 3141 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3142 int64_t Offset = N->getOffset(); 3143 MVT XLenVT = Subtarget.getXLenVT(); 3144 3145 const GlobalValue *GV = N->getGlobal(); 3146 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3147 SDValue Addr = getAddr(N, DAG, IsLocal); 3148 3149 // In order to maximise the opportunity for common subexpression elimination, 3150 // emit a separate ADD node for the global address offset instead of folding 3151 // it in the global address node. Later peephole optimisations may choose to 3152 // fold it back in when profitable. 3153 if (Offset != 0) 3154 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3155 DAG.getConstant(Offset, DL, XLenVT)); 3156 return Addr; 3157 } 3158 3159 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3160 SelectionDAG &DAG) const { 3161 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3162 3163 return getAddr(N, DAG); 3164 } 3165 3166 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3167 SelectionDAG &DAG) const { 3168 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3169 3170 return getAddr(N, DAG); 3171 } 3172 3173 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3174 SelectionDAG &DAG) const { 3175 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3176 3177 return getAddr(N, DAG); 3178 } 3179 3180 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3181 SelectionDAG &DAG, 3182 bool UseGOT) const { 3183 SDLoc DL(N); 3184 EVT Ty = getPointerTy(DAG.getDataLayout()); 3185 const GlobalValue *GV = N->getGlobal(); 3186 MVT XLenVT = Subtarget.getXLenVT(); 3187 3188 if (UseGOT) { 3189 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3190 // load the address from the GOT and add the thread pointer. This generates 3191 // the pattern (PseudoLA_TLS_IE sym), which expands to 3192 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3193 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3194 SDValue Load = 3195 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3196 3197 // Add the thread pointer. 3198 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3199 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3200 } 3201 3202 // Generate a sequence for accessing the address relative to the thread 3203 // pointer, with the appropriate adjustment for the thread pointer offset. 3204 // This generates the pattern 3205 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3206 SDValue AddrHi = 3207 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3208 SDValue AddrAdd = 3209 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3210 SDValue AddrLo = 3211 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3212 3213 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3214 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3215 SDValue MNAdd = SDValue( 3216 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3217 0); 3218 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3219 } 3220 3221 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3222 SelectionDAG &DAG) const { 3223 SDLoc DL(N); 3224 EVT Ty = getPointerTy(DAG.getDataLayout()); 3225 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3226 const GlobalValue *GV = N->getGlobal(); 3227 3228 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3229 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3230 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3231 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3232 SDValue Load = 3233 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3234 3235 // Prepare argument list to generate call. 3236 ArgListTy Args; 3237 ArgListEntry Entry; 3238 Entry.Node = Load; 3239 Entry.Ty = CallTy; 3240 Args.push_back(Entry); 3241 3242 // Setup call to __tls_get_addr. 3243 TargetLowering::CallLoweringInfo CLI(DAG); 3244 CLI.setDebugLoc(DL) 3245 .setChain(DAG.getEntryNode()) 3246 .setLibCallee(CallingConv::C, CallTy, 3247 DAG.getExternalSymbol("__tls_get_addr", Ty), 3248 std::move(Args)); 3249 3250 return LowerCallTo(CLI).first; 3251 } 3252 3253 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3254 SelectionDAG &DAG) const { 3255 SDLoc DL(Op); 3256 EVT Ty = Op.getValueType(); 3257 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3258 int64_t Offset = N->getOffset(); 3259 MVT XLenVT = Subtarget.getXLenVT(); 3260 3261 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3262 3263 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3264 CallingConv::GHC) 3265 report_fatal_error("In GHC calling convention TLS is not supported"); 3266 3267 SDValue Addr; 3268 switch (Model) { 3269 case TLSModel::LocalExec: 3270 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3271 break; 3272 case TLSModel::InitialExec: 3273 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3274 break; 3275 case TLSModel::LocalDynamic: 3276 case TLSModel::GeneralDynamic: 3277 Addr = getDynamicTLSAddr(N, DAG); 3278 break; 3279 } 3280 3281 // In order to maximise the opportunity for common subexpression elimination, 3282 // emit a separate ADD node for the global address offset instead of folding 3283 // it in the global address node. Later peephole optimisations may choose to 3284 // fold it back in when profitable. 3285 if (Offset != 0) 3286 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3287 DAG.getConstant(Offset, DL, XLenVT)); 3288 return Addr; 3289 } 3290 3291 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3292 SDValue CondV = Op.getOperand(0); 3293 SDValue TrueV = Op.getOperand(1); 3294 SDValue FalseV = Op.getOperand(2); 3295 SDLoc DL(Op); 3296 MVT VT = Op.getSimpleValueType(); 3297 MVT XLenVT = Subtarget.getXLenVT(); 3298 3299 // Lower vector SELECTs to VSELECTs by splatting the condition. 3300 if (VT.isVector()) { 3301 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3302 SDValue CondSplat = VT.isScalableVector() 3303 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3304 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3305 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3306 } 3307 3308 // If the result type is XLenVT and CondV is the output of a SETCC node 3309 // which also operated on XLenVT inputs, then merge the SETCC node into the 3310 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3311 // compare+branch instructions. i.e.: 3312 // (select (setcc lhs, rhs, cc), truev, falsev) 3313 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3314 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3315 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3316 SDValue LHS = CondV.getOperand(0); 3317 SDValue RHS = CondV.getOperand(1); 3318 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3319 ISD::CondCode CCVal = CC->get(); 3320 3321 // Special case for a select of 2 constants that have a diffence of 1. 3322 // Normally this is done by DAGCombine, but if the select is introduced by 3323 // type legalization or op legalization, we miss it. Restricting to SETLT 3324 // case for now because that is what signed saturating add/sub need. 3325 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3326 // but we would probably want to swap the true/false values if the condition 3327 // is SETGE/SETLE to avoid an XORI. 3328 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3329 CCVal == ISD::SETLT) { 3330 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3331 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3332 if (TrueVal - 1 == FalseVal) 3333 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3334 if (TrueVal + 1 == FalseVal) 3335 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3336 } 3337 3338 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3339 3340 SDValue TargetCC = DAG.getCondCode(CCVal); 3341 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3342 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3343 } 3344 3345 // Otherwise: 3346 // (select condv, truev, falsev) 3347 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3348 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3349 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3350 3351 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3352 3353 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3354 } 3355 3356 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3357 SDValue CondV = Op.getOperand(1); 3358 SDLoc DL(Op); 3359 MVT XLenVT = Subtarget.getXLenVT(); 3360 3361 if (CondV.getOpcode() == ISD::SETCC && 3362 CondV.getOperand(0).getValueType() == XLenVT) { 3363 SDValue LHS = CondV.getOperand(0); 3364 SDValue RHS = CondV.getOperand(1); 3365 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3366 3367 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3368 3369 SDValue TargetCC = DAG.getCondCode(CCVal); 3370 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3371 LHS, RHS, TargetCC, Op.getOperand(2)); 3372 } 3373 3374 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3375 CondV, DAG.getConstant(0, DL, XLenVT), 3376 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3377 } 3378 3379 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3380 MachineFunction &MF = DAG.getMachineFunction(); 3381 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3382 3383 SDLoc DL(Op); 3384 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3385 getPointerTy(MF.getDataLayout())); 3386 3387 // vastart just stores the address of the VarArgsFrameIndex slot into the 3388 // memory location argument. 3389 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3390 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3391 MachinePointerInfo(SV)); 3392 } 3393 3394 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3395 SelectionDAG &DAG) const { 3396 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3397 MachineFunction &MF = DAG.getMachineFunction(); 3398 MachineFrameInfo &MFI = MF.getFrameInfo(); 3399 MFI.setFrameAddressIsTaken(true); 3400 Register FrameReg = RI.getFrameRegister(MF); 3401 int XLenInBytes = Subtarget.getXLen() / 8; 3402 3403 EVT VT = Op.getValueType(); 3404 SDLoc DL(Op); 3405 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3406 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3407 while (Depth--) { 3408 int Offset = -(XLenInBytes * 2); 3409 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3410 DAG.getIntPtrConstant(Offset, DL)); 3411 FrameAddr = 3412 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3413 } 3414 return FrameAddr; 3415 } 3416 3417 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3418 SelectionDAG &DAG) const { 3419 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3420 MachineFunction &MF = DAG.getMachineFunction(); 3421 MachineFrameInfo &MFI = MF.getFrameInfo(); 3422 MFI.setReturnAddressIsTaken(true); 3423 MVT XLenVT = Subtarget.getXLenVT(); 3424 int XLenInBytes = Subtarget.getXLen() / 8; 3425 3426 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3427 return SDValue(); 3428 3429 EVT VT = Op.getValueType(); 3430 SDLoc DL(Op); 3431 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3432 if (Depth) { 3433 int Off = -XLenInBytes; 3434 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3435 SDValue Offset = DAG.getConstant(Off, DL, VT); 3436 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3437 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3438 MachinePointerInfo()); 3439 } 3440 3441 // Return the value of the return address register, marking it an implicit 3442 // live-in. 3443 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3444 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3445 } 3446 3447 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3448 SelectionDAG &DAG) const { 3449 SDLoc DL(Op); 3450 SDValue Lo = Op.getOperand(0); 3451 SDValue Hi = Op.getOperand(1); 3452 SDValue Shamt = Op.getOperand(2); 3453 EVT VT = Lo.getValueType(); 3454 3455 // if Shamt-XLEN < 0: // Shamt < XLEN 3456 // Lo = Lo << Shamt 3457 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3458 // else: 3459 // Lo = 0 3460 // Hi = Lo << (Shamt-XLEN) 3461 3462 SDValue Zero = DAG.getConstant(0, DL, VT); 3463 SDValue One = DAG.getConstant(1, DL, VT); 3464 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3465 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3466 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3467 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3468 3469 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3470 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3471 SDValue ShiftRightLo = 3472 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3473 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3474 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3475 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3476 3477 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3478 3479 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3480 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3481 3482 SDValue Parts[2] = {Lo, Hi}; 3483 return DAG.getMergeValues(Parts, DL); 3484 } 3485 3486 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3487 bool IsSRA) const { 3488 SDLoc DL(Op); 3489 SDValue Lo = Op.getOperand(0); 3490 SDValue Hi = Op.getOperand(1); 3491 SDValue Shamt = Op.getOperand(2); 3492 EVT VT = Lo.getValueType(); 3493 3494 // SRA expansion: 3495 // if Shamt-XLEN < 0: // Shamt < XLEN 3496 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3497 // Hi = Hi >>s Shamt 3498 // else: 3499 // Lo = Hi >>s (Shamt-XLEN); 3500 // Hi = Hi >>s (XLEN-1) 3501 // 3502 // SRL expansion: 3503 // if Shamt-XLEN < 0: // Shamt < XLEN 3504 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3505 // Hi = Hi >>u Shamt 3506 // else: 3507 // Lo = Hi >>u (Shamt-XLEN); 3508 // Hi = 0; 3509 3510 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3511 3512 SDValue Zero = DAG.getConstant(0, DL, VT); 3513 SDValue One = DAG.getConstant(1, DL, VT); 3514 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3515 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3516 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3517 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3518 3519 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3520 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3521 SDValue ShiftLeftHi = 3522 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3523 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3524 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3525 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3526 SDValue HiFalse = 3527 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3528 3529 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3530 3531 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3532 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3533 3534 SDValue Parts[2] = {Lo, Hi}; 3535 return DAG.getMergeValues(Parts, DL); 3536 } 3537 3538 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3539 // legal equivalently-sized i8 type, so we can use that as a go-between. 3540 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3541 SelectionDAG &DAG) const { 3542 SDLoc DL(Op); 3543 MVT VT = Op.getSimpleValueType(); 3544 SDValue SplatVal = Op.getOperand(0); 3545 // All-zeros or all-ones splats are handled specially. 3546 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3547 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3548 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3549 } 3550 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3551 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3552 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3553 } 3554 MVT XLenVT = Subtarget.getXLenVT(); 3555 assert(SplatVal.getValueType() == XLenVT && 3556 "Unexpected type for i1 splat value"); 3557 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3558 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3559 DAG.getConstant(1, DL, XLenVT)); 3560 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3561 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3562 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3563 } 3564 3565 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3566 // illegal (currently only vXi64 RV32). 3567 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3568 // them to SPLAT_VECTOR_I64 3569 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3570 SelectionDAG &DAG) const { 3571 SDLoc DL(Op); 3572 MVT VecVT = Op.getSimpleValueType(); 3573 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3574 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3575 3576 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3577 SDValue Lo = Op.getOperand(0); 3578 SDValue Hi = Op.getOperand(1); 3579 3580 if (VecVT.isFixedLengthVector()) { 3581 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3582 SDLoc DL(Op); 3583 SDValue Mask, VL; 3584 std::tie(Mask, VL) = 3585 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3586 3587 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3588 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3589 } 3590 3591 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3592 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3593 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3594 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3595 // node in order to try and match RVV vector/scalar instructions. 3596 if ((LoC >> 31) == HiC) 3597 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3598 } 3599 3600 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3601 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3602 isa<ConstantSDNode>(Hi.getOperand(1)) && 3603 Hi.getConstantOperandVal(1) == 31) 3604 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3605 3606 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3607 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3608 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3609 } 3610 3611 // Custom-lower extensions from mask vectors by using a vselect either with 1 3612 // for zero/any-extension or -1 for sign-extension: 3613 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3614 // Note that any-extension is lowered identically to zero-extension. 3615 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3616 int64_t ExtTrueVal) const { 3617 SDLoc DL(Op); 3618 MVT VecVT = Op.getSimpleValueType(); 3619 SDValue Src = Op.getOperand(0); 3620 // Only custom-lower extensions from mask types 3621 assert(Src.getValueType().isVector() && 3622 Src.getValueType().getVectorElementType() == MVT::i1); 3623 3624 MVT XLenVT = Subtarget.getXLenVT(); 3625 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3626 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3627 3628 if (VecVT.isScalableVector()) { 3629 // Be careful not to introduce illegal scalar types at this stage, and be 3630 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3631 // illegal and must be expanded. Since we know that the constants are 3632 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3633 bool IsRV32E64 = 3634 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3635 3636 if (!IsRV32E64) { 3637 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3638 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3639 } else { 3640 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3641 SplatTrueVal = 3642 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3643 } 3644 3645 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3646 } 3647 3648 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3649 MVT I1ContainerVT = 3650 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3651 3652 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3653 3654 SDValue Mask, VL; 3655 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3656 3657 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3658 SplatTrueVal = 3659 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3660 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3661 SplatTrueVal, SplatZero, VL); 3662 3663 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3664 } 3665 3666 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3667 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3668 MVT ExtVT = Op.getSimpleValueType(); 3669 // Only custom-lower extensions from fixed-length vector types. 3670 if (!ExtVT.isFixedLengthVector()) 3671 return Op; 3672 MVT VT = Op.getOperand(0).getSimpleValueType(); 3673 // Grab the canonical container type for the extended type. Infer the smaller 3674 // type from that to ensure the same number of vector elements, as we know 3675 // the LMUL will be sufficient to hold the smaller type. 3676 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3677 // Get the extended container type manually to ensure the same number of 3678 // vector elements between source and dest. 3679 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3680 ContainerExtVT.getVectorElementCount()); 3681 3682 SDValue Op1 = 3683 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3684 3685 SDLoc DL(Op); 3686 SDValue Mask, VL; 3687 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3688 3689 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3690 3691 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3692 } 3693 3694 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3695 // setcc operation: 3696 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3697 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3698 SelectionDAG &DAG) const { 3699 SDLoc DL(Op); 3700 EVT MaskVT = Op.getValueType(); 3701 // Only expect to custom-lower truncations to mask types 3702 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3703 "Unexpected type for vector mask lowering"); 3704 SDValue Src = Op.getOperand(0); 3705 MVT VecVT = Src.getSimpleValueType(); 3706 3707 // If this is a fixed vector, we need to convert it to a scalable vector. 3708 MVT ContainerVT = VecVT; 3709 if (VecVT.isFixedLengthVector()) { 3710 ContainerVT = getContainerForFixedLengthVector(VecVT); 3711 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3712 } 3713 3714 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3715 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3716 3717 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3718 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3719 3720 if (VecVT.isScalableVector()) { 3721 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3722 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3723 } 3724 3725 SDValue Mask, VL; 3726 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3727 3728 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3729 SDValue Trunc = 3730 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3731 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3732 DAG.getCondCode(ISD::SETNE), Mask, VL); 3733 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3734 } 3735 3736 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3737 // first position of a vector, and that vector is slid up to the insert index. 3738 // By limiting the active vector length to index+1 and merging with the 3739 // original vector (with an undisturbed tail policy for elements >= VL), we 3740 // achieve the desired result of leaving all elements untouched except the one 3741 // at VL-1, which is replaced with the desired value. 3742 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3743 SelectionDAG &DAG) const { 3744 SDLoc DL(Op); 3745 MVT VecVT = Op.getSimpleValueType(); 3746 SDValue Vec = Op.getOperand(0); 3747 SDValue Val = Op.getOperand(1); 3748 SDValue Idx = Op.getOperand(2); 3749 3750 if (VecVT.getVectorElementType() == MVT::i1) { 3751 // FIXME: For now we just promote to an i8 vector and insert into that, 3752 // but this is probably not optimal. 3753 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3754 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3755 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3756 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3757 } 3758 3759 MVT ContainerVT = VecVT; 3760 // If the operand is a fixed-length vector, convert to a scalable one. 3761 if (VecVT.isFixedLengthVector()) { 3762 ContainerVT = getContainerForFixedLengthVector(VecVT); 3763 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3764 } 3765 3766 MVT XLenVT = Subtarget.getXLenVT(); 3767 3768 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3769 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3770 // Even i64-element vectors on RV32 can be lowered without scalar 3771 // legalization if the most-significant 32 bits of the value are not affected 3772 // by the sign-extension of the lower 32 bits. 3773 // TODO: We could also catch sign extensions of a 32-bit value. 3774 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3775 const auto *CVal = cast<ConstantSDNode>(Val); 3776 if (isInt<32>(CVal->getSExtValue())) { 3777 IsLegalInsert = true; 3778 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3779 } 3780 } 3781 3782 SDValue Mask, VL; 3783 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3784 3785 SDValue ValInVec; 3786 3787 if (IsLegalInsert) { 3788 unsigned Opc = 3789 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3790 if (isNullConstant(Idx)) { 3791 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3792 if (!VecVT.isFixedLengthVector()) 3793 return Vec; 3794 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3795 } 3796 ValInVec = 3797 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3798 } else { 3799 // On RV32, i64-element vectors must be specially handled to place the 3800 // value at element 0, by using two vslide1up instructions in sequence on 3801 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3802 // this. 3803 SDValue One = DAG.getConstant(1, DL, XLenVT); 3804 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3805 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3806 MVT I32ContainerVT = 3807 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3808 SDValue I32Mask = 3809 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3810 // Limit the active VL to two. 3811 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3812 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3813 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3814 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3815 InsertI64VL); 3816 // First slide in the hi value, then the lo in underneath it. 3817 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3818 ValHi, I32Mask, InsertI64VL); 3819 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3820 ValLo, I32Mask, InsertI64VL); 3821 // Bitcast back to the right container type. 3822 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3823 } 3824 3825 // Now that the value is in a vector, slide it into position. 3826 SDValue InsertVL = 3827 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3828 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3829 ValInVec, Idx, Mask, InsertVL); 3830 if (!VecVT.isFixedLengthVector()) 3831 return Slideup; 3832 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3833 } 3834 3835 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3836 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3837 // types this is done using VMV_X_S to allow us to glean information about the 3838 // sign bits of the result. 3839 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3840 SelectionDAG &DAG) const { 3841 SDLoc DL(Op); 3842 SDValue Idx = Op.getOperand(1); 3843 SDValue Vec = Op.getOperand(0); 3844 EVT EltVT = Op.getValueType(); 3845 MVT VecVT = Vec.getSimpleValueType(); 3846 MVT XLenVT = Subtarget.getXLenVT(); 3847 3848 if (VecVT.getVectorElementType() == MVT::i1) { 3849 // FIXME: For now we just promote to an i8 vector and extract from that, 3850 // but this is probably not optimal. 3851 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3852 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 3854 } 3855 3856 // If this is a fixed vector, we need to convert it to a scalable vector. 3857 MVT ContainerVT = VecVT; 3858 if (VecVT.isFixedLengthVector()) { 3859 ContainerVT = getContainerForFixedLengthVector(VecVT); 3860 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3861 } 3862 3863 // If the index is 0, the vector is already in the right position. 3864 if (!isNullConstant(Idx)) { 3865 // Use a VL of 1 to avoid processing more elements than we need. 3866 SDValue VL = DAG.getConstant(1, DL, XLenVT); 3867 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3868 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3869 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3870 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 3871 } 3872 3873 if (!EltVT.isInteger()) { 3874 // Floating-point extracts are handled in TableGen. 3875 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 3876 DAG.getConstant(0, DL, XLenVT)); 3877 } 3878 3879 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 3880 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 3881 } 3882 3883 // Some RVV intrinsics may claim that they want an integer operand to be 3884 // promoted or expanded. 3885 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 3886 const RISCVSubtarget &Subtarget) { 3887 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3888 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 3889 "Unexpected opcode"); 3890 3891 if (!Subtarget.hasVInstructions()) 3892 return SDValue(); 3893 3894 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 3895 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 3896 SDLoc DL(Op); 3897 3898 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 3899 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 3900 if (!II || !II->SplatOperand) 3901 return SDValue(); 3902 3903 unsigned SplatOp = II->SplatOperand + HasChain; 3904 assert(SplatOp < Op.getNumOperands()); 3905 3906 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 3907 SDValue &ScalarOp = Operands[SplatOp]; 3908 MVT OpVT = ScalarOp.getSimpleValueType(); 3909 MVT XLenVT = Subtarget.getXLenVT(); 3910 3911 // If this isn't a scalar, or its type is XLenVT we're done. 3912 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 3913 return SDValue(); 3914 3915 // Simplest case is that the operand needs to be promoted to XLenVT. 3916 if (OpVT.bitsLT(XLenVT)) { 3917 // If the operand is a constant, sign extend to increase our chances 3918 // of being able to use a .vi instruction. ANY_EXTEND would become a 3919 // a zero extend and the simm5 check in isel would fail. 3920 // FIXME: Should we ignore the upper bits in isel instead? 3921 unsigned ExtOpc = 3922 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 3923 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 3924 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3925 } 3926 3927 // Use the previous operand to get the vXi64 VT. The result might be a mask 3928 // VT for compares. Using the previous operand assumes that the previous 3929 // operand will never have a smaller element size than a scalar operand and 3930 // that a widening operation never uses SEW=64. 3931 // NOTE: If this fails the below assert, we can probably just find the 3932 // element count from any operand or result and use it to construct the VT. 3933 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 3934 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 3935 3936 // The more complex case is when the scalar is larger than XLenVT. 3937 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 3938 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 3939 3940 // If this is a sign-extended 32-bit constant, we can truncate it and rely 3941 // on the instruction to sign-extend since SEW>XLEN. 3942 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 3943 if (isInt<32>(CVal->getSExtValue())) { 3944 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3945 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3946 } 3947 } 3948 3949 // We need to convert the scalar to a splat vector. 3950 // FIXME: Can we implicitly truncate the scalar if it is known to 3951 // be sign extended? 3952 // VL should be the last operand. 3953 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 3954 assert(VL.getValueType() == XLenVT); 3955 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 3956 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3957 } 3958 3959 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3960 SelectionDAG &DAG) const { 3961 unsigned IntNo = Op.getConstantOperandVal(0); 3962 SDLoc DL(Op); 3963 MVT XLenVT = Subtarget.getXLenVT(); 3964 3965 switch (IntNo) { 3966 default: 3967 break; // Don't custom lower most intrinsics. 3968 case Intrinsic::thread_pointer: { 3969 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3970 return DAG.getRegister(RISCV::X4, PtrVT); 3971 } 3972 case Intrinsic::riscv_orc_b: 3973 // Lower to the GORCI encoding for orc.b. 3974 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 3975 DAG.getConstant(7, DL, XLenVT)); 3976 case Intrinsic::riscv_grev: 3977 case Intrinsic::riscv_gorc: { 3978 unsigned Opc = 3979 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 3980 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3981 } 3982 case Intrinsic::riscv_shfl: 3983 case Intrinsic::riscv_unshfl: { 3984 unsigned Opc = 3985 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 3986 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3987 } 3988 case Intrinsic::riscv_bcompress: 3989 case Intrinsic::riscv_bdecompress: { 3990 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 3991 : RISCVISD::BDECOMPRESS; 3992 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3993 } 3994 case Intrinsic::riscv_vmv_x_s: 3995 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 3996 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 3997 Op.getOperand(1)); 3998 case Intrinsic::riscv_vmv_v_x: 3999 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4000 Op.getSimpleValueType(), DL, DAG, Subtarget); 4001 case Intrinsic::riscv_vfmv_v_f: 4002 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4003 Op.getOperand(1), Op.getOperand(2)); 4004 case Intrinsic::riscv_vmv_s_x: { 4005 SDValue Scalar = Op.getOperand(2); 4006 4007 if (Scalar.getValueType().bitsLE(XLenVT)) { 4008 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4009 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4010 Op.getOperand(1), Scalar, Op.getOperand(3)); 4011 } 4012 4013 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4014 4015 // This is an i64 value that lives in two scalar registers. We have to 4016 // insert this in a convoluted way. First we build vXi64 splat containing 4017 // the/ two values that we assemble using some bit math. Next we'll use 4018 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4019 // to merge element 0 from our splat into the source vector. 4020 // FIXME: This is probably not the best way to do this, but it is 4021 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4022 // point. 4023 // sw lo, (a0) 4024 // sw hi, 4(a0) 4025 // vlse vX, (a0) 4026 // 4027 // vid.v vVid 4028 // vmseq.vx mMask, vVid, 0 4029 // vmerge.vvm vDest, vSrc, vVal, mMask 4030 MVT VT = Op.getSimpleValueType(); 4031 SDValue Vec = Op.getOperand(1); 4032 SDValue VL = Op.getOperand(3); 4033 4034 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4035 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4036 DAG.getConstant(0, DL, MVT::i32), VL); 4037 4038 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4039 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4040 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4041 SDValue SelectCond = 4042 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4043 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4044 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4045 Vec, VL); 4046 } 4047 case Intrinsic::riscv_vslide1up: 4048 case Intrinsic::riscv_vslide1down: 4049 case Intrinsic::riscv_vslide1up_mask: 4050 case Intrinsic::riscv_vslide1down_mask: { 4051 // We need to special case these when the scalar is larger than XLen. 4052 unsigned NumOps = Op.getNumOperands(); 4053 bool IsMasked = NumOps == 7; 4054 unsigned OpOffset = IsMasked ? 1 : 0; 4055 SDValue Scalar = Op.getOperand(2 + OpOffset); 4056 if (Scalar.getValueType().bitsLE(XLenVT)) 4057 break; 4058 4059 // Splatting a sign extended constant is fine. 4060 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4061 if (isInt<32>(CVal->getSExtValue())) 4062 break; 4063 4064 MVT VT = Op.getSimpleValueType(); 4065 assert(VT.getVectorElementType() == MVT::i64 && 4066 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4067 4068 // Convert the vector source to the equivalent nxvXi32 vector. 4069 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4070 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4071 4072 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4073 DAG.getConstant(0, DL, XLenVT)); 4074 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4075 DAG.getConstant(1, DL, XLenVT)); 4076 4077 // Double the VL since we halved SEW. 4078 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 4079 SDValue I32VL = 4080 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4081 4082 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4083 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4084 4085 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4086 // instructions. 4087 if (IntNo == Intrinsic::riscv_vslide1up || 4088 IntNo == Intrinsic::riscv_vslide1up_mask) { 4089 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4090 I32Mask, I32VL); 4091 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4092 I32Mask, I32VL); 4093 } else { 4094 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4095 I32Mask, I32VL); 4096 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4097 I32Mask, I32VL); 4098 } 4099 4100 // Convert back to nxvXi64. 4101 Vec = DAG.getBitcast(VT, Vec); 4102 4103 if (!IsMasked) 4104 return Vec; 4105 4106 // Apply mask after the operation. 4107 SDValue Mask = Op.getOperand(NumOps - 3); 4108 SDValue MaskedOff = Op.getOperand(1); 4109 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4110 } 4111 } 4112 4113 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4114 } 4115 4116 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4117 SelectionDAG &DAG) const { 4118 unsigned IntNo = Op.getConstantOperandVal(1); 4119 switch (IntNo) { 4120 default: 4121 break; 4122 case Intrinsic::riscv_masked_strided_load: { 4123 SDLoc DL(Op); 4124 MVT XLenVT = Subtarget.getXLenVT(); 4125 4126 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4127 // the selection of the masked intrinsics doesn't do this for us. 4128 SDValue Mask = Op.getOperand(5); 4129 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4130 4131 MVT VT = Op->getSimpleValueType(0); 4132 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4133 4134 SDValue PassThru = Op.getOperand(2); 4135 if (!IsUnmasked) { 4136 MVT MaskVT = 4137 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4138 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4139 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4140 } 4141 4142 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4143 4144 SDValue IntID = DAG.getTargetConstant( 4145 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4146 XLenVT); 4147 4148 auto *Load = cast<MemIntrinsicSDNode>(Op); 4149 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4150 if (!IsUnmasked) 4151 Ops.push_back(PassThru); 4152 Ops.push_back(Op.getOperand(3)); // Ptr 4153 Ops.push_back(Op.getOperand(4)); // Stride 4154 if (!IsUnmasked) 4155 Ops.push_back(Mask); 4156 Ops.push_back(VL); 4157 if (!IsUnmasked) { 4158 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4159 Ops.push_back(Policy); 4160 } 4161 4162 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4163 SDValue Result = 4164 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4165 Load->getMemoryVT(), Load->getMemOperand()); 4166 SDValue Chain = Result.getValue(1); 4167 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4168 return DAG.getMergeValues({Result, Chain}, DL); 4169 } 4170 } 4171 4172 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4173 } 4174 4175 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4176 SelectionDAG &DAG) const { 4177 unsigned IntNo = Op.getConstantOperandVal(1); 4178 switch (IntNo) { 4179 default: 4180 break; 4181 case Intrinsic::riscv_masked_strided_store: { 4182 SDLoc DL(Op); 4183 MVT XLenVT = Subtarget.getXLenVT(); 4184 4185 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4186 // the selection of the masked intrinsics doesn't do this for us. 4187 SDValue Mask = Op.getOperand(5); 4188 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4189 4190 SDValue Val = Op.getOperand(2); 4191 MVT VT = Val.getSimpleValueType(); 4192 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4193 4194 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4195 if (!IsUnmasked) { 4196 MVT MaskVT = 4197 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4198 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4199 } 4200 4201 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4202 4203 SDValue IntID = DAG.getTargetConstant( 4204 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4205 XLenVT); 4206 4207 auto *Store = cast<MemIntrinsicSDNode>(Op); 4208 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4209 Ops.push_back(Val); 4210 Ops.push_back(Op.getOperand(3)); // Ptr 4211 Ops.push_back(Op.getOperand(4)); // Stride 4212 if (!IsUnmasked) 4213 Ops.push_back(Mask); 4214 Ops.push_back(VL); 4215 4216 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4217 Ops, Store->getMemoryVT(), 4218 Store->getMemOperand()); 4219 } 4220 } 4221 4222 return SDValue(); 4223 } 4224 4225 static MVT getLMUL1VT(MVT VT) { 4226 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4227 "Unexpected vector MVT"); 4228 return MVT::getScalableVectorVT( 4229 VT.getVectorElementType(), 4230 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4231 } 4232 4233 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4234 switch (ISDOpcode) { 4235 default: 4236 llvm_unreachable("Unhandled reduction"); 4237 case ISD::VECREDUCE_ADD: 4238 return RISCVISD::VECREDUCE_ADD_VL; 4239 case ISD::VECREDUCE_UMAX: 4240 return RISCVISD::VECREDUCE_UMAX_VL; 4241 case ISD::VECREDUCE_SMAX: 4242 return RISCVISD::VECREDUCE_SMAX_VL; 4243 case ISD::VECREDUCE_UMIN: 4244 return RISCVISD::VECREDUCE_UMIN_VL; 4245 case ISD::VECREDUCE_SMIN: 4246 return RISCVISD::VECREDUCE_SMIN_VL; 4247 case ISD::VECREDUCE_AND: 4248 return RISCVISD::VECREDUCE_AND_VL; 4249 case ISD::VECREDUCE_OR: 4250 return RISCVISD::VECREDUCE_OR_VL; 4251 case ISD::VECREDUCE_XOR: 4252 return RISCVISD::VECREDUCE_XOR_VL; 4253 } 4254 } 4255 4256 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4257 SelectionDAG &DAG, 4258 bool IsVP) const { 4259 SDLoc DL(Op); 4260 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4261 MVT VecVT = Vec.getSimpleValueType(); 4262 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4263 Op.getOpcode() == ISD::VECREDUCE_OR || 4264 Op.getOpcode() == ISD::VECREDUCE_XOR || 4265 Op.getOpcode() == ISD::VP_REDUCE_AND || 4266 Op.getOpcode() == ISD::VP_REDUCE_OR || 4267 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4268 "Unexpected reduction lowering"); 4269 4270 MVT XLenVT = Subtarget.getXLenVT(); 4271 assert(Op.getValueType() == XLenVT && 4272 "Expected reduction output to be legalized to XLenVT"); 4273 4274 MVT ContainerVT = VecVT; 4275 if (VecVT.isFixedLengthVector()) { 4276 ContainerVT = getContainerForFixedLengthVector(VecVT); 4277 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4278 } 4279 4280 SDValue Mask, VL; 4281 if (IsVP) { 4282 Mask = Op.getOperand(2); 4283 VL = Op.getOperand(3); 4284 } else { 4285 std::tie(Mask, VL) = 4286 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4287 } 4288 4289 unsigned BaseOpc; 4290 ISD::CondCode CC; 4291 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4292 4293 switch (Op.getOpcode()) { 4294 default: 4295 llvm_unreachable("Unhandled reduction"); 4296 case ISD::VECREDUCE_AND: 4297 case ISD::VP_REDUCE_AND: { 4298 // vcpop ~x == 0 4299 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4300 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4301 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4302 CC = ISD::SETEQ; 4303 BaseOpc = ISD::AND; 4304 break; 4305 } 4306 case ISD::VECREDUCE_OR: 4307 case ISD::VP_REDUCE_OR: 4308 // vcpop x != 0 4309 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4310 CC = ISD::SETNE; 4311 BaseOpc = ISD::OR; 4312 break; 4313 case ISD::VECREDUCE_XOR: 4314 case ISD::VP_REDUCE_XOR: { 4315 // ((vcpop x) & 1) != 0 4316 SDValue One = DAG.getConstant(1, DL, XLenVT); 4317 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4318 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4319 CC = ISD::SETNE; 4320 BaseOpc = ISD::XOR; 4321 break; 4322 } 4323 } 4324 4325 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4326 4327 if (!IsVP) 4328 return SetCC; 4329 4330 // Now include the start value in the operation. 4331 // Note that we must return the start value when no elements are operated 4332 // upon. The vcpop instructions we've emitted in each case above will return 4333 // 0 for an inactive vector, and so we've already received the neutral value: 4334 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4335 // can simply include the start value. 4336 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4337 } 4338 4339 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4340 SelectionDAG &DAG) const { 4341 SDLoc DL(Op); 4342 SDValue Vec = Op.getOperand(0); 4343 EVT VecEVT = Vec.getValueType(); 4344 4345 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4346 4347 // Due to ordering in legalize types we may have a vector type that needs to 4348 // be split. Do that manually so we can get down to a legal type. 4349 while (getTypeAction(*DAG.getContext(), VecEVT) == 4350 TargetLowering::TypeSplitVector) { 4351 SDValue Lo, Hi; 4352 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4353 VecEVT = Lo.getValueType(); 4354 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4355 } 4356 4357 // TODO: The type may need to be widened rather than split. Or widened before 4358 // it can be split. 4359 if (!isTypeLegal(VecEVT)) 4360 return SDValue(); 4361 4362 MVT VecVT = VecEVT.getSimpleVT(); 4363 MVT VecEltVT = VecVT.getVectorElementType(); 4364 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4365 4366 MVT ContainerVT = VecVT; 4367 if (VecVT.isFixedLengthVector()) { 4368 ContainerVT = getContainerForFixedLengthVector(VecVT); 4369 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4370 } 4371 4372 MVT M1VT = getLMUL1VT(ContainerVT); 4373 4374 SDValue Mask, VL; 4375 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4376 4377 // FIXME: This is a VLMAX splat which might be too large and can prevent 4378 // vsetvli removal. 4379 SDValue NeutralElem = 4380 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4381 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 4382 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4383 IdentitySplat, Mask, VL); 4384 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4385 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4386 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4387 } 4388 4389 // Given a reduction op, this function returns the matching reduction opcode, 4390 // the vector SDValue and the scalar SDValue required to lower this to a 4391 // RISCVISD node. 4392 static std::tuple<unsigned, SDValue, SDValue> 4393 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4394 SDLoc DL(Op); 4395 auto Flags = Op->getFlags(); 4396 unsigned Opcode = Op.getOpcode(); 4397 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4398 switch (Opcode) { 4399 default: 4400 llvm_unreachable("Unhandled reduction"); 4401 case ISD::VECREDUCE_FADD: 4402 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 4403 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4404 case ISD::VECREDUCE_SEQ_FADD: 4405 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4406 Op.getOperand(0)); 4407 case ISD::VECREDUCE_FMIN: 4408 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4409 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4410 case ISD::VECREDUCE_FMAX: 4411 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4412 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4413 } 4414 } 4415 4416 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4417 SelectionDAG &DAG) const { 4418 SDLoc DL(Op); 4419 MVT VecEltVT = Op.getSimpleValueType(); 4420 4421 unsigned RVVOpcode; 4422 SDValue VectorVal, ScalarVal; 4423 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4424 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4425 MVT VecVT = VectorVal.getSimpleValueType(); 4426 4427 MVT ContainerVT = VecVT; 4428 if (VecVT.isFixedLengthVector()) { 4429 ContainerVT = getContainerForFixedLengthVector(VecVT); 4430 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4431 } 4432 4433 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4434 4435 SDValue Mask, VL; 4436 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4437 4438 // FIXME: This is a VLMAX splat which might be too large and can prevent 4439 // vsetvli removal. 4440 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 4441 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4442 VectorVal, ScalarSplat, Mask, VL); 4443 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4444 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4445 } 4446 4447 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4448 switch (ISDOpcode) { 4449 default: 4450 llvm_unreachable("Unhandled reduction"); 4451 case ISD::VP_REDUCE_ADD: 4452 return RISCVISD::VECREDUCE_ADD_VL; 4453 case ISD::VP_REDUCE_UMAX: 4454 return RISCVISD::VECREDUCE_UMAX_VL; 4455 case ISD::VP_REDUCE_SMAX: 4456 return RISCVISD::VECREDUCE_SMAX_VL; 4457 case ISD::VP_REDUCE_UMIN: 4458 return RISCVISD::VECREDUCE_UMIN_VL; 4459 case ISD::VP_REDUCE_SMIN: 4460 return RISCVISD::VECREDUCE_SMIN_VL; 4461 case ISD::VP_REDUCE_AND: 4462 return RISCVISD::VECREDUCE_AND_VL; 4463 case ISD::VP_REDUCE_OR: 4464 return RISCVISD::VECREDUCE_OR_VL; 4465 case ISD::VP_REDUCE_XOR: 4466 return RISCVISD::VECREDUCE_XOR_VL; 4467 case ISD::VP_REDUCE_FADD: 4468 return RISCVISD::VECREDUCE_FADD_VL; 4469 case ISD::VP_REDUCE_SEQ_FADD: 4470 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4471 case ISD::VP_REDUCE_FMAX: 4472 return RISCVISD::VECREDUCE_FMAX_VL; 4473 case ISD::VP_REDUCE_FMIN: 4474 return RISCVISD::VECREDUCE_FMIN_VL; 4475 } 4476 } 4477 4478 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4479 SelectionDAG &DAG) const { 4480 SDLoc DL(Op); 4481 SDValue Vec = Op.getOperand(1); 4482 EVT VecEVT = Vec.getValueType(); 4483 4484 // TODO: The type may need to be widened rather than split. Or widened before 4485 // it can be split. 4486 if (!isTypeLegal(VecEVT)) 4487 return SDValue(); 4488 4489 MVT VecVT = VecEVT.getSimpleVT(); 4490 MVT VecEltVT = VecVT.getVectorElementType(); 4491 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4492 4493 MVT ContainerVT = VecVT; 4494 if (VecVT.isFixedLengthVector()) { 4495 ContainerVT = getContainerForFixedLengthVector(VecVT); 4496 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4497 } 4498 4499 SDValue VL = Op.getOperand(3); 4500 SDValue Mask = Op.getOperand(2); 4501 4502 MVT M1VT = getLMUL1VT(ContainerVT); 4503 MVT XLenVT = Subtarget.getXLenVT(); 4504 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4505 4506 // FIXME: This is a VLMAX splat which might be too large and can prevent 4507 // vsetvli removal. 4508 SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0)); 4509 SDValue Reduction = 4510 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4511 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4512 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4513 if (!VecVT.isInteger()) 4514 return Elt0; 4515 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4516 } 4517 4518 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4519 SelectionDAG &DAG) const { 4520 SDValue Vec = Op.getOperand(0); 4521 SDValue SubVec = Op.getOperand(1); 4522 MVT VecVT = Vec.getSimpleValueType(); 4523 MVT SubVecVT = SubVec.getSimpleValueType(); 4524 4525 SDLoc DL(Op); 4526 MVT XLenVT = Subtarget.getXLenVT(); 4527 unsigned OrigIdx = Op.getConstantOperandVal(2); 4528 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4529 4530 // We don't have the ability to slide mask vectors up indexed by their i1 4531 // elements; the smallest we can do is i8. Often we are able to bitcast to 4532 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4533 // into a scalable one, we might not necessarily have enough scalable 4534 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4535 if (SubVecVT.getVectorElementType() == MVT::i1 && 4536 (OrigIdx != 0 || !Vec.isUndef())) { 4537 if (VecVT.getVectorMinNumElements() >= 8 && 4538 SubVecVT.getVectorMinNumElements() >= 8) { 4539 assert(OrigIdx % 8 == 0 && "Invalid index"); 4540 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4541 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4542 "Unexpected mask vector lowering"); 4543 OrigIdx /= 8; 4544 SubVecVT = 4545 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4546 SubVecVT.isScalableVector()); 4547 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4548 VecVT.isScalableVector()); 4549 Vec = DAG.getBitcast(VecVT, Vec); 4550 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4551 } else { 4552 // We can't slide this mask vector up indexed by its i1 elements. 4553 // This poses a problem when we wish to insert a scalable vector which 4554 // can't be re-expressed as a larger type. Just choose the slow path and 4555 // extend to a larger type, then truncate back down. 4556 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4557 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4558 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4559 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4560 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4561 Op.getOperand(2)); 4562 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4563 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4564 } 4565 } 4566 4567 // If the subvector vector is a fixed-length type, we cannot use subregister 4568 // manipulation to simplify the codegen; we don't know which register of a 4569 // LMUL group contains the specific subvector as we only know the minimum 4570 // register size. Therefore we must slide the vector group up the full 4571 // amount. 4572 if (SubVecVT.isFixedLengthVector()) { 4573 if (OrigIdx == 0 && Vec.isUndef()) 4574 return Op; 4575 MVT ContainerVT = VecVT; 4576 if (VecVT.isFixedLengthVector()) { 4577 ContainerVT = getContainerForFixedLengthVector(VecVT); 4578 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4579 } 4580 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4581 DAG.getUNDEF(ContainerVT), SubVec, 4582 DAG.getConstant(0, DL, XLenVT)); 4583 SDValue Mask = 4584 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4585 // Set the vector length to only the number of elements we care about. Note 4586 // that for slideup this includes the offset. 4587 SDValue VL = 4588 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4589 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4590 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4591 SubVec, SlideupAmt, Mask, VL); 4592 if (VecVT.isFixedLengthVector()) 4593 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4594 return DAG.getBitcast(Op.getValueType(), Slideup); 4595 } 4596 4597 unsigned SubRegIdx, RemIdx; 4598 std::tie(SubRegIdx, RemIdx) = 4599 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4600 VecVT, SubVecVT, OrigIdx, TRI); 4601 4602 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4603 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4604 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4605 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4606 4607 // 1. If the Idx has been completely eliminated and this subvector's size is 4608 // a vector register or a multiple thereof, or the surrounding elements are 4609 // undef, then this is a subvector insert which naturally aligns to a vector 4610 // register. These can easily be handled using subregister manipulation. 4611 // 2. If the subvector is smaller than a vector register, then the insertion 4612 // must preserve the undisturbed elements of the register. We do this by 4613 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4614 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4615 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4616 // LMUL=1 type back into the larger vector (resolving to another subregister 4617 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4618 // to avoid allocating a large register group to hold our subvector. 4619 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4620 return Op; 4621 4622 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4623 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4624 // (in our case undisturbed). This means we can set up a subvector insertion 4625 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4626 // size of the subvector. 4627 MVT InterSubVT = VecVT; 4628 SDValue AlignedExtract = Vec; 4629 unsigned AlignedIdx = OrigIdx - RemIdx; 4630 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4631 InterSubVT = getLMUL1VT(VecVT); 4632 // Extract a subvector equal to the nearest full vector register type. This 4633 // should resolve to a EXTRACT_SUBREG instruction. 4634 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4635 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4636 } 4637 4638 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4639 // For scalable vectors this must be further multiplied by vscale. 4640 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4641 4642 SDValue Mask, VL; 4643 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4644 4645 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4646 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4647 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4648 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4649 4650 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4651 DAG.getUNDEF(InterSubVT), SubVec, 4652 DAG.getConstant(0, DL, XLenVT)); 4653 4654 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4655 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4656 4657 // If required, insert this subvector back into the correct vector register. 4658 // This should resolve to an INSERT_SUBREG instruction. 4659 if (VecVT.bitsGT(InterSubVT)) 4660 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4661 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4662 4663 // We might have bitcast from a mask type: cast back to the original type if 4664 // required. 4665 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4666 } 4667 4668 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4669 SelectionDAG &DAG) const { 4670 SDValue Vec = Op.getOperand(0); 4671 MVT SubVecVT = Op.getSimpleValueType(); 4672 MVT VecVT = Vec.getSimpleValueType(); 4673 4674 SDLoc DL(Op); 4675 MVT XLenVT = Subtarget.getXLenVT(); 4676 unsigned OrigIdx = Op.getConstantOperandVal(1); 4677 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4678 4679 // We don't have the ability to slide mask vectors down indexed by their i1 4680 // elements; the smallest we can do is i8. Often we are able to bitcast to 4681 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4682 // from a scalable one, we might not necessarily have enough scalable 4683 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4684 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4685 if (VecVT.getVectorMinNumElements() >= 8 && 4686 SubVecVT.getVectorMinNumElements() >= 8) { 4687 assert(OrigIdx % 8 == 0 && "Invalid index"); 4688 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4689 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4690 "Unexpected mask vector lowering"); 4691 OrigIdx /= 8; 4692 SubVecVT = 4693 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4694 SubVecVT.isScalableVector()); 4695 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4696 VecVT.isScalableVector()); 4697 Vec = DAG.getBitcast(VecVT, Vec); 4698 } else { 4699 // We can't slide this mask vector down, indexed by its i1 elements. 4700 // This poses a problem when we wish to extract a scalable vector which 4701 // can't be re-expressed as a larger type. Just choose the slow path and 4702 // extend to a larger type, then truncate back down. 4703 // TODO: We could probably improve this when extracting certain fixed 4704 // from fixed, where we can extract as i8 and shift the correct element 4705 // right to reach the desired subvector? 4706 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4707 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4708 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4709 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4710 Op.getOperand(1)); 4711 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4712 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4713 } 4714 } 4715 4716 // If the subvector vector is a fixed-length type, we cannot use subregister 4717 // manipulation to simplify the codegen; we don't know which register of a 4718 // LMUL group contains the specific subvector as we only know the minimum 4719 // register size. Therefore we must slide the vector group down the full 4720 // amount. 4721 if (SubVecVT.isFixedLengthVector()) { 4722 // With an index of 0 this is a cast-like subvector, which can be performed 4723 // with subregister operations. 4724 if (OrigIdx == 0) 4725 return Op; 4726 MVT ContainerVT = VecVT; 4727 if (VecVT.isFixedLengthVector()) { 4728 ContainerVT = getContainerForFixedLengthVector(VecVT); 4729 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4730 } 4731 SDValue Mask = 4732 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4733 // Set the vector length to only the number of elements we care about. This 4734 // avoids sliding down elements we're going to discard straight away. 4735 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4736 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4737 SDValue Slidedown = 4738 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4739 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4740 // Now we can use a cast-like subvector extract to get the result. 4741 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4742 DAG.getConstant(0, DL, XLenVT)); 4743 return DAG.getBitcast(Op.getValueType(), Slidedown); 4744 } 4745 4746 unsigned SubRegIdx, RemIdx; 4747 std::tie(SubRegIdx, RemIdx) = 4748 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4749 VecVT, SubVecVT, OrigIdx, TRI); 4750 4751 // If the Idx has been completely eliminated then this is a subvector extract 4752 // which naturally aligns to a vector register. These can easily be handled 4753 // using subregister manipulation. 4754 if (RemIdx == 0) 4755 return Op; 4756 4757 // Else we must shift our vector register directly to extract the subvector. 4758 // Do this using VSLIDEDOWN. 4759 4760 // If the vector type is an LMUL-group type, extract a subvector equal to the 4761 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4762 // instruction. 4763 MVT InterSubVT = VecVT; 4764 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4765 InterSubVT = getLMUL1VT(VecVT); 4766 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4767 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4768 } 4769 4770 // Slide this vector register down by the desired number of elements in order 4771 // to place the desired subvector starting at element 0. 4772 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4773 // For scalable vectors this must be further multiplied by vscale. 4774 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4775 4776 SDValue Mask, VL; 4777 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4778 SDValue Slidedown = 4779 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4780 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4781 4782 // Now the vector is in the right position, extract our final subvector. This 4783 // should resolve to a COPY. 4784 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4785 DAG.getConstant(0, DL, XLenVT)); 4786 4787 // We might have bitcast from a mask type: cast back to the original type if 4788 // required. 4789 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4790 } 4791 4792 // Lower step_vector to the vid instruction. Any non-identity step value must 4793 // be accounted for my manual expansion. 4794 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4795 SelectionDAG &DAG) const { 4796 SDLoc DL(Op); 4797 MVT VT = Op.getSimpleValueType(); 4798 MVT XLenVT = Subtarget.getXLenVT(); 4799 SDValue Mask, VL; 4800 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4801 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4802 uint64_t StepValImm = Op.getConstantOperandVal(0); 4803 if (StepValImm != 1) { 4804 if (isPowerOf2_64(StepValImm)) { 4805 SDValue StepVal = 4806 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4807 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4808 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4809 } else { 4810 SDValue StepVal = lowerScalarSplat( 4811 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4812 DL, DAG, Subtarget); 4813 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4814 } 4815 } 4816 return StepVec; 4817 } 4818 4819 // Implement vector_reverse using vrgather.vv with indices determined by 4820 // subtracting the id of each element from (VLMAX-1). This will convert 4821 // the indices like so: 4822 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4823 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4824 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4825 SelectionDAG &DAG) const { 4826 SDLoc DL(Op); 4827 MVT VecVT = Op.getSimpleValueType(); 4828 unsigned EltSize = VecVT.getScalarSizeInBits(); 4829 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4830 4831 unsigned MaxVLMAX = 0; 4832 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4833 if (VectorBitsMax != 0) 4834 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4835 4836 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4837 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4838 4839 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4840 // to use vrgatherei16.vv. 4841 // TODO: It's also possible to use vrgatherei16.vv for other types to 4842 // decrease register width for the index calculation. 4843 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4844 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4845 // Reverse each half, then reassemble them in reverse order. 4846 // NOTE: It's also possible that after splitting that VLMAX no longer 4847 // requires vrgatherei16.vv. 4848 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4849 SDValue Lo, Hi; 4850 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4851 EVT LoVT, HiVT; 4852 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 4853 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 4854 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 4855 // Reassemble the low and high pieces reversed. 4856 // FIXME: This is a CONCAT_VECTORS. 4857 SDValue Res = 4858 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 4859 DAG.getIntPtrConstant(0, DL)); 4860 return DAG.getNode( 4861 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 4862 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 4863 } 4864 4865 // Just promote the int type to i16 which will double the LMUL. 4866 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 4867 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 4868 } 4869 4870 MVT XLenVT = Subtarget.getXLenVT(); 4871 SDValue Mask, VL; 4872 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4873 4874 // Calculate VLMAX-1 for the desired SEW. 4875 unsigned MinElts = VecVT.getVectorMinNumElements(); 4876 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 4877 DAG.getConstant(MinElts, DL, XLenVT)); 4878 SDValue VLMinus1 = 4879 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 4880 4881 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 4882 bool IsRV32E64 = 4883 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 4884 SDValue SplatVL; 4885 if (!IsRV32E64) 4886 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 4887 else 4888 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 4889 4890 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 4891 SDValue Indices = 4892 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 4893 4894 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 4895 } 4896 4897 SDValue 4898 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 4899 SelectionDAG &DAG) const { 4900 SDLoc DL(Op); 4901 auto *Load = cast<LoadSDNode>(Op); 4902 4903 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4904 Load->getMemoryVT(), 4905 *Load->getMemOperand()) && 4906 "Expecting a correctly-aligned load"); 4907 4908 MVT VT = Op.getSimpleValueType(); 4909 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4910 4911 SDValue VL = 4912 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4913 4914 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4915 SDValue NewLoad = DAG.getMemIntrinsicNode( 4916 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 4917 Load->getMemoryVT(), Load->getMemOperand()); 4918 4919 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 4920 return DAG.getMergeValues({Result, Load->getChain()}, DL); 4921 } 4922 4923 SDValue 4924 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 4925 SelectionDAG &DAG) const { 4926 SDLoc DL(Op); 4927 auto *Store = cast<StoreSDNode>(Op); 4928 4929 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4930 Store->getMemoryVT(), 4931 *Store->getMemOperand()) && 4932 "Expecting a correctly-aligned store"); 4933 4934 SDValue StoreVal = Store->getValue(); 4935 MVT VT = StoreVal.getSimpleValueType(); 4936 4937 // If the size less than a byte, we need to pad with zeros to make a byte. 4938 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 4939 VT = MVT::v8i1; 4940 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 4941 DAG.getConstant(0, DL, VT), StoreVal, 4942 DAG.getIntPtrConstant(0, DL)); 4943 } 4944 4945 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4946 4947 SDValue VL = 4948 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4949 4950 SDValue NewValue = 4951 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 4952 return DAG.getMemIntrinsicNode( 4953 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 4954 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 4955 Store->getMemoryVT(), Store->getMemOperand()); 4956 } 4957 4958 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 4959 SelectionDAG &DAG) const { 4960 SDLoc DL(Op); 4961 MVT VT = Op.getSimpleValueType(); 4962 4963 const auto *MemSD = cast<MemSDNode>(Op); 4964 EVT MemVT = MemSD->getMemoryVT(); 4965 MachineMemOperand *MMO = MemSD->getMemOperand(); 4966 SDValue Chain = MemSD->getChain(); 4967 SDValue BasePtr = MemSD->getBasePtr(); 4968 4969 SDValue Mask, PassThru, VL; 4970 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 4971 Mask = VPLoad->getMask(); 4972 PassThru = DAG.getUNDEF(VT); 4973 VL = VPLoad->getVectorLength(); 4974 } else { 4975 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 4976 Mask = MLoad->getMask(); 4977 PassThru = MLoad->getPassThru(); 4978 } 4979 4980 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4981 4982 MVT XLenVT = Subtarget.getXLenVT(); 4983 4984 MVT ContainerVT = VT; 4985 if (VT.isFixedLengthVector()) { 4986 ContainerVT = getContainerForFixedLengthVector(VT); 4987 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4988 if (!IsUnmasked) { 4989 MVT MaskVT = 4990 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4991 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4992 } 4993 } 4994 4995 if (!VL) 4996 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4997 4998 unsigned IntID = 4999 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5000 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5001 if (!IsUnmasked) 5002 Ops.push_back(PassThru); 5003 Ops.push_back(BasePtr); 5004 if (!IsUnmasked) 5005 Ops.push_back(Mask); 5006 Ops.push_back(VL); 5007 if (!IsUnmasked) 5008 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5009 5010 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5011 5012 SDValue Result = 5013 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5014 Chain = Result.getValue(1); 5015 5016 if (VT.isFixedLengthVector()) 5017 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5018 5019 return DAG.getMergeValues({Result, Chain}, DL); 5020 } 5021 5022 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5023 SelectionDAG &DAG) const { 5024 SDLoc DL(Op); 5025 5026 const auto *MemSD = cast<MemSDNode>(Op); 5027 EVT MemVT = MemSD->getMemoryVT(); 5028 MachineMemOperand *MMO = MemSD->getMemOperand(); 5029 SDValue Chain = MemSD->getChain(); 5030 SDValue BasePtr = MemSD->getBasePtr(); 5031 SDValue Val, Mask, VL; 5032 5033 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5034 Val = VPStore->getValue(); 5035 Mask = VPStore->getMask(); 5036 VL = VPStore->getVectorLength(); 5037 } else { 5038 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5039 Val = MStore->getValue(); 5040 Mask = MStore->getMask(); 5041 } 5042 5043 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5044 5045 MVT VT = Val.getSimpleValueType(); 5046 MVT XLenVT = Subtarget.getXLenVT(); 5047 5048 MVT ContainerVT = VT; 5049 if (VT.isFixedLengthVector()) { 5050 ContainerVT = getContainerForFixedLengthVector(VT); 5051 5052 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5053 if (!IsUnmasked) { 5054 MVT MaskVT = 5055 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5056 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5057 } 5058 } 5059 5060 if (!VL) 5061 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5062 5063 unsigned IntID = 5064 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5065 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5066 Ops.push_back(Val); 5067 Ops.push_back(BasePtr); 5068 if (!IsUnmasked) 5069 Ops.push_back(Mask); 5070 Ops.push_back(VL); 5071 5072 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5073 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5074 } 5075 5076 SDValue 5077 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5078 SelectionDAG &DAG) const { 5079 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5080 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5081 5082 MVT VT = Op.getSimpleValueType(); 5083 5084 SDValue Op1 = 5085 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5086 SDValue Op2 = 5087 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5088 5089 SDLoc DL(Op); 5090 SDValue VL = 5091 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5092 5093 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5094 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5095 5096 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5097 Op.getOperand(2), Mask, VL); 5098 5099 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5100 } 5101 5102 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5103 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5104 MVT VT = Op.getSimpleValueType(); 5105 5106 if (VT.getVectorElementType() == MVT::i1) 5107 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5108 5109 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5110 } 5111 5112 SDValue 5113 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5114 SelectionDAG &DAG) const { 5115 unsigned Opc; 5116 switch (Op.getOpcode()) { 5117 default: llvm_unreachable("Unexpected opcode!"); 5118 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5119 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5120 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5121 } 5122 5123 return lowerToScalableOp(Op, DAG, Opc); 5124 } 5125 5126 // Lower vector ABS to smax(X, sub(0, X)). 5127 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5128 SDLoc DL(Op); 5129 MVT VT = Op.getSimpleValueType(); 5130 SDValue X = Op.getOperand(0); 5131 5132 assert(VT.isFixedLengthVector() && "Unexpected type"); 5133 5134 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5135 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5136 5137 SDValue Mask, VL; 5138 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5139 5140 SDValue SplatZero = 5141 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5142 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5143 SDValue NegX = 5144 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5145 SDValue Max = 5146 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5147 5148 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5149 } 5150 5151 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5152 SDValue Op, SelectionDAG &DAG) const { 5153 SDLoc DL(Op); 5154 MVT VT = Op.getSimpleValueType(); 5155 SDValue Mag = Op.getOperand(0); 5156 SDValue Sign = Op.getOperand(1); 5157 assert(Mag.getValueType() == Sign.getValueType() && 5158 "Can only handle COPYSIGN with matching types."); 5159 5160 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5161 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5162 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5163 5164 SDValue Mask, VL; 5165 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5166 5167 SDValue CopySign = 5168 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5169 5170 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5171 } 5172 5173 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5174 SDValue Op, SelectionDAG &DAG) const { 5175 MVT VT = Op.getSimpleValueType(); 5176 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5177 5178 MVT I1ContainerVT = 5179 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5180 5181 SDValue CC = 5182 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5183 SDValue Op1 = 5184 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5185 SDValue Op2 = 5186 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5187 5188 SDLoc DL(Op); 5189 SDValue Mask, VL; 5190 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5191 5192 SDValue Select = 5193 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5194 5195 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5196 } 5197 5198 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5199 unsigned NewOpc, 5200 bool HasMask) const { 5201 MVT VT = Op.getSimpleValueType(); 5202 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5203 5204 // Create list of operands by converting existing ones to scalable types. 5205 SmallVector<SDValue, 6> Ops; 5206 for (const SDValue &V : Op->op_values()) { 5207 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5208 5209 // Pass through non-vector operands. 5210 if (!V.getValueType().isVector()) { 5211 Ops.push_back(V); 5212 continue; 5213 } 5214 5215 // "cast" fixed length vector to a scalable vector. 5216 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5217 "Only fixed length vectors are supported!"); 5218 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5219 } 5220 5221 SDLoc DL(Op); 5222 SDValue Mask, VL; 5223 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5224 if (HasMask) 5225 Ops.push_back(Mask); 5226 Ops.push_back(VL); 5227 5228 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5229 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5230 } 5231 5232 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5233 // * Operands of each node are assumed to be in the same order. 5234 // * The EVL operand is promoted from i32 to i64 on RV64. 5235 // * Fixed-length vectors are converted to their scalable-vector container 5236 // types. 5237 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5238 unsigned RISCVISDOpc) const { 5239 SDLoc DL(Op); 5240 MVT VT = Op.getSimpleValueType(); 5241 SmallVector<SDValue, 4> Ops; 5242 5243 for (const auto &OpIdx : enumerate(Op->ops())) { 5244 SDValue V = OpIdx.value(); 5245 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5246 // Pass through operands which aren't fixed-length vectors. 5247 if (!V.getValueType().isFixedLengthVector()) { 5248 Ops.push_back(V); 5249 continue; 5250 } 5251 // "cast" fixed length vector to a scalable vector. 5252 MVT OpVT = V.getSimpleValueType(); 5253 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5254 assert(useRVVForFixedLengthVectorVT(OpVT) && 5255 "Only fixed length vectors are supported!"); 5256 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5257 } 5258 5259 if (!VT.isFixedLengthVector()) 5260 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5261 5262 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5263 5264 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5265 5266 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5267 } 5268 5269 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5270 // matched to a RVV indexed load. The RVV indexed load instructions only 5271 // support the "unsigned unscaled" addressing mode; indices are implicitly 5272 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5273 // signed or scaled indexing is extended to the XLEN value type and scaled 5274 // accordingly. 5275 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5276 SelectionDAG &DAG) const { 5277 SDLoc DL(Op); 5278 MVT VT = Op.getSimpleValueType(); 5279 5280 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5281 EVT MemVT = MemSD->getMemoryVT(); 5282 MachineMemOperand *MMO = MemSD->getMemOperand(); 5283 SDValue Chain = MemSD->getChain(); 5284 SDValue BasePtr = MemSD->getBasePtr(); 5285 5286 ISD::LoadExtType LoadExtType; 5287 SDValue Index, Mask, PassThru, VL; 5288 5289 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5290 Index = VPGN->getIndex(); 5291 Mask = VPGN->getMask(); 5292 PassThru = DAG.getUNDEF(VT); 5293 VL = VPGN->getVectorLength(); 5294 // VP doesn't support extending loads. 5295 LoadExtType = ISD::NON_EXTLOAD; 5296 } else { 5297 // Else it must be a MGATHER. 5298 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5299 Index = MGN->getIndex(); 5300 Mask = MGN->getMask(); 5301 PassThru = MGN->getPassThru(); 5302 LoadExtType = MGN->getExtensionType(); 5303 } 5304 5305 MVT IndexVT = Index.getSimpleValueType(); 5306 MVT XLenVT = Subtarget.getXLenVT(); 5307 5308 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5309 "Unexpected VTs!"); 5310 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5311 // Targets have to explicitly opt-in for extending vector loads. 5312 assert(LoadExtType == ISD::NON_EXTLOAD && 5313 "Unexpected extending MGATHER/VP_GATHER"); 5314 (void)LoadExtType; 5315 5316 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5317 // the selection of the masked intrinsics doesn't do this for us. 5318 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5319 5320 MVT ContainerVT = VT; 5321 if (VT.isFixedLengthVector()) { 5322 // We need to use the larger of the result and index type to determine the 5323 // scalable type to use so we don't increase LMUL for any operand/result. 5324 if (VT.bitsGE(IndexVT)) { 5325 ContainerVT = getContainerForFixedLengthVector(VT); 5326 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5327 ContainerVT.getVectorElementCount()); 5328 } else { 5329 IndexVT = getContainerForFixedLengthVector(IndexVT); 5330 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5331 IndexVT.getVectorElementCount()); 5332 } 5333 5334 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5335 5336 if (!IsUnmasked) { 5337 MVT MaskVT = 5338 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5339 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5340 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5341 } 5342 } 5343 5344 if (!VL) 5345 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5346 5347 unsigned IntID = 5348 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5349 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5350 if (!IsUnmasked) 5351 Ops.push_back(PassThru); 5352 Ops.push_back(BasePtr); 5353 Ops.push_back(Index); 5354 if (!IsUnmasked) 5355 Ops.push_back(Mask); 5356 Ops.push_back(VL); 5357 if (!IsUnmasked) 5358 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5359 5360 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5361 SDValue Result = 5362 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5363 Chain = Result.getValue(1); 5364 5365 if (VT.isFixedLengthVector()) 5366 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5367 5368 return DAG.getMergeValues({Result, Chain}, DL); 5369 } 5370 5371 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5372 // matched to a RVV indexed store. The RVV indexed store instructions only 5373 // support the "unsigned unscaled" addressing mode; indices are implicitly 5374 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5375 // signed or scaled indexing is extended to the XLEN value type and scaled 5376 // accordingly. 5377 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5378 SelectionDAG &DAG) const { 5379 SDLoc DL(Op); 5380 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5381 EVT MemVT = MemSD->getMemoryVT(); 5382 MachineMemOperand *MMO = MemSD->getMemOperand(); 5383 SDValue Chain = MemSD->getChain(); 5384 SDValue BasePtr = MemSD->getBasePtr(); 5385 5386 bool IsTruncatingStore = false; 5387 SDValue Index, Mask, Val, VL; 5388 5389 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5390 Index = VPSN->getIndex(); 5391 Mask = VPSN->getMask(); 5392 Val = VPSN->getValue(); 5393 VL = VPSN->getVectorLength(); 5394 // VP doesn't support truncating stores. 5395 IsTruncatingStore = false; 5396 } else { 5397 // Else it must be a MSCATTER. 5398 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5399 Index = MSN->getIndex(); 5400 Mask = MSN->getMask(); 5401 Val = MSN->getValue(); 5402 IsTruncatingStore = MSN->isTruncatingStore(); 5403 } 5404 5405 MVT VT = Val.getSimpleValueType(); 5406 MVT IndexVT = Index.getSimpleValueType(); 5407 MVT XLenVT = Subtarget.getXLenVT(); 5408 5409 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5410 "Unexpected VTs!"); 5411 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5412 // Targets have to explicitly opt-in for extending vector loads and 5413 // truncating vector stores. 5414 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5415 (void)IsTruncatingStore; 5416 5417 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5418 // the selection of the masked intrinsics doesn't do this for us. 5419 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5420 5421 MVT ContainerVT = VT; 5422 if (VT.isFixedLengthVector()) { 5423 // We need to use the larger of the value and index type to determine the 5424 // scalable type to use so we don't increase LMUL for any operand/result. 5425 if (VT.bitsGE(IndexVT)) { 5426 ContainerVT = getContainerForFixedLengthVector(VT); 5427 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5428 ContainerVT.getVectorElementCount()); 5429 } else { 5430 IndexVT = getContainerForFixedLengthVector(IndexVT); 5431 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5432 IndexVT.getVectorElementCount()); 5433 } 5434 5435 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5436 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5437 5438 if (!IsUnmasked) { 5439 MVT MaskVT = 5440 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5441 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5442 } 5443 } 5444 5445 if (!VL) 5446 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5447 5448 unsigned IntID = 5449 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5450 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5451 Ops.push_back(Val); 5452 Ops.push_back(BasePtr); 5453 Ops.push_back(Index); 5454 if (!IsUnmasked) 5455 Ops.push_back(Mask); 5456 Ops.push_back(VL); 5457 5458 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5459 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5460 } 5461 5462 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5463 SelectionDAG &DAG) const { 5464 const MVT XLenVT = Subtarget.getXLenVT(); 5465 SDLoc DL(Op); 5466 SDValue Chain = Op->getOperand(0); 5467 SDValue SysRegNo = DAG.getTargetConstant( 5468 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5469 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5470 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5471 5472 // Encoding used for rounding mode in RISCV differs from that used in 5473 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5474 // table, which consists of a sequence of 4-bit fields, each representing 5475 // corresponding FLT_ROUNDS mode. 5476 static const int Table = 5477 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5478 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5479 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5480 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5481 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5482 5483 SDValue Shift = 5484 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5485 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5486 DAG.getConstant(Table, DL, XLenVT), Shift); 5487 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5488 DAG.getConstant(7, DL, XLenVT)); 5489 5490 return DAG.getMergeValues({Masked, Chain}, DL); 5491 } 5492 5493 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5494 SelectionDAG &DAG) const { 5495 const MVT XLenVT = Subtarget.getXLenVT(); 5496 SDLoc DL(Op); 5497 SDValue Chain = Op->getOperand(0); 5498 SDValue RMValue = Op->getOperand(1); 5499 SDValue SysRegNo = DAG.getTargetConstant( 5500 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5501 5502 // Encoding used for rounding mode in RISCV differs from that used in 5503 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5504 // a table, which consists of a sequence of 4-bit fields, each representing 5505 // corresponding RISCV mode. 5506 static const unsigned Table = 5507 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5508 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5509 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5510 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5511 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5512 5513 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5514 DAG.getConstant(2, DL, XLenVT)); 5515 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5516 DAG.getConstant(Table, DL, XLenVT), Shift); 5517 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5518 DAG.getConstant(0x7, DL, XLenVT)); 5519 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5520 RMValue); 5521 } 5522 5523 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5524 // form of the given Opcode. 5525 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5526 switch (Opcode) { 5527 default: 5528 llvm_unreachable("Unexpected opcode"); 5529 case ISD::SHL: 5530 return RISCVISD::SLLW; 5531 case ISD::SRA: 5532 return RISCVISD::SRAW; 5533 case ISD::SRL: 5534 return RISCVISD::SRLW; 5535 case ISD::SDIV: 5536 return RISCVISD::DIVW; 5537 case ISD::UDIV: 5538 return RISCVISD::DIVUW; 5539 case ISD::UREM: 5540 return RISCVISD::REMUW; 5541 case ISD::ROTL: 5542 return RISCVISD::ROLW; 5543 case ISD::ROTR: 5544 return RISCVISD::RORW; 5545 case RISCVISD::GREV: 5546 return RISCVISD::GREVW; 5547 case RISCVISD::GORC: 5548 return RISCVISD::GORCW; 5549 } 5550 } 5551 5552 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5553 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5554 // otherwise be promoted to i64, making it difficult to select the 5555 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5556 // type i8/i16/i32 is lost. 5557 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5558 unsigned ExtOpc = ISD::ANY_EXTEND) { 5559 SDLoc DL(N); 5560 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5561 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5562 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5563 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5564 // ReplaceNodeResults requires we maintain the same type for the return value. 5565 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5566 } 5567 5568 // Converts the given 32-bit operation to a i64 operation with signed extension 5569 // semantic to reduce the signed extension instructions. 5570 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5571 SDLoc DL(N); 5572 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5573 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5574 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5575 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5576 DAG.getValueType(MVT::i32)); 5577 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5578 } 5579 5580 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5581 SmallVectorImpl<SDValue> &Results, 5582 SelectionDAG &DAG) const { 5583 SDLoc DL(N); 5584 switch (N->getOpcode()) { 5585 default: 5586 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5587 case ISD::STRICT_FP_TO_SINT: 5588 case ISD::STRICT_FP_TO_UINT: 5589 case ISD::FP_TO_SINT: 5590 case ISD::FP_TO_UINT: { 5591 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5592 "Unexpected custom legalisation"); 5593 bool IsStrict = N->isStrictFPOpcode(); 5594 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5595 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5596 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5597 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5598 TargetLowering::TypeSoftenFloat) { 5599 // FIXME: Support strict FP. 5600 if (IsStrict) 5601 return; 5602 if (!isTypeLegal(Op0.getValueType())) 5603 return; 5604 unsigned Opc = 5605 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5606 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5607 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5608 return; 5609 } 5610 // If the FP type needs to be softened, emit a library call using the 'si' 5611 // version. If we left it to default legalization we'd end up with 'di'. If 5612 // the FP type doesn't need to be softened just let generic type 5613 // legalization promote the result type. 5614 RTLIB::Libcall LC; 5615 if (IsSigned) 5616 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5617 else 5618 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5619 MakeLibCallOptions CallOptions; 5620 EVT OpVT = Op0.getValueType(); 5621 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5622 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5623 SDValue Result; 5624 std::tie(Result, Chain) = 5625 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5626 Results.push_back(Result); 5627 if (IsStrict) 5628 Results.push_back(Chain); 5629 break; 5630 } 5631 case ISD::READCYCLECOUNTER: { 5632 assert(!Subtarget.is64Bit() && 5633 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5634 5635 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5636 SDValue RCW = 5637 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5638 5639 Results.push_back( 5640 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5641 Results.push_back(RCW.getValue(2)); 5642 break; 5643 } 5644 case ISD::MUL: { 5645 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5646 unsigned XLen = Subtarget.getXLen(); 5647 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5648 if (Size > XLen) { 5649 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5650 SDValue LHS = N->getOperand(0); 5651 SDValue RHS = N->getOperand(1); 5652 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5653 5654 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5655 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5656 // We need exactly one side to be unsigned. 5657 if (LHSIsU == RHSIsU) 5658 return; 5659 5660 auto MakeMULPair = [&](SDValue S, SDValue U) { 5661 MVT XLenVT = Subtarget.getXLenVT(); 5662 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5663 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5664 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5665 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5666 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5667 }; 5668 5669 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5670 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5671 5672 // The other operand should be signed, but still prefer MULH when 5673 // possible. 5674 if (RHSIsU && LHSIsS && !RHSIsS) 5675 Results.push_back(MakeMULPair(LHS, RHS)); 5676 else if (LHSIsU && RHSIsS && !LHSIsS) 5677 Results.push_back(MakeMULPair(RHS, LHS)); 5678 5679 return; 5680 } 5681 LLVM_FALLTHROUGH; 5682 } 5683 case ISD::ADD: 5684 case ISD::SUB: 5685 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5686 "Unexpected custom legalisation"); 5687 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5688 break; 5689 case ISD::SHL: 5690 case ISD::SRA: 5691 case ISD::SRL: 5692 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5693 "Unexpected custom legalisation"); 5694 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5695 Results.push_back(customLegalizeToWOp(N, DAG)); 5696 break; 5697 } 5698 5699 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5700 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5701 // shift amount. 5702 if (N->getOpcode() == ISD::SHL) { 5703 SDLoc DL(N); 5704 SDValue NewOp0 = 5705 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5706 SDValue NewOp1 = 5707 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5708 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5709 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5710 DAG.getValueType(MVT::i32)); 5711 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5712 } 5713 5714 break; 5715 case ISD::ROTL: 5716 case ISD::ROTR: 5717 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5718 "Unexpected custom legalisation"); 5719 Results.push_back(customLegalizeToWOp(N, DAG)); 5720 break; 5721 case ISD::CTTZ: 5722 case ISD::CTTZ_ZERO_UNDEF: 5723 case ISD::CTLZ: 5724 case ISD::CTLZ_ZERO_UNDEF: { 5725 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5726 "Unexpected custom legalisation"); 5727 5728 SDValue NewOp0 = 5729 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5730 bool IsCTZ = 5731 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5732 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5733 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5734 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5735 return; 5736 } 5737 case ISD::SDIV: 5738 case ISD::UDIV: 5739 case ISD::UREM: { 5740 MVT VT = N->getSimpleValueType(0); 5741 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5742 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5743 "Unexpected custom legalisation"); 5744 // Don't promote division/remainder by constant since we should expand those 5745 // to multiply by magic constant. 5746 // FIXME: What if the expansion is disabled for minsize. 5747 if (N->getOperand(1).getOpcode() == ISD::Constant) 5748 return; 5749 5750 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5751 // the upper 32 bits. For other types we need to sign or zero extend 5752 // based on the opcode. 5753 unsigned ExtOpc = ISD::ANY_EXTEND; 5754 if (VT != MVT::i32) 5755 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5756 : ISD::ZERO_EXTEND; 5757 5758 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5759 break; 5760 } 5761 case ISD::UADDO: 5762 case ISD::USUBO: { 5763 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5764 "Unexpected custom legalisation"); 5765 bool IsAdd = N->getOpcode() == ISD::UADDO; 5766 // Create an ADDW or SUBW. 5767 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5768 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5769 SDValue Res = 5770 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5771 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5772 DAG.getValueType(MVT::i32)); 5773 5774 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5775 // Since the inputs are sign extended from i32, this is equivalent to 5776 // comparing the lower 32 bits. 5777 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5778 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5779 IsAdd ? ISD::SETULT : ISD::SETUGT); 5780 5781 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5782 Results.push_back(Overflow); 5783 return; 5784 } 5785 case ISD::UADDSAT: 5786 case ISD::USUBSAT: { 5787 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5788 "Unexpected custom legalisation"); 5789 if (Subtarget.hasStdExtZbb()) { 5790 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5791 // sign extend allows overflow of the lower 32 bits to be detected on 5792 // the promoted size. 5793 SDValue LHS = 5794 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5795 SDValue RHS = 5796 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5797 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5798 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5799 return; 5800 } 5801 5802 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5803 // promotion for UADDO/USUBO. 5804 Results.push_back(expandAddSubSat(N, DAG)); 5805 return; 5806 } 5807 case ISD::BITCAST: { 5808 EVT VT = N->getValueType(0); 5809 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5810 SDValue Op0 = N->getOperand(0); 5811 EVT Op0VT = Op0.getValueType(); 5812 MVT XLenVT = Subtarget.getXLenVT(); 5813 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5814 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5815 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5816 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 5817 Subtarget.hasStdExtF()) { 5818 SDValue FPConv = 5819 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 5820 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 5821 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 5822 isTypeLegal(Op0VT)) { 5823 // Custom-legalize bitcasts from fixed-length vector types to illegal 5824 // scalar types in order to improve codegen. Bitcast the vector to a 5825 // one-element vector type whose element type is the same as the result 5826 // type, and extract the first element. 5827 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 5828 if (isTypeLegal(BVT)) { 5829 SDValue BVec = DAG.getBitcast(BVT, Op0); 5830 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 5831 DAG.getConstant(0, DL, XLenVT))); 5832 } 5833 } 5834 break; 5835 } 5836 case RISCVISD::GREV: 5837 case RISCVISD::GORC: { 5838 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5839 "Unexpected custom legalisation"); 5840 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5841 // This is similar to customLegalizeToWOp, except that we pass the second 5842 // operand (a TargetConstant) straight through: it is already of type 5843 // XLenVT. 5844 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5845 SDValue NewOp0 = 5846 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5847 SDValue NewOp1 = 5848 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5849 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5850 // ReplaceNodeResults requires we maintain the same type for the return 5851 // value. 5852 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5853 break; 5854 } 5855 case RISCVISD::SHFL: { 5856 // There is no SHFLIW instruction, but we can just promote the operation. 5857 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5858 "Unexpected custom legalisation"); 5859 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5860 SDValue NewOp0 = 5861 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5862 SDValue NewOp1 = 5863 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5864 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 5865 // ReplaceNodeResults requires we maintain the same type for the return 5866 // value. 5867 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5868 break; 5869 } 5870 case ISD::BSWAP: 5871 case ISD::BITREVERSE: { 5872 MVT VT = N->getSimpleValueType(0); 5873 MVT XLenVT = Subtarget.getXLenVT(); 5874 assert((VT == MVT::i8 || VT == MVT::i16 || 5875 (VT == MVT::i32 && Subtarget.is64Bit())) && 5876 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 5877 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 5878 unsigned Imm = VT.getSizeInBits() - 1; 5879 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 5880 if (N->getOpcode() == ISD::BSWAP) 5881 Imm &= ~0x7U; 5882 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 5883 SDValue GREVI = 5884 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 5885 // ReplaceNodeResults requires we maintain the same type for the return 5886 // value. 5887 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 5888 break; 5889 } 5890 case ISD::FSHL: 5891 case ISD::FSHR: { 5892 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5893 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 5894 SDValue NewOp0 = 5895 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5896 SDValue NewOp1 = 5897 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5898 SDValue NewOp2 = 5899 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5900 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 5901 // Mask the shift amount to 5 bits. 5902 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5903 DAG.getConstant(0x1f, DL, MVT::i64)); 5904 unsigned Opc = 5905 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 5906 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 5907 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 5908 break; 5909 } 5910 case ISD::EXTRACT_VECTOR_ELT: { 5911 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 5912 // type is illegal (currently only vXi64 RV32). 5913 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 5914 // transferred to the destination register. We issue two of these from the 5915 // upper- and lower- halves of the SEW-bit vector element, slid down to the 5916 // first element. 5917 SDValue Vec = N->getOperand(0); 5918 SDValue Idx = N->getOperand(1); 5919 5920 // The vector type hasn't been legalized yet so we can't issue target 5921 // specific nodes if it needs legalization. 5922 // FIXME: We would manually legalize if it's important. 5923 if (!isTypeLegal(Vec.getValueType())) 5924 return; 5925 5926 MVT VecVT = Vec.getSimpleValueType(); 5927 5928 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 5929 VecVT.getVectorElementType() == MVT::i64 && 5930 "Unexpected EXTRACT_VECTOR_ELT legalization"); 5931 5932 // If this is a fixed vector, we need to convert it to a scalable vector. 5933 MVT ContainerVT = VecVT; 5934 if (VecVT.isFixedLengthVector()) { 5935 ContainerVT = getContainerForFixedLengthVector(VecVT); 5936 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5937 } 5938 5939 MVT XLenVT = Subtarget.getXLenVT(); 5940 5941 // Use a VL of 1 to avoid processing more elements than we need. 5942 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5943 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5944 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5945 5946 // Unless the index is known to be 0, we must slide the vector down to get 5947 // the desired element into index 0. 5948 if (!isNullConstant(Idx)) { 5949 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5950 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5951 } 5952 5953 // Extract the lower XLEN bits of the correct vector element. 5954 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5955 5956 // To extract the upper XLEN bits of the vector element, shift the first 5957 // element right by 32 bits and re-extract the lower XLEN bits. 5958 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5959 DAG.getConstant(32, DL, XLenVT), VL); 5960 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 5961 ThirtyTwoV, Mask, VL); 5962 5963 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5964 5965 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5966 break; 5967 } 5968 case ISD::INTRINSIC_WO_CHAIN: { 5969 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5970 switch (IntNo) { 5971 default: 5972 llvm_unreachable( 5973 "Don't know how to custom type legalize this intrinsic!"); 5974 case Intrinsic::riscv_orc_b: { 5975 // Lower to the GORCI encoding for orc.b with the operand extended. 5976 SDValue NewOp = 5977 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5978 // If Zbp is enabled, use GORCIW which will sign extend the result. 5979 unsigned Opc = 5980 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 5981 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 5982 DAG.getConstant(7, DL, MVT::i64)); 5983 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5984 return; 5985 } 5986 case Intrinsic::riscv_grev: 5987 case Intrinsic::riscv_gorc: { 5988 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5989 "Unexpected custom legalisation"); 5990 SDValue NewOp1 = 5991 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5992 SDValue NewOp2 = 5993 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5994 unsigned Opc = 5995 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 5996 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5997 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5998 break; 5999 } 6000 case Intrinsic::riscv_shfl: 6001 case Intrinsic::riscv_unshfl: { 6002 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6003 "Unexpected custom legalisation"); 6004 SDValue NewOp1 = 6005 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6006 SDValue NewOp2 = 6007 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6008 unsigned Opc = 6009 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6010 if (isa<ConstantSDNode>(N->getOperand(2))) { 6011 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6012 DAG.getConstant(0xf, DL, MVT::i64)); 6013 Opc = 6014 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6015 } 6016 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6017 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6018 break; 6019 } 6020 case Intrinsic::riscv_bcompress: 6021 case Intrinsic::riscv_bdecompress: { 6022 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6023 "Unexpected custom legalisation"); 6024 SDValue NewOp1 = 6025 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6026 SDValue NewOp2 = 6027 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6028 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 6029 ? RISCVISD::BCOMPRESSW 6030 : RISCVISD::BDECOMPRESSW; 6031 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6032 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6033 break; 6034 } 6035 case Intrinsic::riscv_vmv_x_s: { 6036 EVT VT = N->getValueType(0); 6037 MVT XLenVT = Subtarget.getXLenVT(); 6038 if (VT.bitsLT(XLenVT)) { 6039 // Simple case just extract using vmv.x.s and truncate. 6040 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6041 Subtarget.getXLenVT(), N->getOperand(1)); 6042 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6043 return; 6044 } 6045 6046 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6047 "Unexpected custom legalization"); 6048 6049 // We need to do the move in two steps. 6050 SDValue Vec = N->getOperand(1); 6051 MVT VecVT = Vec.getSimpleValueType(); 6052 6053 // First extract the lower XLEN bits of the element. 6054 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6055 6056 // To extract the upper XLEN bits of the vector element, shift the first 6057 // element right by 32 bits and re-extract the lower XLEN bits. 6058 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6059 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6060 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6061 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6062 DAG.getConstant(32, DL, XLenVT), VL); 6063 SDValue LShr32 = 6064 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6065 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6066 6067 Results.push_back( 6068 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6069 break; 6070 } 6071 } 6072 break; 6073 } 6074 case ISD::VECREDUCE_ADD: 6075 case ISD::VECREDUCE_AND: 6076 case ISD::VECREDUCE_OR: 6077 case ISD::VECREDUCE_XOR: 6078 case ISD::VECREDUCE_SMAX: 6079 case ISD::VECREDUCE_UMAX: 6080 case ISD::VECREDUCE_SMIN: 6081 case ISD::VECREDUCE_UMIN: 6082 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6083 Results.push_back(V); 6084 break; 6085 case ISD::VP_REDUCE_ADD: 6086 case ISD::VP_REDUCE_AND: 6087 case ISD::VP_REDUCE_OR: 6088 case ISD::VP_REDUCE_XOR: 6089 case ISD::VP_REDUCE_SMAX: 6090 case ISD::VP_REDUCE_UMAX: 6091 case ISD::VP_REDUCE_SMIN: 6092 case ISD::VP_REDUCE_UMIN: 6093 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6094 Results.push_back(V); 6095 break; 6096 case ISD::FLT_ROUNDS_: { 6097 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6098 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6099 Results.push_back(Res.getValue(0)); 6100 Results.push_back(Res.getValue(1)); 6101 break; 6102 } 6103 } 6104 } 6105 6106 // A structure to hold one of the bit-manipulation patterns below. Together, a 6107 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6108 // (or (and (shl x, 1), 0xAAAAAAAA), 6109 // (and (srl x, 1), 0x55555555)) 6110 struct RISCVBitmanipPat { 6111 SDValue Op; 6112 unsigned ShAmt; 6113 bool IsSHL; 6114 6115 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6116 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6117 } 6118 }; 6119 6120 // Matches patterns of the form 6121 // (and (shl x, C2), (C1 << C2)) 6122 // (and (srl x, C2), C1) 6123 // (shl (and x, C1), C2) 6124 // (srl (and x, (C1 << C2)), C2) 6125 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6126 // The expected masks for each shift amount are specified in BitmanipMasks where 6127 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6128 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6129 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6130 // XLen is 64. 6131 static Optional<RISCVBitmanipPat> 6132 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6133 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6134 "Unexpected number of masks"); 6135 Optional<uint64_t> Mask; 6136 // Optionally consume a mask around the shift operation. 6137 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6138 Mask = Op.getConstantOperandVal(1); 6139 Op = Op.getOperand(0); 6140 } 6141 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6142 return None; 6143 bool IsSHL = Op.getOpcode() == ISD::SHL; 6144 6145 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6146 return None; 6147 uint64_t ShAmt = Op.getConstantOperandVal(1); 6148 6149 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6150 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6151 return None; 6152 // If we don't have enough masks for 64 bit, then we must be trying to 6153 // match SHFL so we're only allowed to shift 1/4 of the width. 6154 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6155 return None; 6156 6157 SDValue Src = Op.getOperand(0); 6158 6159 // The expected mask is shifted left when the AND is found around SHL 6160 // patterns. 6161 // ((x >> 1) & 0x55555555) 6162 // ((x << 1) & 0xAAAAAAAA) 6163 bool SHLExpMask = IsSHL; 6164 6165 if (!Mask) { 6166 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6167 // the mask is all ones: consume that now. 6168 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6169 Mask = Src.getConstantOperandVal(1); 6170 Src = Src.getOperand(0); 6171 // The expected mask is now in fact shifted left for SRL, so reverse the 6172 // decision. 6173 // ((x & 0xAAAAAAAA) >> 1) 6174 // ((x & 0x55555555) << 1) 6175 SHLExpMask = !SHLExpMask; 6176 } else { 6177 // Use a default shifted mask of all-ones if there's no AND, truncated 6178 // down to the expected width. This simplifies the logic later on. 6179 Mask = maskTrailingOnes<uint64_t>(Width); 6180 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6181 } 6182 } 6183 6184 unsigned MaskIdx = Log2_32(ShAmt); 6185 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6186 6187 if (SHLExpMask) 6188 ExpMask <<= ShAmt; 6189 6190 if (Mask != ExpMask) 6191 return None; 6192 6193 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6194 } 6195 6196 // Matches any of the following bit-manipulation patterns: 6197 // (and (shl x, 1), (0x55555555 << 1)) 6198 // (and (srl x, 1), 0x55555555) 6199 // (shl (and x, 0x55555555), 1) 6200 // (srl (and x, (0x55555555 << 1)), 1) 6201 // where the shift amount and mask may vary thus: 6202 // [1] = 0x55555555 / 0xAAAAAAAA 6203 // [2] = 0x33333333 / 0xCCCCCCCC 6204 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6205 // [8] = 0x00FF00FF / 0xFF00FF00 6206 // [16] = 0x0000FFFF / 0xFFFFFFFF 6207 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6208 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6209 // These are the unshifted masks which we use to match bit-manipulation 6210 // patterns. They may be shifted left in certain circumstances. 6211 static const uint64_t BitmanipMasks[] = { 6212 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6213 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6214 6215 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6216 } 6217 6218 // Match the following pattern as a GREVI(W) operation 6219 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6220 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6221 const RISCVSubtarget &Subtarget) { 6222 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6223 EVT VT = Op.getValueType(); 6224 6225 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6226 auto LHS = matchGREVIPat(Op.getOperand(0)); 6227 auto RHS = matchGREVIPat(Op.getOperand(1)); 6228 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6229 SDLoc DL(Op); 6230 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6231 DAG.getConstant(LHS->ShAmt, DL, VT)); 6232 } 6233 } 6234 return SDValue(); 6235 } 6236 6237 // Matches any the following pattern as a GORCI(W) operation 6238 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6239 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6240 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6241 // Note that with the variant of 3., 6242 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6243 // the inner pattern will first be matched as GREVI and then the outer 6244 // pattern will be matched to GORC via the first rule above. 6245 // 4. (or (rotl/rotr x, bitwidth/2), x) 6246 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6247 const RISCVSubtarget &Subtarget) { 6248 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6249 EVT VT = Op.getValueType(); 6250 6251 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6252 SDLoc DL(Op); 6253 SDValue Op0 = Op.getOperand(0); 6254 SDValue Op1 = Op.getOperand(1); 6255 6256 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6257 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6258 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6259 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6260 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6261 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6262 if ((Reverse.getOpcode() == ISD::ROTL || 6263 Reverse.getOpcode() == ISD::ROTR) && 6264 Reverse.getOperand(0) == X && 6265 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6266 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6267 if (RotAmt == (VT.getSizeInBits() / 2)) 6268 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6269 DAG.getConstant(RotAmt, DL, VT)); 6270 } 6271 return SDValue(); 6272 }; 6273 6274 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6275 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6276 return V; 6277 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6278 return V; 6279 6280 // OR is commutable so canonicalize its OR operand to the left 6281 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6282 std::swap(Op0, Op1); 6283 if (Op0.getOpcode() != ISD::OR) 6284 return SDValue(); 6285 SDValue OrOp0 = Op0.getOperand(0); 6286 SDValue OrOp1 = Op0.getOperand(1); 6287 auto LHS = matchGREVIPat(OrOp0); 6288 // OR is commutable so swap the operands and try again: x might have been 6289 // on the left 6290 if (!LHS) { 6291 std::swap(OrOp0, OrOp1); 6292 LHS = matchGREVIPat(OrOp0); 6293 } 6294 auto RHS = matchGREVIPat(Op1); 6295 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6296 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6297 DAG.getConstant(LHS->ShAmt, DL, VT)); 6298 } 6299 } 6300 return SDValue(); 6301 } 6302 6303 // Matches any of the following bit-manipulation patterns: 6304 // (and (shl x, 1), (0x22222222 << 1)) 6305 // (and (srl x, 1), 0x22222222) 6306 // (shl (and x, 0x22222222), 1) 6307 // (srl (and x, (0x22222222 << 1)), 1) 6308 // where the shift amount and mask may vary thus: 6309 // [1] = 0x22222222 / 0x44444444 6310 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6311 // [4] = 0x00F000F0 / 0x0F000F00 6312 // [8] = 0x0000FF00 / 0x00FF0000 6313 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6314 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6315 // These are the unshifted masks which we use to match bit-manipulation 6316 // patterns. They may be shifted left in certain circumstances. 6317 static const uint64_t BitmanipMasks[] = { 6318 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6319 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6320 6321 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6322 } 6323 6324 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6325 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6326 const RISCVSubtarget &Subtarget) { 6327 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6328 EVT VT = Op.getValueType(); 6329 6330 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6331 return SDValue(); 6332 6333 SDValue Op0 = Op.getOperand(0); 6334 SDValue Op1 = Op.getOperand(1); 6335 6336 // Or is commutable so canonicalize the second OR to the LHS. 6337 if (Op0.getOpcode() != ISD::OR) 6338 std::swap(Op0, Op1); 6339 if (Op0.getOpcode() != ISD::OR) 6340 return SDValue(); 6341 6342 // We found an inner OR, so our operands are the operands of the inner OR 6343 // and the other operand of the outer OR. 6344 SDValue A = Op0.getOperand(0); 6345 SDValue B = Op0.getOperand(1); 6346 SDValue C = Op1; 6347 6348 auto Match1 = matchSHFLPat(A); 6349 auto Match2 = matchSHFLPat(B); 6350 6351 // If neither matched, we failed. 6352 if (!Match1 && !Match2) 6353 return SDValue(); 6354 6355 // We had at least one match. if one failed, try the remaining C operand. 6356 if (!Match1) { 6357 std::swap(A, C); 6358 Match1 = matchSHFLPat(A); 6359 if (!Match1) 6360 return SDValue(); 6361 } else if (!Match2) { 6362 std::swap(B, C); 6363 Match2 = matchSHFLPat(B); 6364 if (!Match2) 6365 return SDValue(); 6366 } 6367 assert(Match1 && Match2); 6368 6369 // Make sure our matches pair up. 6370 if (!Match1->formsPairWith(*Match2)) 6371 return SDValue(); 6372 6373 // All the remains is to make sure C is an AND with the same input, that masks 6374 // out the bits that are being shuffled. 6375 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6376 C.getOperand(0) != Match1->Op) 6377 return SDValue(); 6378 6379 uint64_t Mask = C.getConstantOperandVal(1); 6380 6381 static const uint64_t BitmanipMasks[] = { 6382 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6383 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6384 }; 6385 6386 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6387 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6388 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6389 6390 if (Mask != ExpMask) 6391 return SDValue(); 6392 6393 SDLoc DL(Op); 6394 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6395 DAG.getConstant(Match1->ShAmt, DL, VT)); 6396 } 6397 6398 // Optimize (add (shl x, c0), (shl y, c1)) -> 6399 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6400 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6401 const RISCVSubtarget &Subtarget) { 6402 // Perform this optimization only in the zba extension. 6403 if (!Subtarget.hasStdExtZba()) 6404 return SDValue(); 6405 6406 // Skip for vector types and larger types. 6407 EVT VT = N->getValueType(0); 6408 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6409 return SDValue(); 6410 6411 // The two operand nodes must be SHL and have no other use. 6412 SDValue N0 = N->getOperand(0); 6413 SDValue N1 = N->getOperand(1); 6414 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6415 !N0->hasOneUse() || !N1->hasOneUse()) 6416 return SDValue(); 6417 6418 // Check c0 and c1. 6419 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6420 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6421 if (!N0C || !N1C) 6422 return SDValue(); 6423 int64_t C0 = N0C->getSExtValue(); 6424 int64_t C1 = N1C->getSExtValue(); 6425 if (C0 <= 0 || C1 <= 0) 6426 return SDValue(); 6427 6428 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6429 int64_t Bits = std::min(C0, C1); 6430 int64_t Diff = std::abs(C0 - C1); 6431 if (Diff != 1 && Diff != 2 && Diff != 3) 6432 return SDValue(); 6433 6434 // Build nodes. 6435 SDLoc DL(N); 6436 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6437 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6438 SDValue NA0 = 6439 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6440 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6441 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6442 } 6443 6444 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6445 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6446 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6447 // not undo itself, but they are redundant. 6448 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6449 SDValue Src = N->getOperand(0); 6450 6451 if (Src.getOpcode() != N->getOpcode()) 6452 return SDValue(); 6453 6454 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6455 !isa<ConstantSDNode>(Src.getOperand(1))) 6456 return SDValue(); 6457 6458 unsigned ShAmt1 = N->getConstantOperandVal(1); 6459 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6460 Src = Src.getOperand(0); 6461 6462 unsigned CombinedShAmt; 6463 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6464 CombinedShAmt = ShAmt1 | ShAmt2; 6465 else 6466 CombinedShAmt = ShAmt1 ^ ShAmt2; 6467 6468 if (CombinedShAmt == 0) 6469 return Src; 6470 6471 SDLoc DL(N); 6472 return DAG.getNode( 6473 N->getOpcode(), DL, N->getValueType(0), Src, 6474 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6475 } 6476 6477 // Combine a constant select operand into its use: 6478 // 6479 // (and (select cond, -1, c), x) 6480 // -> (select cond, x, (and x, c)) [AllOnes=1] 6481 // (or (select cond, 0, c), x) 6482 // -> (select cond, x, (or x, c)) [AllOnes=0] 6483 // (xor (select cond, 0, c), x) 6484 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6485 // (add (select cond, 0, c), x) 6486 // -> (select cond, x, (add x, c)) [AllOnes=0] 6487 // (sub x, (select cond, 0, c)) 6488 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6489 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6490 SelectionDAG &DAG, bool AllOnes) { 6491 EVT VT = N->getValueType(0); 6492 6493 // Skip vectors. 6494 if (VT.isVector()) 6495 return SDValue(); 6496 6497 if ((Slct.getOpcode() != ISD::SELECT && 6498 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6499 !Slct.hasOneUse()) 6500 return SDValue(); 6501 6502 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6503 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6504 }; 6505 6506 bool SwapSelectOps; 6507 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6508 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6509 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6510 SDValue NonConstantVal; 6511 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6512 SwapSelectOps = false; 6513 NonConstantVal = FalseVal; 6514 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6515 SwapSelectOps = true; 6516 NonConstantVal = TrueVal; 6517 } else 6518 return SDValue(); 6519 6520 // Slct is now know to be the desired identity constant when CC is true. 6521 TrueVal = OtherOp; 6522 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6523 // Unless SwapSelectOps says the condition should be false. 6524 if (SwapSelectOps) 6525 std::swap(TrueVal, FalseVal); 6526 6527 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6528 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6529 {Slct.getOperand(0), Slct.getOperand(1), 6530 Slct.getOperand(2), TrueVal, FalseVal}); 6531 6532 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6533 {Slct.getOperand(0), TrueVal, FalseVal}); 6534 } 6535 6536 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6537 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6538 bool AllOnes) { 6539 SDValue N0 = N->getOperand(0); 6540 SDValue N1 = N->getOperand(1); 6541 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6542 return Result; 6543 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6544 return Result; 6545 return SDValue(); 6546 } 6547 6548 // Transform (add (mul x, c0), c1) -> 6549 // (add (mul (add x, c1/c0), c0), c1%c0). 6550 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6551 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6552 // to an infinite loop in DAGCombine if transformed. 6553 // Or transform (add (mul x, c0), c1) -> 6554 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6555 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6556 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6557 // lead to an infinite loop in DAGCombine if transformed. 6558 // Or transform (add (mul x, c0), c1) -> 6559 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6560 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6561 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6562 // lead to an infinite loop in DAGCombine if transformed. 6563 // Or transform (add (mul x, c0), c1) -> 6564 // (mul (add x, c1/c0), c0). 6565 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6566 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6567 const RISCVSubtarget &Subtarget) { 6568 // Skip for vector types and larger types. 6569 EVT VT = N->getValueType(0); 6570 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6571 return SDValue(); 6572 // The first operand node must be a MUL and has no other use. 6573 SDValue N0 = N->getOperand(0); 6574 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6575 return SDValue(); 6576 // Check if c0 and c1 match above conditions. 6577 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6578 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6579 if (!N0C || !N1C) 6580 return SDValue(); 6581 int64_t C0 = N0C->getSExtValue(); 6582 int64_t C1 = N1C->getSExtValue(); 6583 int64_t CA, CB; 6584 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6585 return SDValue(); 6586 // Search for proper CA (non-zero) and CB that both are simm12. 6587 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6588 !isInt<12>(C0 * (C1 / C0))) { 6589 CA = C1 / C0; 6590 CB = C1 % C0; 6591 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6592 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6593 CA = C1 / C0 + 1; 6594 CB = C1 % C0 - C0; 6595 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6596 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6597 CA = C1 / C0 - 1; 6598 CB = C1 % C0 + C0; 6599 } else 6600 return SDValue(); 6601 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6602 SDLoc DL(N); 6603 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6604 DAG.getConstant(CA, DL, VT)); 6605 SDValue New1 = 6606 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6607 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6608 } 6609 6610 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6611 const RISCVSubtarget &Subtarget) { 6612 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6613 return V; 6614 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6615 return V; 6616 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6617 // (select lhs, rhs, cc, x, (add x, y)) 6618 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6619 } 6620 6621 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6622 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6623 // (select lhs, rhs, cc, x, (sub x, y)) 6624 SDValue N0 = N->getOperand(0); 6625 SDValue N1 = N->getOperand(1); 6626 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6627 } 6628 6629 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6630 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6631 // (select lhs, rhs, cc, x, (and x, y)) 6632 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6633 } 6634 6635 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6636 const RISCVSubtarget &Subtarget) { 6637 if (Subtarget.hasStdExtZbp()) { 6638 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6639 return GREV; 6640 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6641 return GORC; 6642 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6643 return SHFL; 6644 } 6645 6646 // fold (or (select cond, 0, y), x) -> 6647 // (select cond, x, (or x, y)) 6648 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6649 } 6650 6651 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6652 // fold (xor (select cond, 0, y), x) -> 6653 // (select cond, x, (xor x, y)) 6654 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6655 } 6656 6657 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6658 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6659 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6660 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6661 // ADDW/SUBW/MULW. 6662 static SDValue performANY_EXTENDCombine(SDNode *N, 6663 TargetLowering::DAGCombinerInfo &DCI, 6664 const RISCVSubtarget &Subtarget) { 6665 if (!Subtarget.is64Bit()) 6666 return SDValue(); 6667 6668 SelectionDAG &DAG = DCI.DAG; 6669 6670 SDValue Src = N->getOperand(0); 6671 EVT VT = N->getValueType(0); 6672 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6673 return SDValue(); 6674 6675 // The opcode must be one that can implicitly sign_extend. 6676 // FIXME: Additional opcodes. 6677 switch (Src.getOpcode()) { 6678 default: 6679 return SDValue(); 6680 case ISD::MUL: 6681 if (!Subtarget.hasStdExtM()) 6682 return SDValue(); 6683 LLVM_FALLTHROUGH; 6684 case ISD::ADD: 6685 case ISD::SUB: 6686 break; 6687 } 6688 6689 // Only handle cases where the result is used by a CopyToReg. That likely 6690 // means the value is a liveout of the basic block. This helps prevent 6691 // infinite combine loops like PR51206. 6692 if (none_of(N->uses(), 6693 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6694 return SDValue(); 6695 6696 SmallVector<SDNode *, 4> SetCCs; 6697 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6698 UE = Src.getNode()->use_end(); 6699 UI != UE; ++UI) { 6700 SDNode *User = *UI; 6701 if (User == N) 6702 continue; 6703 if (UI.getUse().getResNo() != Src.getResNo()) 6704 continue; 6705 // All i32 setccs are legalized by sign extending operands. 6706 if (User->getOpcode() == ISD::SETCC) { 6707 SetCCs.push_back(User); 6708 continue; 6709 } 6710 // We don't know if we can extend this user. 6711 break; 6712 } 6713 6714 // If we don't have any SetCCs, this isn't worthwhile. 6715 if (SetCCs.empty()) 6716 return SDValue(); 6717 6718 SDLoc DL(N); 6719 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6720 DCI.CombineTo(N, SExt); 6721 6722 // Promote all the setccs. 6723 for (SDNode *SetCC : SetCCs) { 6724 SmallVector<SDValue, 4> Ops; 6725 6726 for (unsigned j = 0; j != 2; ++j) { 6727 SDValue SOp = SetCC->getOperand(j); 6728 if (SOp == Src) 6729 Ops.push_back(SExt); 6730 else 6731 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6732 } 6733 6734 Ops.push_back(SetCC->getOperand(2)); 6735 DCI.CombineTo(SetCC, 6736 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6737 } 6738 return SDValue(N, 0); 6739 } 6740 6741 // Try to form VWMUL or VWMULU. 6742 // FIXME: Support VWMULSU. 6743 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6744 SelectionDAG &DAG) { 6745 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6746 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6747 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6748 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6749 return SDValue(); 6750 6751 SDValue Mask = N->getOperand(2); 6752 SDValue VL = N->getOperand(3); 6753 6754 // Make sure the mask and VL match. 6755 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6756 return SDValue(); 6757 6758 MVT VT = N->getSimpleValueType(0); 6759 6760 // Determine the narrow size for a widening multiply. 6761 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 6762 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 6763 VT.getVectorElementCount()); 6764 6765 SDLoc DL(N); 6766 6767 // See if the other operand is the same opcode. 6768 if (Op0.getOpcode() == Op1.getOpcode()) { 6769 if (!Op1.hasOneUse()) 6770 return SDValue(); 6771 6772 // Make sure the mask and VL match. 6773 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 6774 return SDValue(); 6775 6776 Op1 = Op1.getOperand(0); 6777 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 6778 // The operand is a splat of a scalar. 6779 6780 // The VL must be the same. 6781 if (Op1.getOperand(1) != VL) 6782 return SDValue(); 6783 6784 // Get the scalar value. 6785 Op1 = Op1.getOperand(0); 6786 6787 // See if have enough sign bits or zero bits in the scalar to use a 6788 // widening multiply by splatting to smaller element size. 6789 unsigned EltBits = VT.getScalarSizeInBits(); 6790 unsigned ScalarBits = Op1.getValueSizeInBits(); 6791 // Make sure we're getting all element bits from the scalar register. 6792 // FIXME: Support implicit sign extension of vmv.v.x? 6793 if (ScalarBits < EltBits) 6794 return SDValue(); 6795 6796 if (IsSignExt) { 6797 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 6798 return SDValue(); 6799 } else { 6800 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 6801 if (!DAG.MaskedValueIsZero(Op1, Mask)) 6802 return SDValue(); 6803 } 6804 6805 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 6806 } else 6807 return SDValue(); 6808 6809 Op0 = Op0.getOperand(0); 6810 6811 // Re-introduce narrower extends if needed. 6812 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 6813 if (Op0.getValueType() != NarrowVT) 6814 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 6815 if (Op1.getValueType() != NarrowVT) 6816 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 6817 6818 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 6819 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 6820 } 6821 6822 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 6823 DAGCombinerInfo &DCI) const { 6824 SelectionDAG &DAG = DCI.DAG; 6825 6826 // Helper to call SimplifyDemandedBits on an operand of N where only some low 6827 // bits are demanded. N will be added to the Worklist if it was not deleted. 6828 // Caller should return SDValue(N, 0) if this returns true. 6829 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 6830 SDValue Op = N->getOperand(OpNo); 6831 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 6832 if (!SimplifyDemandedBits(Op, Mask, DCI)) 6833 return false; 6834 6835 if (N->getOpcode() != ISD::DELETED_NODE) 6836 DCI.AddToWorklist(N); 6837 return true; 6838 }; 6839 6840 switch (N->getOpcode()) { 6841 default: 6842 break; 6843 case RISCVISD::SplitF64: { 6844 SDValue Op0 = N->getOperand(0); 6845 // If the input to SplitF64 is just BuildPairF64 then the operation is 6846 // redundant. Instead, use BuildPairF64's operands directly. 6847 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 6848 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 6849 6850 SDLoc DL(N); 6851 6852 // It's cheaper to materialise two 32-bit integers than to load a double 6853 // from the constant pool and transfer it to integer registers through the 6854 // stack. 6855 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 6856 APInt V = C->getValueAPF().bitcastToAPInt(); 6857 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 6858 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 6859 return DCI.CombineTo(N, Lo, Hi); 6860 } 6861 6862 // This is a target-specific version of a DAGCombine performed in 6863 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6864 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6865 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6866 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6867 !Op0.getNode()->hasOneUse()) 6868 break; 6869 SDValue NewSplitF64 = 6870 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 6871 Op0.getOperand(0)); 6872 SDValue Lo = NewSplitF64.getValue(0); 6873 SDValue Hi = NewSplitF64.getValue(1); 6874 APInt SignBit = APInt::getSignMask(32); 6875 if (Op0.getOpcode() == ISD::FNEG) { 6876 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 6877 DAG.getConstant(SignBit, DL, MVT::i32)); 6878 return DCI.CombineTo(N, Lo, NewHi); 6879 } 6880 assert(Op0.getOpcode() == ISD::FABS); 6881 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 6882 DAG.getConstant(~SignBit, DL, MVT::i32)); 6883 return DCI.CombineTo(N, Lo, NewHi); 6884 } 6885 case RISCVISD::SLLW: 6886 case RISCVISD::SRAW: 6887 case RISCVISD::SRLW: 6888 case RISCVISD::ROLW: 6889 case RISCVISD::RORW: { 6890 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6891 if (SimplifyDemandedLowBitsHelper(0, 32) || 6892 SimplifyDemandedLowBitsHelper(1, 5)) 6893 return SDValue(N, 0); 6894 break; 6895 } 6896 case RISCVISD::CLZW: 6897 case RISCVISD::CTZW: { 6898 // Only the lower 32 bits of the first operand are read 6899 if (SimplifyDemandedLowBitsHelper(0, 32)) 6900 return SDValue(N, 0); 6901 break; 6902 } 6903 case RISCVISD::FSL: 6904 case RISCVISD::FSR: { 6905 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 6906 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 6907 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6908 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 6909 return SDValue(N, 0); 6910 break; 6911 } 6912 case RISCVISD::FSLW: 6913 case RISCVISD::FSRW: { 6914 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 6915 // read. 6916 if (SimplifyDemandedLowBitsHelper(0, 32) || 6917 SimplifyDemandedLowBitsHelper(1, 32) || 6918 SimplifyDemandedLowBitsHelper(2, 6)) 6919 return SDValue(N, 0); 6920 break; 6921 } 6922 case RISCVISD::GREV: 6923 case RISCVISD::GORC: { 6924 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 6925 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6926 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6927 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 6928 return SDValue(N, 0); 6929 6930 return combineGREVI_GORCI(N, DCI.DAG); 6931 } 6932 case RISCVISD::GREVW: 6933 case RISCVISD::GORCW: { 6934 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6935 if (SimplifyDemandedLowBitsHelper(0, 32) || 6936 SimplifyDemandedLowBitsHelper(1, 5)) 6937 return SDValue(N, 0); 6938 6939 return combineGREVI_GORCI(N, DCI.DAG); 6940 } 6941 case RISCVISD::SHFL: 6942 case RISCVISD::UNSHFL: { 6943 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 6944 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6945 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6946 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 6947 return SDValue(N, 0); 6948 6949 break; 6950 } 6951 case RISCVISD::SHFLW: 6952 case RISCVISD::UNSHFLW: { 6953 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 6954 SDValue LHS = N->getOperand(0); 6955 SDValue RHS = N->getOperand(1); 6956 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 6957 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 6958 if (SimplifyDemandedLowBitsHelper(0, 32) || 6959 SimplifyDemandedLowBitsHelper(1, 4)) 6960 return SDValue(N, 0); 6961 6962 break; 6963 } 6964 case RISCVISD::BCOMPRESSW: 6965 case RISCVISD::BDECOMPRESSW: { 6966 // Only the lower 32 bits of LHS and RHS are read. 6967 if (SimplifyDemandedLowBitsHelper(0, 32) || 6968 SimplifyDemandedLowBitsHelper(1, 32)) 6969 return SDValue(N, 0); 6970 6971 break; 6972 } 6973 case RISCVISD::FMV_X_ANYEXTH: 6974 case RISCVISD::FMV_X_ANYEXTW_RV64: { 6975 SDLoc DL(N); 6976 SDValue Op0 = N->getOperand(0); 6977 MVT VT = N->getSimpleValueType(0); 6978 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 6979 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 6980 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 6981 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 6982 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 6983 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 6984 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 6985 assert(Op0.getOperand(0).getValueType() == VT && 6986 "Unexpected value type!"); 6987 return Op0.getOperand(0); 6988 } 6989 6990 // This is a target-specific version of a DAGCombine performed in 6991 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6992 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6993 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6994 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6995 !Op0.getNode()->hasOneUse()) 6996 break; 6997 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 6998 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 6999 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7000 if (Op0.getOpcode() == ISD::FNEG) 7001 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7002 DAG.getConstant(SignBit, DL, VT)); 7003 7004 assert(Op0.getOpcode() == ISD::FABS); 7005 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7006 DAG.getConstant(~SignBit, DL, VT)); 7007 } 7008 case ISD::ADD: 7009 return performADDCombine(N, DAG, Subtarget); 7010 case ISD::SUB: 7011 return performSUBCombine(N, DAG); 7012 case ISD::AND: 7013 return performANDCombine(N, DAG); 7014 case ISD::OR: 7015 return performORCombine(N, DAG, Subtarget); 7016 case ISD::XOR: 7017 return performXORCombine(N, DAG); 7018 case ISD::ANY_EXTEND: 7019 return performANY_EXTENDCombine(N, DCI, Subtarget); 7020 case ISD::ZERO_EXTEND: 7021 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7022 // type legalization. This is safe because fp_to_uint produces poison if 7023 // it overflows. 7024 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() && 7025 N->getOperand(0).getOpcode() == ISD::FP_TO_UINT && 7026 isTypeLegal(N->getOperand(0).getOperand(0).getValueType())) 7027 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7028 N->getOperand(0).getOperand(0)); 7029 return SDValue(); 7030 case RISCVISD::SELECT_CC: { 7031 // Transform 7032 SDValue LHS = N->getOperand(0); 7033 SDValue RHS = N->getOperand(1); 7034 SDValue TrueV = N->getOperand(3); 7035 SDValue FalseV = N->getOperand(4); 7036 7037 // If the True and False values are the same, we don't need a select_cc. 7038 if (TrueV == FalseV) 7039 return TrueV; 7040 7041 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7042 if (!ISD::isIntEqualitySetCC(CCVal)) 7043 break; 7044 7045 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7046 // (select_cc X, Y, lt, trueV, falseV) 7047 // Sometimes the setcc is introduced after select_cc has been formed. 7048 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7049 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7050 // If we're looking for eq 0 instead of ne 0, we need to invert the 7051 // condition. 7052 bool Invert = CCVal == ISD::SETEQ; 7053 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7054 if (Invert) 7055 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7056 7057 SDLoc DL(N); 7058 RHS = LHS.getOperand(1); 7059 LHS = LHS.getOperand(0); 7060 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7061 7062 SDValue TargetCC = DAG.getCondCode(CCVal); 7063 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7064 {LHS, RHS, TargetCC, TrueV, FalseV}); 7065 } 7066 7067 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7068 // (select_cc X, Y, eq/ne, trueV, falseV) 7069 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7070 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7071 {LHS.getOperand(0), LHS.getOperand(1), 7072 N->getOperand(2), TrueV, FalseV}); 7073 // (select_cc X, 1, setne, trueV, falseV) -> 7074 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7075 // This can occur when legalizing some floating point comparisons. 7076 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7077 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7078 SDLoc DL(N); 7079 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7080 SDValue TargetCC = DAG.getCondCode(CCVal); 7081 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7082 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7083 {LHS, RHS, TargetCC, TrueV, FalseV}); 7084 } 7085 7086 break; 7087 } 7088 case RISCVISD::BR_CC: { 7089 SDValue LHS = N->getOperand(1); 7090 SDValue RHS = N->getOperand(2); 7091 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7092 if (!ISD::isIntEqualitySetCC(CCVal)) 7093 break; 7094 7095 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7096 // (br_cc X, Y, lt, dest) 7097 // Sometimes the setcc is introduced after br_cc has been formed. 7098 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7099 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7100 // If we're looking for eq 0 instead of ne 0, we need to invert the 7101 // condition. 7102 bool Invert = CCVal == ISD::SETEQ; 7103 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7104 if (Invert) 7105 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7106 7107 SDLoc DL(N); 7108 RHS = LHS.getOperand(1); 7109 LHS = LHS.getOperand(0); 7110 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7111 7112 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7113 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7114 N->getOperand(4)); 7115 } 7116 7117 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7118 // (br_cc X, Y, eq/ne, trueV, falseV) 7119 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7120 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7121 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7122 N->getOperand(3), N->getOperand(4)); 7123 7124 // (br_cc X, 1, setne, br_cc) -> 7125 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7126 // This can occur when legalizing some floating point comparisons. 7127 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7128 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7129 SDLoc DL(N); 7130 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7131 SDValue TargetCC = DAG.getCondCode(CCVal); 7132 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7133 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7134 N->getOperand(0), LHS, RHS, TargetCC, 7135 N->getOperand(4)); 7136 } 7137 break; 7138 } 7139 case ISD::FCOPYSIGN: { 7140 EVT VT = N->getValueType(0); 7141 if (!VT.isVector()) 7142 break; 7143 // There is a form of VFSGNJ which injects the negated sign of its second 7144 // operand. Try and bubble any FNEG up after the extend/round to produce 7145 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7146 // TRUNC=1. 7147 SDValue In2 = N->getOperand(1); 7148 // Avoid cases where the extend/round has multiple uses, as duplicating 7149 // those is typically more expensive than removing a fneg. 7150 if (!In2.hasOneUse()) 7151 break; 7152 if (In2.getOpcode() != ISD::FP_EXTEND && 7153 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7154 break; 7155 In2 = In2.getOperand(0); 7156 if (In2.getOpcode() != ISD::FNEG) 7157 break; 7158 SDLoc DL(N); 7159 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7160 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7161 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7162 } 7163 case ISD::MGATHER: 7164 case ISD::MSCATTER: 7165 case ISD::VP_GATHER: 7166 case ISD::VP_SCATTER: { 7167 if (!DCI.isBeforeLegalize()) 7168 break; 7169 SDValue Index, ScaleOp; 7170 bool IsIndexScaled = false; 7171 bool IsIndexSigned = false; 7172 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7173 Index = VPGSN->getIndex(); 7174 ScaleOp = VPGSN->getScale(); 7175 IsIndexScaled = VPGSN->isIndexScaled(); 7176 IsIndexSigned = VPGSN->isIndexSigned(); 7177 } else { 7178 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7179 Index = MGSN->getIndex(); 7180 ScaleOp = MGSN->getScale(); 7181 IsIndexScaled = MGSN->isIndexScaled(); 7182 IsIndexSigned = MGSN->isIndexSigned(); 7183 } 7184 EVT IndexVT = Index.getValueType(); 7185 MVT XLenVT = Subtarget.getXLenVT(); 7186 // RISCV indexed loads only support the "unsigned unscaled" addressing 7187 // mode, so anything else must be manually legalized. 7188 bool NeedsIdxLegalization = 7189 IsIndexScaled || 7190 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7191 if (!NeedsIdxLegalization) 7192 break; 7193 7194 SDLoc DL(N); 7195 7196 // Any index legalization should first promote to XLenVT, so we don't lose 7197 // bits when scaling. This may create an illegal index type so we let 7198 // LLVM's legalization take care of the splitting. 7199 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7200 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7201 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7202 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7203 DL, IndexVT, Index); 7204 } 7205 7206 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7207 if (IsIndexScaled && Scale != 1) { 7208 // Manually scale the indices by the element size. 7209 // TODO: Sanitize the scale operand here? 7210 // TODO: For VP nodes, should we use VP_SHL here? 7211 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7212 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7213 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7214 } 7215 7216 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7217 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7218 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7219 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7220 VPGN->getScale(), VPGN->getMask(), 7221 VPGN->getVectorLength()}, 7222 VPGN->getMemOperand(), NewIndexTy); 7223 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7224 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7225 {VPSN->getChain(), VPSN->getValue(), 7226 VPSN->getBasePtr(), Index, VPSN->getScale(), 7227 VPSN->getMask(), VPSN->getVectorLength()}, 7228 VPSN->getMemOperand(), NewIndexTy); 7229 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7230 return DAG.getMaskedGather( 7231 N->getVTList(), MGN->getMemoryVT(), DL, 7232 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7233 MGN->getBasePtr(), Index, MGN->getScale()}, 7234 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7235 const auto *MSN = cast<MaskedScatterSDNode>(N); 7236 return DAG.getMaskedScatter( 7237 N->getVTList(), MSN->getMemoryVT(), DL, 7238 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7239 Index, MSN->getScale()}, 7240 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7241 } 7242 case RISCVISD::SRA_VL: 7243 case RISCVISD::SRL_VL: 7244 case RISCVISD::SHL_VL: { 7245 SDValue ShAmt = N->getOperand(1); 7246 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7247 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7248 SDLoc DL(N); 7249 SDValue VL = N->getOperand(3); 7250 EVT VT = N->getValueType(0); 7251 ShAmt = 7252 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7253 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7254 N->getOperand(2), N->getOperand(3)); 7255 } 7256 break; 7257 } 7258 case ISD::SRA: 7259 case ISD::SRL: 7260 case ISD::SHL: { 7261 SDValue ShAmt = N->getOperand(1); 7262 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7263 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7264 SDLoc DL(N); 7265 EVT VT = N->getValueType(0); 7266 ShAmt = 7267 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7268 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7269 } 7270 break; 7271 } 7272 case RISCVISD::MUL_VL: { 7273 SDValue Op0 = N->getOperand(0); 7274 SDValue Op1 = N->getOperand(1); 7275 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7276 return V; 7277 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7278 return V; 7279 return SDValue(); 7280 } 7281 case ISD::STORE: { 7282 auto *Store = cast<StoreSDNode>(N); 7283 SDValue Val = Store->getValue(); 7284 // Combine store of vmv.x.s to vse with VL of 1. 7285 // FIXME: Support FP. 7286 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7287 SDValue Src = Val.getOperand(0); 7288 EVT VecVT = Src.getValueType(); 7289 EVT MemVT = Store->getMemoryVT(); 7290 // The memory VT and the element type must match. 7291 if (VecVT.getVectorElementType() == MemVT) { 7292 SDLoc DL(N); 7293 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7294 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7295 DAG.getConstant(1, DL, MaskVT), 7296 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7297 Store->getPointerInfo(), 7298 Store->getOriginalAlign(), 7299 Store->getMemOperand()->getFlags()); 7300 } 7301 } 7302 7303 break; 7304 } 7305 } 7306 7307 return SDValue(); 7308 } 7309 7310 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7311 const SDNode *N, CombineLevel Level) const { 7312 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7313 // materialised in fewer instructions than `(OP _, c1)`: 7314 // 7315 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7316 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7317 SDValue N0 = N->getOperand(0); 7318 EVT Ty = N0.getValueType(); 7319 if (Ty.isScalarInteger() && 7320 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7321 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7322 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7323 if (C1 && C2) { 7324 const APInt &C1Int = C1->getAPIntValue(); 7325 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7326 7327 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7328 // and the combine should happen, to potentially allow further combines 7329 // later. 7330 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7331 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7332 return true; 7333 7334 // We can materialise `c1` in an add immediate, so it's "free", and the 7335 // combine should be prevented. 7336 if (C1Int.getMinSignedBits() <= 64 && 7337 isLegalAddImmediate(C1Int.getSExtValue())) 7338 return false; 7339 7340 // Neither constant will fit into an immediate, so find materialisation 7341 // costs. 7342 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7343 Subtarget.getFeatureBits(), 7344 /*CompressionCost*/true); 7345 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7346 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7347 /*CompressionCost*/true); 7348 7349 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7350 // combine should be prevented. 7351 if (C1Cost < ShiftedC1Cost) 7352 return false; 7353 } 7354 } 7355 return true; 7356 } 7357 7358 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7359 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7360 TargetLoweringOpt &TLO) const { 7361 // Delay this optimization as late as possible. 7362 if (!TLO.LegalOps) 7363 return false; 7364 7365 EVT VT = Op.getValueType(); 7366 if (VT.isVector()) 7367 return false; 7368 7369 // Only handle AND for now. 7370 if (Op.getOpcode() != ISD::AND) 7371 return false; 7372 7373 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7374 if (!C) 7375 return false; 7376 7377 const APInt &Mask = C->getAPIntValue(); 7378 7379 // Clear all non-demanded bits initially. 7380 APInt ShrunkMask = Mask & DemandedBits; 7381 7382 // Try to make a smaller immediate by setting undemanded bits. 7383 7384 APInt ExpandedMask = Mask | ~DemandedBits; 7385 7386 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7387 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7388 }; 7389 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7390 if (NewMask == Mask) 7391 return true; 7392 SDLoc DL(Op); 7393 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7394 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7395 return TLO.CombineTo(Op, NewOp); 7396 }; 7397 7398 // If the shrunk mask fits in sign extended 12 bits, let the target 7399 // independent code apply it. 7400 if (ShrunkMask.isSignedIntN(12)) 7401 return false; 7402 7403 // Preserve (and X, 0xffff) when zext.h is supported. 7404 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7405 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7406 if (IsLegalMask(NewMask)) 7407 return UseMask(NewMask); 7408 } 7409 7410 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7411 if (VT == MVT::i64) { 7412 APInt NewMask = APInt(64, 0xffffffff); 7413 if (IsLegalMask(NewMask)) 7414 return UseMask(NewMask); 7415 } 7416 7417 // For the remaining optimizations, we need to be able to make a negative 7418 // number through a combination of mask and undemanded bits. 7419 if (!ExpandedMask.isNegative()) 7420 return false; 7421 7422 // What is the fewest number of bits we need to represent the negative number. 7423 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7424 7425 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7426 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7427 APInt NewMask = ShrunkMask; 7428 if (MinSignedBits <= 12) 7429 NewMask.setBitsFrom(11); 7430 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7431 NewMask.setBitsFrom(31); 7432 else 7433 return false; 7434 7435 // Check that our new mask is a subset of the demanded mask. 7436 assert(IsLegalMask(NewMask)); 7437 return UseMask(NewMask); 7438 } 7439 7440 static void computeGREV(APInt &Src, unsigned ShAmt) { 7441 ShAmt &= Src.getBitWidth() - 1; 7442 uint64_t x = Src.getZExtValue(); 7443 if (ShAmt & 1) 7444 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7445 if (ShAmt & 2) 7446 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7447 if (ShAmt & 4) 7448 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7449 if (ShAmt & 8) 7450 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7451 if (ShAmt & 16) 7452 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7453 if (ShAmt & 32) 7454 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7455 Src = x; 7456 } 7457 7458 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7459 KnownBits &Known, 7460 const APInt &DemandedElts, 7461 const SelectionDAG &DAG, 7462 unsigned Depth) const { 7463 unsigned BitWidth = Known.getBitWidth(); 7464 unsigned Opc = Op.getOpcode(); 7465 assert((Opc >= ISD::BUILTIN_OP_END || 7466 Opc == ISD::INTRINSIC_WO_CHAIN || 7467 Opc == ISD::INTRINSIC_W_CHAIN || 7468 Opc == ISD::INTRINSIC_VOID) && 7469 "Should use MaskedValueIsZero if you don't know whether Op" 7470 " is a target node!"); 7471 7472 Known.resetAll(); 7473 switch (Opc) { 7474 default: break; 7475 case RISCVISD::SELECT_CC: { 7476 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7477 // If we don't know any bits, early out. 7478 if (Known.isUnknown()) 7479 break; 7480 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7481 7482 // Only known if known in both the LHS and RHS. 7483 Known = KnownBits::commonBits(Known, Known2); 7484 break; 7485 } 7486 case RISCVISD::REMUW: { 7487 KnownBits Known2; 7488 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7489 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7490 // We only care about the lower 32 bits. 7491 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7492 // Restore the original width by sign extending. 7493 Known = Known.sext(BitWidth); 7494 break; 7495 } 7496 case RISCVISD::DIVUW: { 7497 KnownBits Known2; 7498 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7499 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7500 // We only care about the lower 32 bits. 7501 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7502 // Restore the original width by sign extending. 7503 Known = Known.sext(BitWidth); 7504 break; 7505 } 7506 case RISCVISD::CTZW: { 7507 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7508 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7509 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7510 Known.Zero.setBitsFrom(LowBits); 7511 break; 7512 } 7513 case RISCVISD::CLZW: { 7514 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7515 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7516 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7517 Known.Zero.setBitsFrom(LowBits); 7518 break; 7519 } 7520 case RISCVISD::GREV: 7521 case RISCVISD::GREVW: { 7522 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7523 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7524 if (Opc == RISCVISD::GREVW) 7525 Known = Known.trunc(32); 7526 unsigned ShAmt = C->getZExtValue(); 7527 computeGREV(Known.Zero, ShAmt); 7528 computeGREV(Known.One, ShAmt); 7529 if (Opc == RISCVISD::GREVW) 7530 Known = Known.sext(BitWidth); 7531 } 7532 break; 7533 } 7534 case RISCVISD::READ_VLENB: 7535 // We assume VLENB is at least 16 bytes. 7536 Known.Zero.setLowBits(4); 7537 // We assume VLENB is no more than 65536 / 8 bytes. 7538 Known.Zero.setBitsFrom(14); 7539 break; 7540 case ISD::INTRINSIC_W_CHAIN: { 7541 unsigned IntNo = Op.getConstantOperandVal(1); 7542 switch (IntNo) { 7543 default: 7544 // We can't do anything for most intrinsics. 7545 break; 7546 case Intrinsic::riscv_vsetvli: 7547 case Intrinsic::riscv_vsetvlimax: 7548 // Assume that VL output is positive and would fit in an int32_t. 7549 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7550 if (BitWidth >= 32) 7551 Known.Zero.setBitsFrom(31); 7552 break; 7553 } 7554 break; 7555 } 7556 } 7557 } 7558 7559 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7560 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7561 unsigned Depth) const { 7562 switch (Op.getOpcode()) { 7563 default: 7564 break; 7565 case RISCVISD::SELECT_CC: { 7566 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7567 if (Tmp == 1) return 1; // Early out. 7568 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7569 return std::min(Tmp, Tmp2); 7570 } 7571 case RISCVISD::SLLW: 7572 case RISCVISD::SRAW: 7573 case RISCVISD::SRLW: 7574 case RISCVISD::DIVW: 7575 case RISCVISD::DIVUW: 7576 case RISCVISD::REMUW: 7577 case RISCVISD::ROLW: 7578 case RISCVISD::RORW: 7579 case RISCVISD::GREVW: 7580 case RISCVISD::GORCW: 7581 case RISCVISD::FSLW: 7582 case RISCVISD::FSRW: 7583 case RISCVISD::SHFLW: 7584 case RISCVISD::UNSHFLW: 7585 case RISCVISD::BCOMPRESSW: 7586 case RISCVISD::BDECOMPRESSW: 7587 case RISCVISD::FCVT_W_RTZ_RV64: 7588 case RISCVISD::FCVT_WU_RTZ_RV64: 7589 // TODO: As the result is sign-extended, this is conservatively correct. A 7590 // more precise answer could be calculated for SRAW depending on known 7591 // bits in the shift amount. 7592 return 33; 7593 case RISCVISD::SHFL: 7594 case RISCVISD::UNSHFL: { 7595 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7596 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7597 // will stay within the upper 32 bits. If there were more than 32 sign bits 7598 // before there will be at least 33 sign bits after. 7599 if (Op.getValueType() == MVT::i64 && 7600 isa<ConstantSDNode>(Op.getOperand(1)) && 7601 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7602 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7603 if (Tmp > 32) 7604 return 33; 7605 } 7606 break; 7607 } 7608 case RISCVISD::VMV_X_S: 7609 // The number of sign bits of the scalar result is computed by obtaining the 7610 // element type of the input vector operand, subtracting its width from the 7611 // XLEN, and then adding one (sign bit within the element type). If the 7612 // element type is wider than XLen, the least-significant XLEN bits are 7613 // taken. 7614 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7615 return 1; 7616 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7617 } 7618 7619 return 1; 7620 } 7621 7622 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7623 MachineBasicBlock *BB) { 7624 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7625 7626 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7627 // Should the count have wrapped while it was being read, we need to try 7628 // again. 7629 // ... 7630 // read: 7631 // rdcycleh x3 # load high word of cycle 7632 // rdcycle x2 # load low word of cycle 7633 // rdcycleh x4 # load high word of cycle 7634 // bne x3, x4, read # check if high word reads match, otherwise try again 7635 // ... 7636 7637 MachineFunction &MF = *BB->getParent(); 7638 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7639 MachineFunction::iterator It = ++BB->getIterator(); 7640 7641 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7642 MF.insert(It, LoopMBB); 7643 7644 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7645 MF.insert(It, DoneMBB); 7646 7647 // Transfer the remainder of BB and its successor edges to DoneMBB. 7648 DoneMBB->splice(DoneMBB->begin(), BB, 7649 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7650 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7651 7652 BB->addSuccessor(LoopMBB); 7653 7654 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7655 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7656 Register LoReg = MI.getOperand(0).getReg(); 7657 Register HiReg = MI.getOperand(1).getReg(); 7658 DebugLoc DL = MI.getDebugLoc(); 7659 7660 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7661 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7662 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7663 .addReg(RISCV::X0); 7664 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7665 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7666 .addReg(RISCV::X0); 7667 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7668 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7669 .addReg(RISCV::X0); 7670 7671 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7672 .addReg(HiReg) 7673 .addReg(ReadAgainReg) 7674 .addMBB(LoopMBB); 7675 7676 LoopMBB->addSuccessor(LoopMBB); 7677 LoopMBB->addSuccessor(DoneMBB); 7678 7679 MI.eraseFromParent(); 7680 7681 return DoneMBB; 7682 } 7683 7684 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7685 MachineBasicBlock *BB) { 7686 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7687 7688 MachineFunction &MF = *BB->getParent(); 7689 DebugLoc DL = MI.getDebugLoc(); 7690 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7691 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7692 Register LoReg = MI.getOperand(0).getReg(); 7693 Register HiReg = MI.getOperand(1).getReg(); 7694 Register SrcReg = MI.getOperand(2).getReg(); 7695 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7696 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7697 7698 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7699 RI); 7700 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7701 MachineMemOperand *MMOLo = 7702 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7703 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7704 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7705 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7706 .addFrameIndex(FI) 7707 .addImm(0) 7708 .addMemOperand(MMOLo); 7709 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7710 .addFrameIndex(FI) 7711 .addImm(4) 7712 .addMemOperand(MMOHi); 7713 MI.eraseFromParent(); // The pseudo instruction is gone now. 7714 return BB; 7715 } 7716 7717 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7718 MachineBasicBlock *BB) { 7719 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7720 "Unexpected instruction"); 7721 7722 MachineFunction &MF = *BB->getParent(); 7723 DebugLoc DL = MI.getDebugLoc(); 7724 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7725 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7726 Register DstReg = MI.getOperand(0).getReg(); 7727 Register LoReg = MI.getOperand(1).getReg(); 7728 Register HiReg = MI.getOperand(2).getReg(); 7729 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7730 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7731 7732 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7733 MachineMemOperand *MMOLo = 7734 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7735 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7736 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7737 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7738 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7739 .addFrameIndex(FI) 7740 .addImm(0) 7741 .addMemOperand(MMOLo); 7742 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7743 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7744 .addFrameIndex(FI) 7745 .addImm(4) 7746 .addMemOperand(MMOHi); 7747 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7748 MI.eraseFromParent(); // The pseudo instruction is gone now. 7749 return BB; 7750 } 7751 7752 static bool isSelectPseudo(MachineInstr &MI) { 7753 switch (MI.getOpcode()) { 7754 default: 7755 return false; 7756 case RISCV::Select_GPR_Using_CC_GPR: 7757 case RISCV::Select_FPR16_Using_CC_GPR: 7758 case RISCV::Select_FPR32_Using_CC_GPR: 7759 case RISCV::Select_FPR64_Using_CC_GPR: 7760 return true; 7761 } 7762 } 7763 7764 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7765 MachineBasicBlock *BB, 7766 const RISCVSubtarget &Subtarget) { 7767 // To "insert" Select_* instructions, we actually have to insert the triangle 7768 // control-flow pattern. The incoming instructions know the destination vreg 7769 // to set, the condition code register to branch on, the true/false values to 7770 // select between, and the condcode to use to select the appropriate branch. 7771 // 7772 // We produce the following control flow: 7773 // HeadMBB 7774 // | \ 7775 // | IfFalseMBB 7776 // | / 7777 // TailMBB 7778 // 7779 // When we find a sequence of selects we attempt to optimize their emission 7780 // by sharing the control flow. Currently we only handle cases where we have 7781 // multiple selects with the exact same condition (same LHS, RHS and CC). 7782 // The selects may be interleaved with other instructions if the other 7783 // instructions meet some requirements we deem safe: 7784 // - They are debug instructions. Otherwise, 7785 // - They do not have side-effects, do not access memory and their inputs do 7786 // not depend on the results of the select pseudo-instructions. 7787 // The TrueV/FalseV operands of the selects cannot depend on the result of 7788 // previous selects in the sequence. 7789 // These conditions could be further relaxed. See the X86 target for a 7790 // related approach and more information. 7791 Register LHS = MI.getOperand(1).getReg(); 7792 Register RHS = MI.getOperand(2).getReg(); 7793 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 7794 7795 SmallVector<MachineInstr *, 4> SelectDebugValues; 7796 SmallSet<Register, 4> SelectDests; 7797 SelectDests.insert(MI.getOperand(0).getReg()); 7798 7799 MachineInstr *LastSelectPseudo = &MI; 7800 7801 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 7802 SequenceMBBI != E; ++SequenceMBBI) { 7803 if (SequenceMBBI->isDebugInstr()) 7804 continue; 7805 else if (isSelectPseudo(*SequenceMBBI)) { 7806 if (SequenceMBBI->getOperand(1).getReg() != LHS || 7807 SequenceMBBI->getOperand(2).getReg() != RHS || 7808 SequenceMBBI->getOperand(3).getImm() != CC || 7809 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 7810 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 7811 break; 7812 LastSelectPseudo = &*SequenceMBBI; 7813 SequenceMBBI->collectDebugValues(SelectDebugValues); 7814 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 7815 } else { 7816 if (SequenceMBBI->hasUnmodeledSideEffects() || 7817 SequenceMBBI->mayLoadOrStore()) 7818 break; 7819 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 7820 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 7821 })) 7822 break; 7823 } 7824 } 7825 7826 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 7827 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7828 DebugLoc DL = MI.getDebugLoc(); 7829 MachineFunction::iterator I = ++BB->getIterator(); 7830 7831 MachineBasicBlock *HeadMBB = BB; 7832 MachineFunction *F = BB->getParent(); 7833 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 7834 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 7835 7836 F->insert(I, IfFalseMBB); 7837 F->insert(I, TailMBB); 7838 7839 // Transfer debug instructions associated with the selects to TailMBB. 7840 for (MachineInstr *DebugInstr : SelectDebugValues) { 7841 TailMBB->push_back(DebugInstr->removeFromParent()); 7842 } 7843 7844 // Move all instructions after the sequence to TailMBB. 7845 TailMBB->splice(TailMBB->end(), HeadMBB, 7846 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 7847 // Update machine-CFG edges by transferring all successors of the current 7848 // block to the new block which will contain the Phi nodes for the selects. 7849 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 7850 // Set the successors for HeadMBB. 7851 HeadMBB->addSuccessor(IfFalseMBB); 7852 HeadMBB->addSuccessor(TailMBB); 7853 7854 // Insert appropriate branch. 7855 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 7856 .addReg(LHS) 7857 .addReg(RHS) 7858 .addMBB(TailMBB); 7859 7860 // IfFalseMBB just falls through to TailMBB. 7861 IfFalseMBB->addSuccessor(TailMBB); 7862 7863 // Create PHIs for all of the select pseudo-instructions. 7864 auto SelectMBBI = MI.getIterator(); 7865 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 7866 auto InsertionPoint = TailMBB->begin(); 7867 while (SelectMBBI != SelectEnd) { 7868 auto Next = std::next(SelectMBBI); 7869 if (isSelectPseudo(*SelectMBBI)) { 7870 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 7871 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 7872 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 7873 .addReg(SelectMBBI->getOperand(4).getReg()) 7874 .addMBB(HeadMBB) 7875 .addReg(SelectMBBI->getOperand(5).getReg()) 7876 .addMBB(IfFalseMBB); 7877 SelectMBBI->eraseFromParent(); 7878 } 7879 SelectMBBI = Next; 7880 } 7881 7882 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 7883 return TailMBB; 7884 } 7885 7886 MachineBasicBlock * 7887 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 7888 MachineBasicBlock *BB) const { 7889 switch (MI.getOpcode()) { 7890 default: 7891 llvm_unreachable("Unexpected instr type to insert"); 7892 case RISCV::ReadCycleWide: 7893 assert(!Subtarget.is64Bit() && 7894 "ReadCycleWrite is only to be used on riscv32"); 7895 return emitReadCycleWidePseudo(MI, BB); 7896 case RISCV::Select_GPR_Using_CC_GPR: 7897 case RISCV::Select_FPR16_Using_CC_GPR: 7898 case RISCV::Select_FPR32_Using_CC_GPR: 7899 case RISCV::Select_FPR64_Using_CC_GPR: 7900 return emitSelectPseudo(MI, BB, Subtarget); 7901 case RISCV::BuildPairF64Pseudo: 7902 return emitBuildPairF64Pseudo(MI, BB); 7903 case RISCV::SplitF64Pseudo: 7904 return emitSplitF64Pseudo(MI, BB); 7905 } 7906 } 7907 7908 // Calling Convention Implementation. 7909 // The expectations for frontend ABI lowering vary from target to target. 7910 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 7911 // details, but this is a longer term goal. For now, we simply try to keep the 7912 // role of the frontend as simple and well-defined as possible. The rules can 7913 // be summarised as: 7914 // * Never split up large scalar arguments. We handle them here. 7915 // * If a hardfloat calling convention is being used, and the struct may be 7916 // passed in a pair of registers (fp+fp, int+fp), and both registers are 7917 // available, then pass as two separate arguments. If either the GPRs or FPRs 7918 // are exhausted, then pass according to the rule below. 7919 // * If a struct could never be passed in registers or directly in a stack 7920 // slot (as it is larger than 2*XLEN and the floating point rules don't 7921 // apply), then pass it using a pointer with the byval attribute. 7922 // * If a struct is less than 2*XLEN, then coerce to either a two-element 7923 // word-sized array or a 2*XLEN scalar (depending on alignment). 7924 // * The frontend can determine whether a struct is returned by reference or 7925 // not based on its size and fields. If it will be returned by reference, the 7926 // frontend must modify the prototype so a pointer with the sret annotation is 7927 // passed as the first argument. This is not necessary for large scalar 7928 // returns. 7929 // * Struct return values and varargs should be coerced to structs containing 7930 // register-size fields in the same situations they would be for fixed 7931 // arguments. 7932 7933 static const MCPhysReg ArgGPRs[] = { 7934 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 7935 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 7936 }; 7937 static const MCPhysReg ArgFPR16s[] = { 7938 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 7939 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 7940 }; 7941 static const MCPhysReg ArgFPR32s[] = { 7942 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 7943 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 7944 }; 7945 static const MCPhysReg ArgFPR64s[] = { 7946 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 7947 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 7948 }; 7949 // This is an interim calling convention and it may be changed in the future. 7950 static const MCPhysReg ArgVRs[] = { 7951 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 7952 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 7953 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 7954 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 7955 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 7956 RISCV::V20M2, RISCV::V22M2}; 7957 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 7958 RISCV::V20M4}; 7959 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 7960 7961 // Pass a 2*XLEN argument that has been split into two XLEN values through 7962 // registers or the stack as necessary. 7963 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 7964 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 7965 MVT ValVT2, MVT LocVT2, 7966 ISD::ArgFlagsTy ArgFlags2) { 7967 unsigned XLenInBytes = XLen / 8; 7968 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7969 // At least one half can be passed via register. 7970 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 7971 VA1.getLocVT(), CCValAssign::Full)); 7972 } else { 7973 // Both halves must be passed on the stack, with proper alignment. 7974 Align StackAlign = 7975 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 7976 State.addLoc( 7977 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 7978 State.AllocateStack(XLenInBytes, StackAlign), 7979 VA1.getLocVT(), CCValAssign::Full)); 7980 State.addLoc(CCValAssign::getMem( 7981 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7982 LocVT2, CCValAssign::Full)); 7983 return false; 7984 } 7985 7986 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7987 // The second half can also be passed via register. 7988 State.addLoc( 7989 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 7990 } else { 7991 // The second half is passed via the stack, without additional alignment. 7992 State.addLoc(CCValAssign::getMem( 7993 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7994 LocVT2, CCValAssign::Full)); 7995 } 7996 7997 return false; 7998 } 7999 8000 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8001 Optional<unsigned> FirstMaskArgument, 8002 CCState &State, const RISCVTargetLowering &TLI) { 8003 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8004 if (RC == &RISCV::VRRegClass) { 8005 // Assign the first mask argument to V0. 8006 // This is an interim calling convention and it may be changed in the 8007 // future. 8008 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8009 return State.AllocateReg(RISCV::V0); 8010 return State.AllocateReg(ArgVRs); 8011 } 8012 if (RC == &RISCV::VRM2RegClass) 8013 return State.AllocateReg(ArgVRM2s); 8014 if (RC == &RISCV::VRM4RegClass) 8015 return State.AllocateReg(ArgVRM4s); 8016 if (RC == &RISCV::VRM8RegClass) 8017 return State.AllocateReg(ArgVRM8s); 8018 llvm_unreachable("Unhandled register class for ValueType"); 8019 } 8020 8021 // Implements the RISC-V calling convention. Returns true upon failure. 8022 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8023 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8024 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8025 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8026 Optional<unsigned> FirstMaskArgument) { 8027 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8028 assert(XLen == 32 || XLen == 64); 8029 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8030 8031 // Any return value split in to more than two values can't be returned 8032 // directly. Vectors are returned via the available vector registers. 8033 if (!LocVT.isVector() && IsRet && ValNo > 1) 8034 return true; 8035 8036 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8037 // variadic argument, or if no F16/F32 argument registers are available. 8038 bool UseGPRForF16_F32 = true; 8039 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8040 // variadic argument, or if no F64 argument registers are available. 8041 bool UseGPRForF64 = true; 8042 8043 switch (ABI) { 8044 default: 8045 llvm_unreachable("Unexpected ABI"); 8046 case RISCVABI::ABI_ILP32: 8047 case RISCVABI::ABI_LP64: 8048 break; 8049 case RISCVABI::ABI_ILP32F: 8050 case RISCVABI::ABI_LP64F: 8051 UseGPRForF16_F32 = !IsFixed; 8052 break; 8053 case RISCVABI::ABI_ILP32D: 8054 case RISCVABI::ABI_LP64D: 8055 UseGPRForF16_F32 = !IsFixed; 8056 UseGPRForF64 = !IsFixed; 8057 break; 8058 } 8059 8060 // FPR16, FPR32, and FPR64 alias each other. 8061 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8062 UseGPRForF16_F32 = true; 8063 UseGPRForF64 = true; 8064 } 8065 8066 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8067 // similar local variables rather than directly checking against the target 8068 // ABI. 8069 8070 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8071 LocVT = XLenVT; 8072 LocInfo = CCValAssign::BCvt; 8073 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8074 LocVT = MVT::i64; 8075 LocInfo = CCValAssign::BCvt; 8076 } 8077 8078 // If this is a variadic argument, the RISC-V calling convention requires 8079 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8080 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8081 // be used regardless of whether the original argument was split during 8082 // legalisation or not. The argument will not be passed by registers if the 8083 // original type is larger than 2*XLEN, so the register alignment rule does 8084 // not apply. 8085 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8086 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8087 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8088 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8089 // Skip 'odd' register if necessary. 8090 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8091 State.AllocateReg(ArgGPRs); 8092 } 8093 8094 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8095 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8096 State.getPendingArgFlags(); 8097 8098 assert(PendingLocs.size() == PendingArgFlags.size() && 8099 "PendingLocs and PendingArgFlags out of sync"); 8100 8101 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8102 // registers are exhausted. 8103 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8104 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8105 "Can't lower f64 if it is split"); 8106 // Depending on available argument GPRS, f64 may be passed in a pair of 8107 // GPRs, split between a GPR and the stack, or passed completely on the 8108 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8109 // cases. 8110 Register Reg = State.AllocateReg(ArgGPRs); 8111 LocVT = MVT::i32; 8112 if (!Reg) { 8113 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8114 State.addLoc( 8115 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8116 return false; 8117 } 8118 if (!State.AllocateReg(ArgGPRs)) 8119 State.AllocateStack(4, Align(4)); 8120 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8121 return false; 8122 } 8123 8124 // Fixed-length vectors are located in the corresponding scalable-vector 8125 // container types. 8126 if (ValVT.isFixedLengthVector()) 8127 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8128 8129 // Split arguments might be passed indirectly, so keep track of the pending 8130 // values. Split vectors are passed via a mix of registers and indirectly, so 8131 // treat them as we would any other argument. 8132 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8133 LocVT = XLenVT; 8134 LocInfo = CCValAssign::Indirect; 8135 PendingLocs.push_back( 8136 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8137 PendingArgFlags.push_back(ArgFlags); 8138 if (!ArgFlags.isSplitEnd()) { 8139 return false; 8140 } 8141 } 8142 8143 // If the split argument only had two elements, it should be passed directly 8144 // in registers or on the stack. 8145 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8146 PendingLocs.size() <= 2) { 8147 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8148 // Apply the normal calling convention rules to the first half of the 8149 // split argument. 8150 CCValAssign VA = PendingLocs[0]; 8151 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8152 PendingLocs.clear(); 8153 PendingArgFlags.clear(); 8154 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8155 ArgFlags); 8156 } 8157 8158 // Allocate to a register if possible, or else a stack slot. 8159 Register Reg; 8160 unsigned StoreSizeBytes = XLen / 8; 8161 Align StackAlign = Align(XLen / 8); 8162 8163 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8164 Reg = State.AllocateReg(ArgFPR16s); 8165 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8166 Reg = State.AllocateReg(ArgFPR32s); 8167 else if (ValVT == MVT::f64 && !UseGPRForF64) 8168 Reg = State.AllocateReg(ArgFPR64s); 8169 else if (ValVT.isVector()) { 8170 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8171 if (!Reg) { 8172 // For return values, the vector must be passed fully via registers or 8173 // via the stack. 8174 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8175 // but we're using all of them. 8176 if (IsRet) 8177 return true; 8178 // Try using a GPR to pass the address 8179 if ((Reg = State.AllocateReg(ArgGPRs))) { 8180 LocVT = XLenVT; 8181 LocInfo = CCValAssign::Indirect; 8182 } else if (ValVT.isScalableVector()) { 8183 report_fatal_error("Unable to pass scalable vector types on the stack"); 8184 } else { 8185 // Pass fixed-length vectors on the stack. 8186 LocVT = ValVT; 8187 StoreSizeBytes = ValVT.getStoreSize(); 8188 // Align vectors to their element sizes, being careful for vXi1 8189 // vectors. 8190 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8191 } 8192 } 8193 } else { 8194 Reg = State.AllocateReg(ArgGPRs); 8195 } 8196 8197 unsigned StackOffset = 8198 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8199 8200 // If we reach this point and PendingLocs is non-empty, we must be at the 8201 // end of a split argument that must be passed indirectly. 8202 if (!PendingLocs.empty()) { 8203 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8204 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8205 8206 for (auto &It : PendingLocs) { 8207 if (Reg) 8208 It.convertToReg(Reg); 8209 else 8210 It.convertToMem(StackOffset); 8211 State.addLoc(It); 8212 } 8213 PendingLocs.clear(); 8214 PendingArgFlags.clear(); 8215 return false; 8216 } 8217 8218 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8219 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8220 "Expected an XLenVT or vector types at this stage"); 8221 8222 if (Reg) { 8223 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8224 return false; 8225 } 8226 8227 // When a floating-point value is passed on the stack, no bit-conversion is 8228 // needed. 8229 if (ValVT.isFloatingPoint()) { 8230 LocVT = ValVT; 8231 LocInfo = CCValAssign::Full; 8232 } 8233 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8234 return false; 8235 } 8236 8237 template <typename ArgTy> 8238 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8239 for (const auto &ArgIdx : enumerate(Args)) { 8240 MVT ArgVT = ArgIdx.value().VT; 8241 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8242 return ArgIdx.index(); 8243 } 8244 return None; 8245 } 8246 8247 void RISCVTargetLowering::analyzeInputArgs( 8248 MachineFunction &MF, CCState &CCInfo, 8249 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8250 RISCVCCAssignFn Fn) const { 8251 unsigned NumArgs = Ins.size(); 8252 FunctionType *FType = MF.getFunction().getFunctionType(); 8253 8254 Optional<unsigned> FirstMaskArgument; 8255 if (Subtarget.hasVInstructions()) 8256 FirstMaskArgument = preAssignMask(Ins); 8257 8258 for (unsigned i = 0; i != NumArgs; ++i) { 8259 MVT ArgVT = Ins[i].VT; 8260 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8261 8262 Type *ArgTy = nullptr; 8263 if (IsRet) 8264 ArgTy = FType->getReturnType(); 8265 else if (Ins[i].isOrigArg()) 8266 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8267 8268 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8269 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8270 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8271 FirstMaskArgument)) { 8272 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8273 << EVT(ArgVT).getEVTString() << '\n'); 8274 llvm_unreachable(nullptr); 8275 } 8276 } 8277 } 8278 8279 void RISCVTargetLowering::analyzeOutputArgs( 8280 MachineFunction &MF, CCState &CCInfo, 8281 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8282 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8283 unsigned NumArgs = Outs.size(); 8284 8285 Optional<unsigned> FirstMaskArgument; 8286 if (Subtarget.hasVInstructions()) 8287 FirstMaskArgument = preAssignMask(Outs); 8288 8289 for (unsigned i = 0; i != NumArgs; i++) { 8290 MVT ArgVT = Outs[i].VT; 8291 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8292 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8293 8294 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8295 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8296 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8297 FirstMaskArgument)) { 8298 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8299 << EVT(ArgVT).getEVTString() << "\n"); 8300 llvm_unreachable(nullptr); 8301 } 8302 } 8303 } 8304 8305 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8306 // values. 8307 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8308 const CCValAssign &VA, const SDLoc &DL, 8309 const RISCVSubtarget &Subtarget) { 8310 switch (VA.getLocInfo()) { 8311 default: 8312 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8313 case CCValAssign::Full: 8314 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8315 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8316 break; 8317 case CCValAssign::BCvt: 8318 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8319 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8320 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8321 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8322 else 8323 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8324 break; 8325 } 8326 return Val; 8327 } 8328 8329 // The caller is responsible for loading the full value if the argument is 8330 // passed with CCValAssign::Indirect. 8331 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8332 const CCValAssign &VA, const SDLoc &DL, 8333 const RISCVTargetLowering &TLI) { 8334 MachineFunction &MF = DAG.getMachineFunction(); 8335 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8336 EVT LocVT = VA.getLocVT(); 8337 SDValue Val; 8338 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8339 Register VReg = RegInfo.createVirtualRegister(RC); 8340 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8341 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8342 8343 if (VA.getLocInfo() == CCValAssign::Indirect) 8344 return Val; 8345 8346 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8347 } 8348 8349 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8350 const CCValAssign &VA, const SDLoc &DL, 8351 const RISCVSubtarget &Subtarget) { 8352 EVT LocVT = VA.getLocVT(); 8353 8354 switch (VA.getLocInfo()) { 8355 default: 8356 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8357 case CCValAssign::Full: 8358 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8359 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8360 break; 8361 case CCValAssign::BCvt: 8362 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8363 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8364 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8365 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8366 else 8367 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8368 break; 8369 } 8370 return Val; 8371 } 8372 8373 // The caller is responsible for loading the full value if the argument is 8374 // passed with CCValAssign::Indirect. 8375 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8376 const CCValAssign &VA, const SDLoc &DL) { 8377 MachineFunction &MF = DAG.getMachineFunction(); 8378 MachineFrameInfo &MFI = MF.getFrameInfo(); 8379 EVT LocVT = VA.getLocVT(); 8380 EVT ValVT = VA.getValVT(); 8381 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8382 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8383 /*Immutable=*/true); 8384 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8385 SDValue Val; 8386 8387 ISD::LoadExtType ExtType; 8388 switch (VA.getLocInfo()) { 8389 default: 8390 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8391 case CCValAssign::Full: 8392 case CCValAssign::Indirect: 8393 case CCValAssign::BCvt: 8394 ExtType = ISD::NON_EXTLOAD; 8395 break; 8396 } 8397 Val = DAG.getExtLoad( 8398 ExtType, DL, LocVT, Chain, FIN, 8399 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8400 return Val; 8401 } 8402 8403 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8404 const CCValAssign &VA, const SDLoc &DL) { 8405 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8406 "Unexpected VA"); 8407 MachineFunction &MF = DAG.getMachineFunction(); 8408 MachineFrameInfo &MFI = MF.getFrameInfo(); 8409 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8410 8411 if (VA.isMemLoc()) { 8412 // f64 is passed on the stack. 8413 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8414 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8415 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8416 MachinePointerInfo::getFixedStack(MF, FI)); 8417 } 8418 8419 assert(VA.isRegLoc() && "Expected register VA assignment"); 8420 8421 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8422 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8423 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8424 SDValue Hi; 8425 if (VA.getLocReg() == RISCV::X17) { 8426 // Second half of f64 is passed on the stack. 8427 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8428 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8429 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8430 MachinePointerInfo::getFixedStack(MF, FI)); 8431 } else { 8432 // Second half of f64 is passed in another GPR. 8433 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8434 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8435 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8436 } 8437 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8438 } 8439 8440 // FastCC has less than 1% performance improvement for some particular 8441 // benchmark. But theoretically, it may has benenfit for some cases. 8442 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8443 unsigned ValNo, MVT ValVT, MVT LocVT, 8444 CCValAssign::LocInfo LocInfo, 8445 ISD::ArgFlagsTy ArgFlags, CCState &State, 8446 bool IsFixed, bool IsRet, Type *OrigTy, 8447 const RISCVTargetLowering &TLI, 8448 Optional<unsigned> FirstMaskArgument) { 8449 8450 // X5 and X6 might be used for save-restore libcall. 8451 static const MCPhysReg GPRList[] = { 8452 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8453 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8454 RISCV::X29, RISCV::X30, RISCV::X31}; 8455 8456 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8457 if (unsigned Reg = State.AllocateReg(GPRList)) { 8458 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8459 return false; 8460 } 8461 } 8462 8463 if (LocVT == MVT::f16) { 8464 static const MCPhysReg FPR16List[] = { 8465 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8466 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8467 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8468 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8469 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8470 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8471 return false; 8472 } 8473 } 8474 8475 if (LocVT == MVT::f32) { 8476 static const MCPhysReg FPR32List[] = { 8477 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8478 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8479 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8480 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8481 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8482 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8483 return false; 8484 } 8485 } 8486 8487 if (LocVT == MVT::f64) { 8488 static const MCPhysReg FPR64List[] = { 8489 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8490 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8491 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8492 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8493 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8494 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8495 return false; 8496 } 8497 } 8498 8499 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8500 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8501 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8502 return false; 8503 } 8504 8505 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8506 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8507 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8508 return false; 8509 } 8510 8511 if (LocVT.isVector()) { 8512 if (unsigned Reg = 8513 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8514 // Fixed-length vectors are located in the corresponding scalable-vector 8515 // container types. 8516 if (ValVT.isFixedLengthVector()) 8517 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8518 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8519 } else { 8520 // Try and pass the address via a "fast" GPR. 8521 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8522 LocInfo = CCValAssign::Indirect; 8523 LocVT = TLI.getSubtarget().getXLenVT(); 8524 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8525 } else if (ValVT.isFixedLengthVector()) { 8526 auto StackAlign = 8527 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8528 unsigned StackOffset = 8529 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8530 State.addLoc( 8531 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8532 } else { 8533 // Can't pass scalable vectors on the stack. 8534 return true; 8535 } 8536 } 8537 8538 return false; 8539 } 8540 8541 return true; // CC didn't match. 8542 } 8543 8544 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8545 CCValAssign::LocInfo LocInfo, 8546 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8547 8548 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8549 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8550 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8551 static const MCPhysReg GPRList[] = { 8552 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8553 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8554 if (unsigned Reg = State.AllocateReg(GPRList)) { 8555 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8556 return false; 8557 } 8558 } 8559 8560 if (LocVT == MVT::f32) { 8561 // Pass in STG registers: F1, ..., F6 8562 // fs0 ... fs5 8563 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8564 RISCV::F18_F, RISCV::F19_F, 8565 RISCV::F20_F, RISCV::F21_F}; 8566 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8567 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8568 return false; 8569 } 8570 } 8571 8572 if (LocVT == MVT::f64) { 8573 // Pass in STG registers: D1, ..., D6 8574 // fs6 ... fs11 8575 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8576 RISCV::F24_D, RISCV::F25_D, 8577 RISCV::F26_D, RISCV::F27_D}; 8578 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8579 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8580 return false; 8581 } 8582 } 8583 8584 report_fatal_error("No registers left in GHC calling convention"); 8585 return true; 8586 } 8587 8588 // Transform physical registers into virtual registers. 8589 SDValue RISCVTargetLowering::LowerFormalArguments( 8590 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8591 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8592 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8593 8594 MachineFunction &MF = DAG.getMachineFunction(); 8595 8596 switch (CallConv) { 8597 default: 8598 report_fatal_error("Unsupported calling convention"); 8599 case CallingConv::C: 8600 case CallingConv::Fast: 8601 break; 8602 case CallingConv::GHC: 8603 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8604 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8605 report_fatal_error( 8606 "GHC calling convention requires the F and D instruction set extensions"); 8607 } 8608 8609 const Function &Func = MF.getFunction(); 8610 if (Func.hasFnAttribute("interrupt")) { 8611 if (!Func.arg_empty()) 8612 report_fatal_error( 8613 "Functions with the interrupt attribute cannot have arguments!"); 8614 8615 StringRef Kind = 8616 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8617 8618 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8619 report_fatal_error( 8620 "Function interrupt attribute argument not supported!"); 8621 } 8622 8623 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8624 MVT XLenVT = Subtarget.getXLenVT(); 8625 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8626 // Used with vargs to acumulate store chains. 8627 std::vector<SDValue> OutChains; 8628 8629 // Assign locations to all of the incoming arguments. 8630 SmallVector<CCValAssign, 16> ArgLocs; 8631 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8632 8633 if (CallConv == CallingConv::GHC) 8634 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8635 else 8636 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8637 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8638 : CC_RISCV); 8639 8640 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8641 CCValAssign &VA = ArgLocs[i]; 8642 SDValue ArgValue; 8643 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8644 // case. 8645 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8646 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8647 else if (VA.isRegLoc()) 8648 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8649 else 8650 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8651 8652 if (VA.getLocInfo() == CCValAssign::Indirect) { 8653 // If the original argument was split and passed by reference (e.g. i128 8654 // on RV32), we need to load all parts of it here (using the same 8655 // address). Vectors may be partly split to registers and partly to the 8656 // stack, in which case the base address is partly offset and subsequent 8657 // stores are relative to that. 8658 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8659 MachinePointerInfo())); 8660 unsigned ArgIndex = Ins[i].OrigArgIndex; 8661 unsigned ArgPartOffset = Ins[i].PartOffset; 8662 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8663 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8664 CCValAssign &PartVA = ArgLocs[i + 1]; 8665 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8666 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8667 if (PartVA.getValVT().isScalableVector()) 8668 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8669 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8670 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8671 MachinePointerInfo())); 8672 ++i; 8673 } 8674 continue; 8675 } 8676 InVals.push_back(ArgValue); 8677 } 8678 8679 if (IsVarArg) { 8680 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8681 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8682 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8683 MachineFrameInfo &MFI = MF.getFrameInfo(); 8684 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8685 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8686 8687 // Offset of the first variable argument from stack pointer, and size of 8688 // the vararg save area. For now, the varargs save area is either zero or 8689 // large enough to hold a0-a7. 8690 int VaArgOffset, VarArgsSaveSize; 8691 8692 // If all registers are allocated, then all varargs must be passed on the 8693 // stack and we don't need to save any argregs. 8694 if (ArgRegs.size() == Idx) { 8695 VaArgOffset = CCInfo.getNextStackOffset(); 8696 VarArgsSaveSize = 0; 8697 } else { 8698 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8699 VaArgOffset = -VarArgsSaveSize; 8700 } 8701 8702 // Record the frame index of the first variable argument 8703 // which is a value necessary to VASTART. 8704 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8705 RVFI->setVarArgsFrameIndex(FI); 8706 8707 // If saving an odd number of registers then create an extra stack slot to 8708 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8709 // offsets to even-numbered registered remain 2*XLEN-aligned. 8710 if (Idx % 2) { 8711 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8712 VarArgsSaveSize += XLenInBytes; 8713 } 8714 8715 // Copy the integer registers that may have been used for passing varargs 8716 // to the vararg save area. 8717 for (unsigned I = Idx; I < ArgRegs.size(); 8718 ++I, VaArgOffset += XLenInBytes) { 8719 const Register Reg = RegInfo.createVirtualRegister(RC); 8720 RegInfo.addLiveIn(ArgRegs[I], Reg); 8721 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8722 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8723 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8724 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8725 MachinePointerInfo::getFixedStack(MF, FI)); 8726 cast<StoreSDNode>(Store.getNode()) 8727 ->getMemOperand() 8728 ->setValue((Value *)nullptr); 8729 OutChains.push_back(Store); 8730 } 8731 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8732 } 8733 8734 // All stores are grouped in one node to allow the matching between 8735 // the size of Ins and InVals. This only happens for vararg functions. 8736 if (!OutChains.empty()) { 8737 OutChains.push_back(Chain); 8738 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8739 } 8740 8741 return Chain; 8742 } 8743 8744 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8745 /// for tail call optimization. 8746 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8747 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8748 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8749 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8750 8751 auto &Callee = CLI.Callee; 8752 auto CalleeCC = CLI.CallConv; 8753 auto &Outs = CLI.Outs; 8754 auto &Caller = MF.getFunction(); 8755 auto CallerCC = Caller.getCallingConv(); 8756 8757 // Exception-handling functions need a special set of instructions to 8758 // indicate a return to the hardware. Tail-calling another function would 8759 // probably break this. 8760 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8761 // should be expanded as new function attributes are introduced. 8762 if (Caller.hasFnAttribute("interrupt")) 8763 return false; 8764 8765 // Do not tail call opt if the stack is used to pass parameters. 8766 if (CCInfo.getNextStackOffset() != 0) 8767 return false; 8768 8769 // Do not tail call opt if any parameters need to be passed indirectly. 8770 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 8771 // passed indirectly. So the address of the value will be passed in a 8772 // register, or if not available, then the address is put on the stack. In 8773 // order to pass indirectly, space on the stack often needs to be allocated 8774 // in order to store the value. In this case the CCInfo.getNextStackOffset() 8775 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 8776 // are passed CCValAssign::Indirect. 8777 for (auto &VA : ArgLocs) 8778 if (VA.getLocInfo() == CCValAssign::Indirect) 8779 return false; 8780 8781 // Do not tail call opt if either caller or callee uses struct return 8782 // semantics. 8783 auto IsCallerStructRet = Caller.hasStructRetAttr(); 8784 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 8785 if (IsCallerStructRet || IsCalleeStructRet) 8786 return false; 8787 8788 // Externally-defined functions with weak linkage should not be 8789 // tail-called. The behaviour of branch instructions in this situation (as 8790 // used for tail calls) is implementation-defined, so we cannot rely on the 8791 // linker replacing the tail call with a return. 8792 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 8793 const GlobalValue *GV = G->getGlobal(); 8794 if (GV->hasExternalWeakLinkage()) 8795 return false; 8796 } 8797 8798 // The callee has to preserve all registers the caller needs to preserve. 8799 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8800 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 8801 if (CalleeCC != CallerCC) { 8802 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 8803 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 8804 return false; 8805 } 8806 8807 // Byval parameters hand the function a pointer directly into the stack area 8808 // we want to reuse during a tail call. Working around this *is* possible 8809 // but less efficient and uglier in LowerCall. 8810 for (auto &Arg : Outs) 8811 if (Arg.Flags.isByVal()) 8812 return false; 8813 8814 return true; 8815 } 8816 8817 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 8818 return DAG.getDataLayout().getPrefTypeAlign( 8819 VT.getTypeForEVT(*DAG.getContext())); 8820 } 8821 8822 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 8823 // and output parameter nodes. 8824 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 8825 SmallVectorImpl<SDValue> &InVals) const { 8826 SelectionDAG &DAG = CLI.DAG; 8827 SDLoc &DL = CLI.DL; 8828 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 8829 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 8830 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 8831 SDValue Chain = CLI.Chain; 8832 SDValue Callee = CLI.Callee; 8833 bool &IsTailCall = CLI.IsTailCall; 8834 CallingConv::ID CallConv = CLI.CallConv; 8835 bool IsVarArg = CLI.IsVarArg; 8836 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8837 MVT XLenVT = Subtarget.getXLenVT(); 8838 8839 MachineFunction &MF = DAG.getMachineFunction(); 8840 8841 // Analyze the operands of the call, assigning locations to each operand. 8842 SmallVector<CCValAssign, 16> ArgLocs; 8843 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8844 8845 if (CallConv == CallingConv::GHC) 8846 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 8847 else 8848 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 8849 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8850 : CC_RISCV); 8851 8852 // Check if it's really possible to do a tail call. 8853 if (IsTailCall) 8854 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 8855 8856 if (IsTailCall) 8857 ++NumTailCalls; 8858 else if (CLI.CB && CLI.CB->isMustTailCall()) 8859 report_fatal_error("failed to perform tail call elimination on a call " 8860 "site marked musttail"); 8861 8862 // Get a count of how many bytes are to be pushed on the stack. 8863 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 8864 8865 // Create local copies for byval args 8866 SmallVector<SDValue, 8> ByValArgs; 8867 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8868 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8869 if (!Flags.isByVal()) 8870 continue; 8871 8872 SDValue Arg = OutVals[i]; 8873 unsigned Size = Flags.getByValSize(); 8874 Align Alignment = Flags.getNonZeroByValAlign(); 8875 8876 int FI = 8877 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 8878 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8879 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 8880 8881 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 8882 /*IsVolatile=*/false, 8883 /*AlwaysInline=*/false, IsTailCall, 8884 MachinePointerInfo(), MachinePointerInfo()); 8885 ByValArgs.push_back(FIPtr); 8886 } 8887 8888 if (!IsTailCall) 8889 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 8890 8891 // Copy argument values to their designated locations. 8892 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 8893 SmallVector<SDValue, 8> MemOpChains; 8894 SDValue StackPtr; 8895 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 8896 CCValAssign &VA = ArgLocs[i]; 8897 SDValue ArgValue = OutVals[i]; 8898 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8899 8900 // Handle passing f64 on RV32D with a soft float ABI as a special case. 8901 bool IsF64OnRV32DSoftABI = 8902 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 8903 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 8904 SDValue SplitF64 = DAG.getNode( 8905 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 8906 SDValue Lo = SplitF64.getValue(0); 8907 SDValue Hi = SplitF64.getValue(1); 8908 8909 Register RegLo = VA.getLocReg(); 8910 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 8911 8912 if (RegLo == RISCV::X17) { 8913 // Second half of f64 is passed on the stack. 8914 // Work out the address of the stack slot. 8915 if (!StackPtr.getNode()) 8916 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8917 // Emit the store. 8918 MemOpChains.push_back( 8919 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 8920 } else { 8921 // Second half of f64 is passed in another GPR. 8922 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8923 Register RegHigh = RegLo + 1; 8924 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 8925 } 8926 continue; 8927 } 8928 8929 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 8930 // as any other MemLoc. 8931 8932 // Promote the value if needed. 8933 // For now, only handle fully promoted and indirect arguments. 8934 if (VA.getLocInfo() == CCValAssign::Indirect) { 8935 // Store the argument in a stack slot and pass its address. 8936 Align StackAlign = 8937 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 8938 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 8939 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 8940 // If the original argument was split (e.g. i128), we need 8941 // to store the required parts of it here (and pass just one address). 8942 // Vectors may be partly split to registers and partly to the stack, in 8943 // which case the base address is partly offset and subsequent stores are 8944 // relative to that. 8945 unsigned ArgIndex = Outs[i].OrigArgIndex; 8946 unsigned ArgPartOffset = Outs[i].PartOffset; 8947 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8948 // Calculate the total size to store. We don't have access to what we're 8949 // actually storing other than performing the loop and collecting the 8950 // info. 8951 SmallVector<std::pair<SDValue, SDValue>> Parts; 8952 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 8953 SDValue PartValue = OutVals[i + 1]; 8954 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 8955 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8956 EVT PartVT = PartValue.getValueType(); 8957 if (PartVT.isScalableVector()) 8958 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8959 StoredSize += PartVT.getStoreSize(); 8960 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 8961 Parts.push_back(std::make_pair(PartValue, Offset)); 8962 ++i; 8963 } 8964 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 8965 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 8966 MemOpChains.push_back( 8967 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 8968 MachinePointerInfo::getFixedStack(MF, FI))); 8969 for (const auto &Part : Parts) { 8970 SDValue PartValue = Part.first; 8971 SDValue PartOffset = Part.second; 8972 SDValue Address = 8973 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 8974 MemOpChains.push_back( 8975 DAG.getStore(Chain, DL, PartValue, Address, 8976 MachinePointerInfo::getFixedStack(MF, FI))); 8977 } 8978 ArgValue = SpillSlot; 8979 } else { 8980 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 8981 } 8982 8983 // Use local copy if it is a byval arg. 8984 if (Flags.isByVal()) 8985 ArgValue = ByValArgs[j++]; 8986 8987 if (VA.isRegLoc()) { 8988 // Queue up the argument copies and emit them at the end. 8989 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 8990 } else { 8991 assert(VA.isMemLoc() && "Argument not register or memory"); 8992 assert(!IsTailCall && "Tail call not allowed if stack is used " 8993 "for passing parameters"); 8994 8995 // Work out the address of the stack slot. 8996 if (!StackPtr.getNode()) 8997 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8998 SDValue Address = 8999 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9000 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9001 9002 // Emit the store. 9003 MemOpChains.push_back( 9004 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9005 } 9006 } 9007 9008 // Join the stores, which are independent of one another. 9009 if (!MemOpChains.empty()) 9010 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9011 9012 SDValue Glue; 9013 9014 // Build a sequence of copy-to-reg nodes, chained and glued together. 9015 for (auto &Reg : RegsToPass) { 9016 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9017 Glue = Chain.getValue(1); 9018 } 9019 9020 // Validate that none of the argument registers have been marked as 9021 // reserved, if so report an error. Do the same for the return address if this 9022 // is not a tailcall. 9023 validateCCReservedRegs(RegsToPass, MF); 9024 if (!IsTailCall && 9025 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9026 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9027 MF.getFunction(), 9028 "Return address register required, but has been reserved."}); 9029 9030 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9031 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9032 // split it and then direct call can be matched by PseudoCALL. 9033 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9034 const GlobalValue *GV = S->getGlobal(); 9035 9036 unsigned OpFlags = RISCVII::MO_CALL; 9037 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9038 OpFlags = RISCVII::MO_PLT; 9039 9040 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9041 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9042 unsigned OpFlags = RISCVII::MO_CALL; 9043 9044 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9045 nullptr)) 9046 OpFlags = RISCVII::MO_PLT; 9047 9048 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9049 } 9050 9051 // The first call operand is the chain and the second is the target address. 9052 SmallVector<SDValue, 8> Ops; 9053 Ops.push_back(Chain); 9054 Ops.push_back(Callee); 9055 9056 // Add argument registers to the end of the list so that they are 9057 // known live into the call. 9058 for (auto &Reg : RegsToPass) 9059 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9060 9061 if (!IsTailCall) { 9062 // Add a register mask operand representing the call-preserved registers. 9063 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9064 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9065 assert(Mask && "Missing call preserved mask for calling convention"); 9066 Ops.push_back(DAG.getRegisterMask(Mask)); 9067 } 9068 9069 // Glue the call to the argument copies, if any. 9070 if (Glue.getNode()) 9071 Ops.push_back(Glue); 9072 9073 // Emit the call. 9074 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9075 9076 if (IsTailCall) { 9077 MF.getFrameInfo().setHasTailCall(); 9078 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9079 } 9080 9081 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9082 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9083 Glue = Chain.getValue(1); 9084 9085 // Mark the end of the call, which is glued to the call itself. 9086 Chain = DAG.getCALLSEQ_END(Chain, 9087 DAG.getConstant(NumBytes, DL, PtrVT, true), 9088 DAG.getConstant(0, DL, PtrVT, true), 9089 Glue, DL); 9090 Glue = Chain.getValue(1); 9091 9092 // Assign locations to each value returned by this call. 9093 SmallVector<CCValAssign, 16> RVLocs; 9094 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9095 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9096 9097 // Copy all of the result registers out of their specified physreg. 9098 for (auto &VA : RVLocs) { 9099 // Copy the value out 9100 SDValue RetValue = 9101 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9102 // Glue the RetValue to the end of the call sequence 9103 Chain = RetValue.getValue(1); 9104 Glue = RetValue.getValue(2); 9105 9106 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9107 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9108 SDValue RetValue2 = 9109 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9110 Chain = RetValue2.getValue(1); 9111 Glue = RetValue2.getValue(2); 9112 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9113 RetValue2); 9114 } 9115 9116 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9117 9118 InVals.push_back(RetValue); 9119 } 9120 9121 return Chain; 9122 } 9123 9124 bool RISCVTargetLowering::CanLowerReturn( 9125 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9126 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9127 SmallVector<CCValAssign, 16> RVLocs; 9128 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9129 9130 Optional<unsigned> FirstMaskArgument; 9131 if (Subtarget.hasVInstructions()) 9132 FirstMaskArgument = preAssignMask(Outs); 9133 9134 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9135 MVT VT = Outs[i].VT; 9136 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9137 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9138 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9139 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9140 *this, FirstMaskArgument)) 9141 return false; 9142 } 9143 return true; 9144 } 9145 9146 SDValue 9147 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9148 bool IsVarArg, 9149 const SmallVectorImpl<ISD::OutputArg> &Outs, 9150 const SmallVectorImpl<SDValue> &OutVals, 9151 const SDLoc &DL, SelectionDAG &DAG) const { 9152 const MachineFunction &MF = DAG.getMachineFunction(); 9153 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9154 9155 // Stores the assignment of the return value to a location. 9156 SmallVector<CCValAssign, 16> RVLocs; 9157 9158 // Info about the registers and stack slot. 9159 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9160 *DAG.getContext()); 9161 9162 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9163 nullptr, CC_RISCV); 9164 9165 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9166 report_fatal_error("GHC functions return void only"); 9167 9168 SDValue Glue; 9169 SmallVector<SDValue, 4> RetOps(1, Chain); 9170 9171 // Copy the result values into the output registers. 9172 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9173 SDValue Val = OutVals[i]; 9174 CCValAssign &VA = RVLocs[i]; 9175 assert(VA.isRegLoc() && "Can only return in registers!"); 9176 9177 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9178 // Handle returning f64 on RV32D with a soft float ABI. 9179 assert(VA.isRegLoc() && "Expected return via registers"); 9180 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9181 DAG.getVTList(MVT::i32, MVT::i32), Val); 9182 SDValue Lo = SplitF64.getValue(0); 9183 SDValue Hi = SplitF64.getValue(1); 9184 Register RegLo = VA.getLocReg(); 9185 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9186 Register RegHi = RegLo + 1; 9187 9188 if (STI.isRegisterReservedByUser(RegLo) || 9189 STI.isRegisterReservedByUser(RegHi)) 9190 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9191 MF.getFunction(), 9192 "Return value register required, but has been reserved."}); 9193 9194 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9195 Glue = Chain.getValue(1); 9196 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9197 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9198 Glue = Chain.getValue(1); 9199 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9200 } else { 9201 // Handle a 'normal' return. 9202 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9203 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9204 9205 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9206 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9207 MF.getFunction(), 9208 "Return value register required, but has been reserved."}); 9209 9210 // Guarantee that all emitted copies are stuck together. 9211 Glue = Chain.getValue(1); 9212 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9213 } 9214 } 9215 9216 RetOps[0] = Chain; // Update chain. 9217 9218 // Add the glue node if we have it. 9219 if (Glue.getNode()) { 9220 RetOps.push_back(Glue); 9221 } 9222 9223 unsigned RetOpc = RISCVISD::RET_FLAG; 9224 // Interrupt service routines use different return instructions. 9225 const Function &Func = DAG.getMachineFunction().getFunction(); 9226 if (Func.hasFnAttribute("interrupt")) { 9227 if (!Func.getReturnType()->isVoidTy()) 9228 report_fatal_error( 9229 "Functions with the interrupt attribute must have void return type!"); 9230 9231 MachineFunction &MF = DAG.getMachineFunction(); 9232 StringRef Kind = 9233 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9234 9235 if (Kind == "user") 9236 RetOpc = RISCVISD::URET_FLAG; 9237 else if (Kind == "supervisor") 9238 RetOpc = RISCVISD::SRET_FLAG; 9239 else 9240 RetOpc = RISCVISD::MRET_FLAG; 9241 } 9242 9243 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9244 } 9245 9246 void RISCVTargetLowering::validateCCReservedRegs( 9247 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9248 MachineFunction &MF) const { 9249 const Function &F = MF.getFunction(); 9250 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9251 9252 if (llvm::any_of(Regs, [&STI](auto Reg) { 9253 return STI.isRegisterReservedByUser(Reg.first); 9254 })) 9255 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9256 F, "Argument register required, but has been reserved."}); 9257 } 9258 9259 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9260 return CI->isTailCall(); 9261 } 9262 9263 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9264 #define NODE_NAME_CASE(NODE) \ 9265 case RISCVISD::NODE: \ 9266 return "RISCVISD::" #NODE; 9267 // clang-format off 9268 switch ((RISCVISD::NodeType)Opcode) { 9269 case RISCVISD::FIRST_NUMBER: 9270 break; 9271 NODE_NAME_CASE(RET_FLAG) 9272 NODE_NAME_CASE(URET_FLAG) 9273 NODE_NAME_CASE(SRET_FLAG) 9274 NODE_NAME_CASE(MRET_FLAG) 9275 NODE_NAME_CASE(CALL) 9276 NODE_NAME_CASE(SELECT_CC) 9277 NODE_NAME_CASE(BR_CC) 9278 NODE_NAME_CASE(BuildPairF64) 9279 NODE_NAME_CASE(SplitF64) 9280 NODE_NAME_CASE(TAIL) 9281 NODE_NAME_CASE(MULHSU) 9282 NODE_NAME_CASE(SLLW) 9283 NODE_NAME_CASE(SRAW) 9284 NODE_NAME_CASE(SRLW) 9285 NODE_NAME_CASE(DIVW) 9286 NODE_NAME_CASE(DIVUW) 9287 NODE_NAME_CASE(REMUW) 9288 NODE_NAME_CASE(ROLW) 9289 NODE_NAME_CASE(RORW) 9290 NODE_NAME_CASE(CLZW) 9291 NODE_NAME_CASE(CTZW) 9292 NODE_NAME_CASE(FSLW) 9293 NODE_NAME_CASE(FSRW) 9294 NODE_NAME_CASE(FSL) 9295 NODE_NAME_CASE(FSR) 9296 NODE_NAME_CASE(FMV_H_X) 9297 NODE_NAME_CASE(FMV_X_ANYEXTH) 9298 NODE_NAME_CASE(FMV_W_X_RV64) 9299 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9300 NODE_NAME_CASE(FCVT_X_RTZ) 9301 NODE_NAME_CASE(FCVT_XU_RTZ) 9302 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9303 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9304 NODE_NAME_CASE(READ_CYCLE_WIDE) 9305 NODE_NAME_CASE(GREV) 9306 NODE_NAME_CASE(GREVW) 9307 NODE_NAME_CASE(GORC) 9308 NODE_NAME_CASE(GORCW) 9309 NODE_NAME_CASE(SHFL) 9310 NODE_NAME_CASE(SHFLW) 9311 NODE_NAME_CASE(UNSHFL) 9312 NODE_NAME_CASE(UNSHFLW) 9313 NODE_NAME_CASE(BCOMPRESS) 9314 NODE_NAME_CASE(BCOMPRESSW) 9315 NODE_NAME_CASE(BDECOMPRESS) 9316 NODE_NAME_CASE(BDECOMPRESSW) 9317 NODE_NAME_CASE(VMV_V_X_VL) 9318 NODE_NAME_CASE(VFMV_V_F_VL) 9319 NODE_NAME_CASE(VMV_X_S) 9320 NODE_NAME_CASE(VMV_S_X_VL) 9321 NODE_NAME_CASE(VFMV_S_F_VL) 9322 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9323 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9324 NODE_NAME_CASE(READ_VLENB) 9325 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9326 NODE_NAME_CASE(VSLIDEUP_VL) 9327 NODE_NAME_CASE(VSLIDE1UP_VL) 9328 NODE_NAME_CASE(VSLIDEDOWN_VL) 9329 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9330 NODE_NAME_CASE(VID_VL) 9331 NODE_NAME_CASE(VFNCVT_ROD_VL) 9332 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9333 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9334 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9335 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9336 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9337 NODE_NAME_CASE(VECREDUCE_AND_VL) 9338 NODE_NAME_CASE(VECREDUCE_OR_VL) 9339 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9340 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9341 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9342 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9343 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9344 NODE_NAME_CASE(ADD_VL) 9345 NODE_NAME_CASE(AND_VL) 9346 NODE_NAME_CASE(MUL_VL) 9347 NODE_NAME_CASE(OR_VL) 9348 NODE_NAME_CASE(SDIV_VL) 9349 NODE_NAME_CASE(SHL_VL) 9350 NODE_NAME_CASE(SREM_VL) 9351 NODE_NAME_CASE(SRA_VL) 9352 NODE_NAME_CASE(SRL_VL) 9353 NODE_NAME_CASE(SUB_VL) 9354 NODE_NAME_CASE(UDIV_VL) 9355 NODE_NAME_CASE(UREM_VL) 9356 NODE_NAME_CASE(XOR_VL) 9357 NODE_NAME_CASE(SADDSAT_VL) 9358 NODE_NAME_CASE(UADDSAT_VL) 9359 NODE_NAME_CASE(SSUBSAT_VL) 9360 NODE_NAME_CASE(USUBSAT_VL) 9361 NODE_NAME_CASE(FADD_VL) 9362 NODE_NAME_CASE(FSUB_VL) 9363 NODE_NAME_CASE(FMUL_VL) 9364 NODE_NAME_CASE(FDIV_VL) 9365 NODE_NAME_CASE(FNEG_VL) 9366 NODE_NAME_CASE(FABS_VL) 9367 NODE_NAME_CASE(FSQRT_VL) 9368 NODE_NAME_CASE(FMA_VL) 9369 NODE_NAME_CASE(FCOPYSIGN_VL) 9370 NODE_NAME_CASE(SMIN_VL) 9371 NODE_NAME_CASE(SMAX_VL) 9372 NODE_NAME_CASE(UMIN_VL) 9373 NODE_NAME_CASE(UMAX_VL) 9374 NODE_NAME_CASE(FMINNUM_VL) 9375 NODE_NAME_CASE(FMAXNUM_VL) 9376 NODE_NAME_CASE(MULHS_VL) 9377 NODE_NAME_CASE(MULHU_VL) 9378 NODE_NAME_CASE(FP_TO_SINT_VL) 9379 NODE_NAME_CASE(FP_TO_UINT_VL) 9380 NODE_NAME_CASE(SINT_TO_FP_VL) 9381 NODE_NAME_CASE(UINT_TO_FP_VL) 9382 NODE_NAME_CASE(FP_EXTEND_VL) 9383 NODE_NAME_CASE(FP_ROUND_VL) 9384 NODE_NAME_CASE(VWMUL_VL) 9385 NODE_NAME_CASE(VWMULU_VL) 9386 NODE_NAME_CASE(SETCC_VL) 9387 NODE_NAME_CASE(VSELECT_VL) 9388 NODE_NAME_CASE(VMAND_VL) 9389 NODE_NAME_CASE(VMOR_VL) 9390 NODE_NAME_CASE(VMXOR_VL) 9391 NODE_NAME_CASE(VMCLR_VL) 9392 NODE_NAME_CASE(VMSET_VL) 9393 NODE_NAME_CASE(VRGATHER_VX_VL) 9394 NODE_NAME_CASE(VRGATHER_VV_VL) 9395 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9396 NODE_NAME_CASE(VSEXT_VL) 9397 NODE_NAME_CASE(VZEXT_VL) 9398 NODE_NAME_CASE(VCPOP_VL) 9399 NODE_NAME_CASE(VLE_VL) 9400 NODE_NAME_CASE(VSE_VL) 9401 NODE_NAME_CASE(READ_CSR) 9402 NODE_NAME_CASE(WRITE_CSR) 9403 NODE_NAME_CASE(SWAP_CSR) 9404 } 9405 // clang-format on 9406 return nullptr; 9407 #undef NODE_NAME_CASE 9408 } 9409 9410 /// getConstraintType - Given a constraint letter, return the type of 9411 /// constraint it is for this target. 9412 RISCVTargetLowering::ConstraintType 9413 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9414 if (Constraint.size() == 1) { 9415 switch (Constraint[0]) { 9416 default: 9417 break; 9418 case 'f': 9419 return C_RegisterClass; 9420 case 'I': 9421 case 'J': 9422 case 'K': 9423 return C_Immediate; 9424 case 'A': 9425 return C_Memory; 9426 case 'S': // A symbolic address 9427 return C_Other; 9428 } 9429 } else { 9430 if (Constraint == "vr" || Constraint == "vm") 9431 return C_RegisterClass; 9432 } 9433 return TargetLowering::getConstraintType(Constraint); 9434 } 9435 9436 std::pair<unsigned, const TargetRegisterClass *> 9437 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9438 StringRef Constraint, 9439 MVT VT) const { 9440 // First, see if this is a constraint that directly corresponds to a 9441 // RISCV register class. 9442 if (Constraint.size() == 1) { 9443 switch (Constraint[0]) { 9444 case 'r': 9445 return std::make_pair(0U, &RISCV::GPRRegClass); 9446 case 'f': 9447 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9448 return std::make_pair(0U, &RISCV::FPR16RegClass); 9449 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9450 return std::make_pair(0U, &RISCV::FPR32RegClass); 9451 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9452 return std::make_pair(0U, &RISCV::FPR64RegClass); 9453 break; 9454 default: 9455 break; 9456 } 9457 } else { 9458 if (Constraint == "vr") { 9459 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9460 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9461 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9462 return std::make_pair(0U, RC); 9463 } 9464 } else if (Constraint == "vm") { 9465 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9466 return std::make_pair(0U, &RISCV::VMRegClass); 9467 } 9468 } 9469 9470 // Clang will correctly decode the usage of register name aliases into their 9471 // official names. However, other frontends like `rustc` do not. This allows 9472 // users of these frontends to use the ABI names for registers in LLVM-style 9473 // register constraints. 9474 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9475 .Case("{zero}", RISCV::X0) 9476 .Case("{ra}", RISCV::X1) 9477 .Case("{sp}", RISCV::X2) 9478 .Case("{gp}", RISCV::X3) 9479 .Case("{tp}", RISCV::X4) 9480 .Case("{t0}", RISCV::X5) 9481 .Case("{t1}", RISCV::X6) 9482 .Case("{t2}", RISCV::X7) 9483 .Cases("{s0}", "{fp}", RISCV::X8) 9484 .Case("{s1}", RISCV::X9) 9485 .Case("{a0}", RISCV::X10) 9486 .Case("{a1}", RISCV::X11) 9487 .Case("{a2}", RISCV::X12) 9488 .Case("{a3}", RISCV::X13) 9489 .Case("{a4}", RISCV::X14) 9490 .Case("{a5}", RISCV::X15) 9491 .Case("{a6}", RISCV::X16) 9492 .Case("{a7}", RISCV::X17) 9493 .Case("{s2}", RISCV::X18) 9494 .Case("{s3}", RISCV::X19) 9495 .Case("{s4}", RISCV::X20) 9496 .Case("{s5}", RISCV::X21) 9497 .Case("{s6}", RISCV::X22) 9498 .Case("{s7}", RISCV::X23) 9499 .Case("{s8}", RISCV::X24) 9500 .Case("{s9}", RISCV::X25) 9501 .Case("{s10}", RISCV::X26) 9502 .Case("{s11}", RISCV::X27) 9503 .Case("{t3}", RISCV::X28) 9504 .Case("{t4}", RISCV::X29) 9505 .Case("{t5}", RISCV::X30) 9506 .Case("{t6}", RISCV::X31) 9507 .Default(RISCV::NoRegister); 9508 if (XRegFromAlias != RISCV::NoRegister) 9509 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9510 9511 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9512 // TableGen record rather than the AsmName to choose registers for InlineAsm 9513 // constraints, plus we want to match those names to the widest floating point 9514 // register type available, manually select floating point registers here. 9515 // 9516 // The second case is the ABI name of the register, so that frontends can also 9517 // use the ABI names in register constraint lists. 9518 if (Subtarget.hasStdExtF()) { 9519 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9520 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9521 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9522 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9523 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9524 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9525 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9526 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9527 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9528 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9529 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9530 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9531 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9532 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9533 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9534 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9535 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9536 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9537 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9538 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9539 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9540 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9541 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9542 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9543 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9544 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9545 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9546 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9547 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9548 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9549 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9550 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9551 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9552 .Default(RISCV::NoRegister); 9553 if (FReg != RISCV::NoRegister) { 9554 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9555 if (Subtarget.hasStdExtD()) { 9556 unsigned RegNo = FReg - RISCV::F0_F; 9557 unsigned DReg = RISCV::F0_D + RegNo; 9558 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9559 } 9560 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9561 } 9562 } 9563 9564 if (Subtarget.hasVInstructions()) { 9565 Register VReg = StringSwitch<Register>(Constraint.lower()) 9566 .Case("{v0}", RISCV::V0) 9567 .Case("{v1}", RISCV::V1) 9568 .Case("{v2}", RISCV::V2) 9569 .Case("{v3}", RISCV::V3) 9570 .Case("{v4}", RISCV::V4) 9571 .Case("{v5}", RISCV::V5) 9572 .Case("{v6}", RISCV::V6) 9573 .Case("{v7}", RISCV::V7) 9574 .Case("{v8}", RISCV::V8) 9575 .Case("{v9}", RISCV::V9) 9576 .Case("{v10}", RISCV::V10) 9577 .Case("{v11}", RISCV::V11) 9578 .Case("{v12}", RISCV::V12) 9579 .Case("{v13}", RISCV::V13) 9580 .Case("{v14}", RISCV::V14) 9581 .Case("{v15}", RISCV::V15) 9582 .Case("{v16}", RISCV::V16) 9583 .Case("{v17}", RISCV::V17) 9584 .Case("{v18}", RISCV::V18) 9585 .Case("{v19}", RISCV::V19) 9586 .Case("{v20}", RISCV::V20) 9587 .Case("{v21}", RISCV::V21) 9588 .Case("{v22}", RISCV::V22) 9589 .Case("{v23}", RISCV::V23) 9590 .Case("{v24}", RISCV::V24) 9591 .Case("{v25}", RISCV::V25) 9592 .Case("{v26}", RISCV::V26) 9593 .Case("{v27}", RISCV::V27) 9594 .Case("{v28}", RISCV::V28) 9595 .Case("{v29}", RISCV::V29) 9596 .Case("{v30}", RISCV::V30) 9597 .Case("{v31}", RISCV::V31) 9598 .Default(RISCV::NoRegister); 9599 if (VReg != RISCV::NoRegister) { 9600 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9601 return std::make_pair(VReg, &RISCV::VMRegClass); 9602 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9603 return std::make_pair(VReg, &RISCV::VRRegClass); 9604 for (const auto *RC : 9605 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9606 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9607 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9608 return std::make_pair(VReg, RC); 9609 } 9610 } 9611 } 9612 } 9613 9614 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9615 } 9616 9617 unsigned 9618 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9619 // Currently only support length 1 constraints. 9620 if (ConstraintCode.size() == 1) { 9621 switch (ConstraintCode[0]) { 9622 case 'A': 9623 return InlineAsm::Constraint_A; 9624 default: 9625 break; 9626 } 9627 } 9628 9629 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9630 } 9631 9632 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9633 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9634 SelectionDAG &DAG) const { 9635 // Currently only support length 1 constraints. 9636 if (Constraint.length() == 1) { 9637 switch (Constraint[0]) { 9638 case 'I': 9639 // Validate & create a 12-bit signed immediate operand. 9640 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9641 uint64_t CVal = C->getSExtValue(); 9642 if (isInt<12>(CVal)) 9643 Ops.push_back( 9644 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9645 } 9646 return; 9647 case 'J': 9648 // Validate & create an integer zero operand. 9649 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9650 if (C->getZExtValue() == 0) 9651 Ops.push_back( 9652 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9653 return; 9654 case 'K': 9655 // Validate & create a 5-bit unsigned immediate operand. 9656 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9657 uint64_t CVal = C->getZExtValue(); 9658 if (isUInt<5>(CVal)) 9659 Ops.push_back( 9660 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9661 } 9662 return; 9663 case 'S': 9664 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9665 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9666 GA->getValueType(0))); 9667 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9668 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9669 BA->getValueType(0))); 9670 } 9671 return; 9672 default: 9673 break; 9674 } 9675 } 9676 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9677 } 9678 9679 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9680 Instruction *Inst, 9681 AtomicOrdering Ord) const { 9682 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9683 return Builder.CreateFence(Ord); 9684 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9685 return Builder.CreateFence(AtomicOrdering::Release); 9686 return nullptr; 9687 } 9688 9689 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9690 Instruction *Inst, 9691 AtomicOrdering Ord) const { 9692 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9693 return Builder.CreateFence(AtomicOrdering::Acquire); 9694 return nullptr; 9695 } 9696 9697 TargetLowering::AtomicExpansionKind 9698 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9699 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9700 // point operations can't be used in an lr/sc sequence without breaking the 9701 // forward-progress guarantee. 9702 if (AI->isFloatingPointOperation()) 9703 return AtomicExpansionKind::CmpXChg; 9704 9705 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9706 if (Size == 8 || Size == 16) 9707 return AtomicExpansionKind::MaskedIntrinsic; 9708 return AtomicExpansionKind::None; 9709 } 9710 9711 static Intrinsic::ID 9712 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9713 if (XLen == 32) { 9714 switch (BinOp) { 9715 default: 9716 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9717 case AtomicRMWInst::Xchg: 9718 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9719 case AtomicRMWInst::Add: 9720 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9721 case AtomicRMWInst::Sub: 9722 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9723 case AtomicRMWInst::Nand: 9724 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9725 case AtomicRMWInst::Max: 9726 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9727 case AtomicRMWInst::Min: 9728 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9729 case AtomicRMWInst::UMax: 9730 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9731 case AtomicRMWInst::UMin: 9732 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9733 } 9734 } 9735 9736 if (XLen == 64) { 9737 switch (BinOp) { 9738 default: 9739 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9740 case AtomicRMWInst::Xchg: 9741 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9742 case AtomicRMWInst::Add: 9743 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9744 case AtomicRMWInst::Sub: 9745 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9746 case AtomicRMWInst::Nand: 9747 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9748 case AtomicRMWInst::Max: 9749 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9750 case AtomicRMWInst::Min: 9751 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9752 case AtomicRMWInst::UMax: 9753 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9754 case AtomicRMWInst::UMin: 9755 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9756 } 9757 } 9758 9759 llvm_unreachable("Unexpected XLen\n"); 9760 } 9761 9762 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 9763 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 9764 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 9765 unsigned XLen = Subtarget.getXLen(); 9766 Value *Ordering = 9767 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 9768 Type *Tys[] = {AlignedAddr->getType()}; 9769 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 9770 AI->getModule(), 9771 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 9772 9773 if (XLen == 64) { 9774 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 9775 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9776 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 9777 } 9778 9779 Value *Result; 9780 9781 // Must pass the shift amount needed to sign extend the loaded value prior 9782 // to performing a signed comparison for min/max. ShiftAmt is the number of 9783 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 9784 // is the number of bits to left+right shift the value in order to 9785 // sign-extend. 9786 if (AI->getOperation() == AtomicRMWInst::Min || 9787 AI->getOperation() == AtomicRMWInst::Max) { 9788 const DataLayout &DL = AI->getModule()->getDataLayout(); 9789 unsigned ValWidth = 9790 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 9791 Value *SextShamt = 9792 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 9793 Result = Builder.CreateCall(LrwOpScwLoop, 9794 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 9795 } else { 9796 Result = 9797 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 9798 } 9799 9800 if (XLen == 64) 9801 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9802 return Result; 9803 } 9804 9805 TargetLowering::AtomicExpansionKind 9806 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 9807 AtomicCmpXchgInst *CI) const { 9808 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 9809 if (Size == 8 || Size == 16) 9810 return AtomicExpansionKind::MaskedIntrinsic; 9811 return AtomicExpansionKind::None; 9812 } 9813 9814 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 9815 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 9816 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 9817 unsigned XLen = Subtarget.getXLen(); 9818 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 9819 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 9820 if (XLen == 64) { 9821 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 9822 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 9823 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9824 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 9825 } 9826 Type *Tys[] = {AlignedAddr->getType()}; 9827 Function *MaskedCmpXchg = 9828 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 9829 Value *Result = Builder.CreateCall( 9830 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 9831 if (XLen == 64) 9832 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9833 return Result; 9834 } 9835 9836 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 9837 return false; 9838 } 9839 9840 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 9841 EVT VT) const { 9842 VT = VT.getScalarType(); 9843 9844 if (!VT.isSimple()) 9845 return false; 9846 9847 switch (VT.getSimpleVT().SimpleTy) { 9848 case MVT::f16: 9849 return Subtarget.hasStdExtZfh(); 9850 case MVT::f32: 9851 return Subtarget.hasStdExtF(); 9852 case MVT::f64: 9853 return Subtarget.hasStdExtD(); 9854 default: 9855 break; 9856 } 9857 9858 return false; 9859 } 9860 9861 Register RISCVTargetLowering::getExceptionPointerRegister( 9862 const Constant *PersonalityFn) const { 9863 return RISCV::X10; 9864 } 9865 9866 Register RISCVTargetLowering::getExceptionSelectorRegister( 9867 const Constant *PersonalityFn) const { 9868 return RISCV::X11; 9869 } 9870 9871 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 9872 // Return false to suppress the unnecessary extensions if the LibCall 9873 // arguments or return value is f32 type for LP64 ABI. 9874 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 9875 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 9876 return false; 9877 9878 return true; 9879 } 9880 9881 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 9882 if (Subtarget.is64Bit() && Type == MVT::i32) 9883 return true; 9884 9885 return IsSigned; 9886 } 9887 9888 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 9889 SDValue C) const { 9890 // Check integral scalar types. 9891 if (VT.isScalarInteger()) { 9892 // Omit the optimization if the sub target has the M extension and the data 9893 // size exceeds XLen. 9894 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 9895 return false; 9896 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 9897 // Break the MUL to a SLLI and an ADD/SUB. 9898 const APInt &Imm = ConstNode->getAPIntValue(); 9899 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 9900 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 9901 return true; 9902 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 9903 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 9904 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 9905 (Imm - 8).isPowerOf2())) 9906 return true; 9907 // Omit the following optimization if the sub target has the M extension 9908 // and the data size >= XLen. 9909 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 9910 return false; 9911 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 9912 // a pair of LUI/ADDI. 9913 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 9914 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 9915 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 9916 (1 - ImmS).isPowerOf2()) 9917 return true; 9918 } 9919 } 9920 } 9921 9922 return false; 9923 } 9924 9925 bool RISCVTargetLowering::isMulAddWithConstProfitable( 9926 const SDValue &AddNode, const SDValue &ConstNode) const { 9927 // Let the DAGCombiner decide for vectors. 9928 EVT VT = AddNode.getValueType(); 9929 if (VT.isVector()) 9930 return true; 9931 9932 // Let the DAGCombiner decide for larger types. 9933 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 9934 return true; 9935 9936 // It is worse if c1 is simm12 while c1*c2 is not. 9937 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 9938 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 9939 const APInt &C1 = C1Node->getAPIntValue(); 9940 const APInt &C2 = C2Node->getAPIntValue(); 9941 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 9942 return false; 9943 9944 // Default to true and let the DAGCombiner decide. 9945 return true; 9946 } 9947 9948 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 9949 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 9950 bool *Fast) const { 9951 if (!VT.isVector()) 9952 return false; 9953 9954 EVT ElemVT = VT.getVectorElementType(); 9955 if (Alignment >= ElemVT.getStoreSize()) { 9956 if (Fast) 9957 *Fast = true; 9958 return true; 9959 } 9960 9961 return false; 9962 } 9963 9964 bool RISCVTargetLowering::splitValueIntoRegisterParts( 9965 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 9966 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 9967 bool IsABIRegCopy = CC.hasValue(); 9968 EVT ValueVT = Val.getValueType(); 9969 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9970 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 9971 // and cast to f32. 9972 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 9973 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 9974 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 9975 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 9976 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 9977 Parts[0] = Val; 9978 return true; 9979 } 9980 9981 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9982 LLVMContext &Context = *DAG.getContext(); 9983 EVT ValueEltVT = ValueVT.getVectorElementType(); 9984 EVT PartEltVT = PartVT.getVectorElementType(); 9985 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9986 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9987 if (PartVTBitSize % ValueVTBitSize == 0) { 9988 // If the element types are different, bitcast to the same element type of 9989 // PartVT first. 9990 if (ValueEltVT != PartEltVT) { 9991 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9992 assert(Count != 0 && "The number of element should not be zero."); 9993 EVT SameEltTypeVT = 9994 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9995 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 9996 } 9997 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 9998 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9999 Parts[0] = Val; 10000 return true; 10001 } 10002 } 10003 return false; 10004 } 10005 10006 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10007 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10008 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10009 bool IsABIRegCopy = CC.hasValue(); 10010 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10011 SDValue Val = Parts[0]; 10012 10013 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10014 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10015 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10016 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10017 return Val; 10018 } 10019 10020 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10021 LLVMContext &Context = *DAG.getContext(); 10022 SDValue Val = Parts[0]; 10023 EVT ValueEltVT = ValueVT.getVectorElementType(); 10024 EVT PartEltVT = PartVT.getVectorElementType(); 10025 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10026 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10027 if (PartVTBitSize % ValueVTBitSize == 0) { 10028 EVT SameEltTypeVT = ValueVT; 10029 // If the element types are different, convert it to the same element type 10030 // of PartVT. 10031 if (ValueEltVT != PartEltVT) { 10032 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 10033 assert(Count != 0 && "The number of element should not be zero."); 10034 SameEltTypeVT = 10035 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 10036 } 10037 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 10038 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 10039 if (ValueEltVT != PartEltVT) 10040 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 10041 return Val; 10042 } 10043 } 10044 return SDValue(); 10045 } 10046 10047 #define GET_REGISTER_MATCHER 10048 #include "RISCVGenAsmMatcher.inc" 10049 10050 Register 10051 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10052 const MachineFunction &MF) const { 10053 Register Reg = MatchRegisterAltName(RegName); 10054 if (Reg == RISCV::NoRegister) 10055 Reg = MatchRegisterName(RegName); 10056 if (Reg == RISCV::NoRegister) 10057 report_fatal_error( 10058 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10059 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10060 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10061 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10062 StringRef(RegName) + "\".")); 10063 return Reg; 10064 } 10065 10066 namespace llvm { 10067 namespace RISCVVIntrinsicsTable { 10068 10069 #define GET_RISCVVIntrinsicsTable_IMPL 10070 #include "RISCVGenSearchableTables.inc" 10071 10072 } // namespace RISCVVIntrinsicsTable 10073 10074 } // namespace llvm 10075