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 342 if (Subtarget.hasStdExtF()) { 343 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 344 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 345 setOperationAction(ISD::LRINT, MVT::f32, Legal); 346 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 347 setOperationAction(ISD::LROUND, MVT::f32, Legal); 348 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 349 for (auto CC : FPCCToExpand) 350 setCondCodeAction(CC, MVT::f32, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 352 setOperationAction(ISD::SELECT, MVT::f32, Custom); 353 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 354 for (auto Op : FPOpToExpand) 355 setOperationAction(Op, MVT::f32, Expand); 356 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 357 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 358 } 359 360 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 361 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 362 363 if (Subtarget.hasStdExtD()) { 364 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 365 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 366 setOperationAction(ISD::LRINT, MVT::f64, Legal); 367 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 368 setOperationAction(ISD::LROUND, MVT::f64, Legal); 369 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 370 for (auto CC : FPCCToExpand) 371 setCondCodeAction(CC, MVT::f64, Expand); 372 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 373 setOperationAction(ISD::SELECT, MVT::f64, Custom); 374 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 375 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 376 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 377 for (auto Op : FPOpToExpand) 378 setOperationAction(Op, MVT::f64, Expand); 379 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 380 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 381 } 382 383 if (Subtarget.is64Bit()) { 384 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 385 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 386 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 387 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 388 } 389 390 if (Subtarget.hasStdExtF()) { 391 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 392 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 393 394 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 395 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 396 } 397 398 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 399 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 400 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 401 setOperationAction(ISD::JumpTable, XLenVT, Custom); 402 403 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 404 405 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 406 // Unfortunately this can't be determined just from the ISA naming string. 407 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 408 Subtarget.is64Bit() ? Legal : Custom); 409 410 setOperationAction(ISD::TRAP, MVT::Other, Legal); 411 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 412 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 413 if (Subtarget.is64Bit()) 414 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 415 416 if (Subtarget.hasStdExtA()) { 417 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 418 setMinCmpXchgSizeInBits(32); 419 } else { 420 setMaxAtomicSizeInBitsSupported(0); 421 } 422 423 setBooleanContents(ZeroOrOneBooleanContent); 424 425 if (Subtarget.hasVInstructions()) { 426 setBooleanVectorContents(ZeroOrOneBooleanContent); 427 428 setOperationAction(ISD::VSCALE, XLenVT, Custom); 429 430 // RVV intrinsics may have illegal operands. 431 // We also need to custom legalize vmv.x.s. 432 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 433 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 434 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 435 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 436 if (Subtarget.is64Bit()) { 437 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 438 } else { 439 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 440 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 441 } 442 443 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 444 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 445 446 static const unsigned IntegerVPOps[] = { 447 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 448 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 449 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 450 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 451 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 452 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 453 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}; 454 455 static const unsigned FloatingPointVPOps[] = { 456 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 457 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 458 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX}; 459 460 if (!Subtarget.is64Bit()) { 461 // We must custom-lower certain vXi64 operations on RV32 due to the vector 462 // element type being illegal. 463 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 464 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 465 466 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 467 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 468 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 469 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 470 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 471 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 472 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 473 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 474 475 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 476 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 477 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 478 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 479 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 480 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 481 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 482 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 483 } 484 485 for (MVT VT : BoolVecVTs) { 486 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 487 488 // Mask VTs are custom-expanded into a series of standard nodes 489 setOperationAction(ISD::TRUNCATE, VT, Custom); 490 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 491 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 492 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 493 494 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 495 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 496 497 setOperationAction(ISD::SELECT, VT, Custom); 498 setOperationAction(ISD::SELECT_CC, VT, Expand); 499 setOperationAction(ISD::VSELECT, VT, Expand); 500 501 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 502 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 503 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 504 505 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 506 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 507 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 508 509 // RVV has native int->float & float->int conversions where the 510 // element type sizes are within one power-of-two of each other. Any 511 // wider distances between type sizes have to be lowered as sequences 512 // which progressively narrow the gap in stages. 513 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 514 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 515 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 516 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 517 518 // Expand all extending loads to types larger than this, and truncating 519 // stores from types larger than this. 520 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 521 setTruncStoreAction(OtherVT, VT, Expand); 522 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 523 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 524 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 525 } 526 } 527 528 for (MVT VT : IntVecVTs) { 529 if (VT.getVectorElementType() == MVT::i64 && 530 !Subtarget.hasVInstructionsI64()) 531 continue; 532 533 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 534 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 535 536 // Vectors implement MULHS/MULHU. 537 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 538 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 539 540 setOperationAction(ISD::SMIN, VT, Legal); 541 setOperationAction(ISD::SMAX, VT, Legal); 542 setOperationAction(ISD::UMIN, VT, Legal); 543 setOperationAction(ISD::UMAX, VT, Legal); 544 545 setOperationAction(ISD::ROTL, VT, Expand); 546 setOperationAction(ISD::ROTR, VT, Expand); 547 548 setOperationAction(ISD::CTTZ, VT, Expand); 549 setOperationAction(ISD::CTLZ, VT, Expand); 550 setOperationAction(ISD::CTPOP, VT, Expand); 551 552 setOperationAction(ISD::BSWAP, VT, Expand); 553 554 // Custom-lower extensions and truncations from/to mask types. 555 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 556 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 557 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 558 559 // RVV has native int->float & float->int conversions where the 560 // element type sizes are within one power-of-two of each other. Any 561 // wider distances between type sizes have to be lowered as sequences 562 // which progressively narrow the gap in stages. 563 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 564 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 565 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 566 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 567 568 setOperationAction(ISD::SADDSAT, VT, Legal); 569 setOperationAction(ISD::UADDSAT, VT, Legal); 570 setOperationAction(ISD::SSUBSAT, VT, Legal); 571 setOperationAction(ISD::USUBSAT, VT, Legal); 572 573 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 574 // nodes which truncate by one power of two at a time. 575 setOperationAction(ISD::TRUNCATE, VT, Custom); 576 577 // Custom-lower insert/extract operations to simplify patterns. 578 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 579 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 580 581 // Custom-lower reduction operations to set up the corresponding custom 582 // nodes' operands. 583 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 584 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 585 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 586 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 587 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 588 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 589 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 590 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 591 592 for (unsigned VPOpc : IntegerVPOps) 593 setOperationAction(VPOpc, VT, Custom); 594 595 setOperationAction(ISD::LOAD, VT, Custom); 596 setOperationAction(ISD::STORE, VT, Custom); 597 598 setOperationAction(ISD::MLOAD, VT, Custom); 599 setOperationAction(ISD::MSTORE, VT, Custom); 600 setOperationAction(ISD::MGATHER, VT, Custom); 601 setOperationAction(ISD::MSCATTER, VT, Custom); 602 603 setOperationAction(ISD::VP_LOAD, VT, Custom); 604 setOperationAction(ISD::VP_STORE, VT, Custom); 605 setOperationAction(ISD::VP_GATHER, VT, Custom); 606 setOperationAction(ISD::VP_SCATTER, VT, Custom); 607 608 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 609 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 610 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 611 612 setOperationAction(ISD::SELECT, VT, Custom); 613 setOperationAction(ISD::SELECT_CC, VT, Expand); 614 615 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 616 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 617 618 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 619 setTruncStoreAction(VT, OtherVT, Expand); 620 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 621 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 622 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 623 } 624 } 625 626 // Expand various CCs to best match the RVV ISA, which natively supports UNE 627 // but no other unordered comparisons, and supports all ordered comparisons 628 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 629 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 630 // and we pattern-match those back to the "original", swapping operands once 631 // more. This way we catch both operations and both "vf" and "fv" forms with 632 // fewer patterns. 633 static const ISD::CondCode VFPCCToExpand[] = { 634 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 635 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 636 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 637 }; 638 639 // Sets common operation actions on RVV floating-point vector types. 640 const auto SetCommonVFPActions = [&](MVT VT) { 641 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 642 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 643 // sizes are within one power-of-two of each other. Therefore conversions 644 // between vXf16 and vXf64 must be lowered as sequences which convert via 645 // vXf32. 646 setOperationAction(ISD::FP_ROUND, VT, Custom); 647 setOperationAction(ISD::FP_EXTEND, VT, Custom); 648 // Custom-lower insert/extract operations to simplify patterns. 649 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 650 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 651 // Expand various condition codes (explained above). 652 for (auto CC : VFPCCToExpand) 653 setCondCodeAction(CC, VT, Expand); 654 655 setOperationAction(ISD::FMINNUM, VT, Legal); 656 setOperationAction(ISD::FMAXNUM, VT, Legal); 657 658 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 659 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 660 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 661 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 662 663 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 664 665 setOperationAction(ISD::LOAD, VT, Custom); 666 setOperationAction(ISD::STORE, VT, Custom); 667 668 setOperationAction(ISD::MLOAD, VT, Custom); 669 setOperationAction(ISD::MSTORE, VT, Custom); 670 setOperationAction(ISD::MGATHER, VT, Custom); 671 setOperationAction(ISD::MSCATTER, VT, Custom); 672 673 setOperationAction(ISD::VP_LOAD, VT, Custom); 674 setOperationAction(ISD::VP_STORE, VT, Custom); 675 setOperationAction(ISD::VP_GATHER, VT, Custom); 676 setOperationAction(ISD::VP_SCATTER, VT, Custom); 677 678 setOperationAction(ISD::SELECT, VT, Custom); 679 setOperationAction(ISD::SELECT_CC, VT, Expand); 680 681 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 682 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 683 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 684 685 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 686 687 for (unsigned VPOpc : FloatingPointVPOps) 688 setOperationAction(VPOpc, VT, Custom); 689 }; 690 691 // Sets common extload/truncstore actions on RVV floating-point vector 692 // types. 693 const auto SetCommonVFPExtLoadTruncStoreActions = 694 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 695 for (auto SmallVT : SmallerVTs) { 696 setTruncStoreAction(VT, SmallVT, Expand); 697 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 698 } 699 }; 700 701 if (Subtarget.hasVInstructionsF16()) 702 for (MVT VT : F16VecVTs) 703 SetCommonVFPActions(VT); 704 705 for (MVT VT : F32VecVTs) { 706 if (Subtarget.hasVInstructionsF32()) 707 SetCommonVFPActions(VT); 708 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 709 } 710 711 for (MVT VT : F64VecVTs) { 712 if (Subtarget.hasVInstructionsF64()) 713 SetCommonVFPActions(VT); 714 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 715 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 716 } 717 718 if (Subtarget.useRVVForFixedLengthVectors()) { 719 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 720 if (!useRVVForFixedLengthVectorVT(VT)) 721 continue; 722 723 // By default everything must be expanded. 724 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 725 setOperationAction(Op, VT, Expand); 726 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 727 setTruncStoreAction(VT, OtherVT, Expand); 728 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 729 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 730 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 731 } 732 733 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 734 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 735 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 736 737 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 738 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 739 740 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 741 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 742 743 setOperationAction(ISD::LOAD, VT, Custom); 744 setOperationAction(ISD::STORE, VT, Custom); 745 746 setOperationAction(ISD::SETCC, VT, Custom); 747 748 setOperationAction(ISD::SELECT, VT, Custom); 749 750 setOperationAction(ISD::TRUNCATE, VT, Custom); 751 752 setOperationAction(ISD::BITCAST, VT, Custom); 753 754 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 755 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 756 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 757 758 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 759 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 760 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 761 762 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 763 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 764 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 765 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 766 767 // Operations below are different for between masks and other vectors. 768 if (VT.getVectorElementType() == MVT::i1) { 769 setOperationAction(ISD::AND, VT, Custom); 770 setOperationAction(ISD::OR, VT, Custom); 771 setOperationAction(ISD::XOR, VT, Custom); 772 continue; 773 } 774 775 // Use SPLAT_VECTOR to prevent type legalization from destroying the 776 // splats when type legalizing i64 scalar on RV32. 777 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 778 // improvements first. 779 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 780 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 781 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 782 } 783 784 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 785 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 786 787 setOperationAction(ISD::MLOAD, VT, Custom); 788 setOperationAction(ISD::MSTORE, VT, Custom); 789 setOperationAction(ISD::MGATHER, VT, Custom); 790 setOperationAction(ISD::MSCATTER, VT, Custom); 791 792 setOperationAction(ISD::VP_LOAD, VT, Custom); 793 setOperationAction(ISD::VP_STORE, VT, Custom); 794 setOperationAction(ISD::VP_GATHER, VT, Custom); 795 setOperationAction(ISD::VP_SCATTER, VT, Custom); 796 797 setOperationAction(ISD::ADD, VT, Custom); 798 setOperationAction(ISD::MUL, VT, Custom); 799 setOperationAction(ISD::SUB, VT, Custom); 800 setOperationAction(ISD::AND, VT, Custom); 801 setOperationAction(ISD::OR, VT, Custom); 802 setOperationAction(ISD::XOR, VT, Custom); 803 setOperationAction(ISD::SDIV, VT, Custom); 804 setOperationAction(ISD::SREM, VT, Custom); 805 setOperationAction(ISD::UDIV, VT, Custom); 806 setOperationAction(ISD::UREM, VT, Custom); 807 setOperationAction(ISD::SHL, VT, Custom); 808 setOperationAction(ISD::SRA, VT, Custom); 809 setOperationAction(ISD::SRL, VT, Custom); 810 811 setOperationAction(ISD::SMIN, VT, Custom); 812 setOperationAction(ISD::SMAX, VT, Custom); 813 setOperationAction(ISD::UMIN, VT, Custom); 814 setOperationAction(ISD::UMAX, VT, Custom); 815 setOperationAction(ISD::ABS, VT, Custom); 816 817 setOperationAction(ISD::MULHS, VT, Custom); 818 setOperationAction(ISD::MULHU, VT, Custom); 819 820 setOperationAction(ISD::SADDSAT, VT, Custom); 821 setOperationAction(ISD::UADDSAT, VT, Custom); 822 setOperationAction(ISD::SSUBSAT, VT, Custom); 823 setOperationAction(ISD::USUBSAT, VT, Custom); 824 825 setOperationAction(ISD::VSELECT, VT, Custom); 826 setOperationAction(ISD::SELECT_CC, VT, Expand); 827 828 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 829 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 830 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 831 832 // Custom-lower reduction operations to set up the corresponding custom 833 // nodes' operands. 834 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 835 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 836 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 837 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 838 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 839 840 for (unsigned VPOpc : IntegerVPOps) 841 setOperationAction(VPOpc, VT, Custom); 842 } 843 844 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 845 if (!useRVVForFixedLengthVectorVT(VT)) 846 continue; 847 848 // By default everything must be expanded. 849 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 850 setOperationAction(Op, VT, Expand); 851 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 852 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 853 setTruncStoreAction(VT, OtherVT, Expand); 854 } 855 856 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 857 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 858 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 859 860 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 861 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 862 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 863 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 864 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 865 866 setOperationAction(ISD::LOAD, VT, Custom); 867 setOperationAction(ISD::STORE, VT, Custom); 868 setOperationAction(ISD::MLOAD, VT, Custom); 869 setOperationAction(ISD::MSTORE, VT, Custom); 870 setOperationAction(ISD::MGATHER, VT, Custom); 871 setOperationAction(ISD::MSCATTER, VT, Custom); 872 873 setOperationAction(ISD::VP_LOAD, VT, Custom); 874 setOperationAction(ISD::VP_STORE, VT, Custom); 875 setOperationAction(ISD::VP_GATHER, VT, Custom); 876 setOperationAction(ISD::VP_SCATTER, VT, Custom); 877 878 setOperationAction(ISD::FADD, VT, Custom); 879 setOperationAction(ISD::FSUB, VT, Custom); 880 setOperationAction(ISD::FMUL, VT, Custom); 881 setOperationAction(ISD::FDIV, VT, Custom); 882 setOperationAction(ISD::FNEG, VT, Custom); 883 setOperationAction(ISD::FABS, VT, Custom); 884 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 885 setOperationAction(ISD::FSQRT, VT, Custom); 886 setOperationAction(ISD::FMA, VT, Custom); 887 setOperationAction(ISD::FMINNUM, VT, Custom); 888 setOperationAction(ISD::FMAXNUM, VT, Custom); 889 890 setOperationAction(ISD::FP_ROUND, VT, Custom); 891 setOperationAction(ISD::FP_EXTEND, VT, Custom); 892 893 for (auto CC : VFPCCToExpand) 894 setCondCodeAction(CC, VT, Expand); 895 896 setOperationAction(ISD::VSELECT, VT, Custom); 897 setOperationAction(ISD::SELECT, VT, Custom); 898 setOperationAction(ISD::SELECT_CC, VT, Expand); 899 900 setOperationAction(ISD::BITCAST, VT, Custom); 901 902 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 903 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 904 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 905 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 906 907 for (unsigned VPOpc : FloatingPointVPOps) 908 setOperationAction(VPOpc, VT, Custom); 909 } 910 911 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 912 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 913 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 914 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 915 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 916 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 917 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 918 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 919 } 920 } 921 922 // Function alignments. 923 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 924 setMinFunctionAlignment(FunctionAlignment); 925 setPrefFunctionAlignment(FunctionAlignment); 926 927 setMinimumJumpTableEntries(5); 928 929 // Jumps are expensive, compared to logic 930 setJumpIsExpensive(); 931 932 // We can use any register for comparisons 933 setHasMultipleConditionRegisters(); 934 935 setTargetDAGCombine(ISD::ADD); 936 setTargetDAGCombine(ISD::SUB); 937 setTargetDAGCombine(ISD::AND); 938 setTargetDAGCombine(ISD::OR); 939 setTargetDAGCombine(ISD::XOR); 940 setTargetDAGCombine(ISD::ANY_EXTEND); 941 setTargetDAGCombine(ISD::ZERO_EXTEND); 942 if (Subtarget.hasVInstructions()) { 943 setTargetDAGCombine(ISD::FCOPYSIGN); 944 setTargetDAGCombine(ISD::MGATHER); 945 setTargetDAGCombine(ISD::MSCATTER); 946 setTargetDAGCombine(ISD::VP_GATHER); 947 setTargetDAGCombine(ISD::VP_SCATTER); 948 setTargetDAGCombine(ISD::SRA); 949 setTargetDAGCombine(ISD::SRL); 950 setTargetDAGCombine(ISD::SHL); 951 setTargetDAGCombine(ISD::STORE); 952 } 953 } 954 955 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 956 LLVMContext &Context, 957 EVT VT) const { 958 if (!VT.isVector()) 959 return getPointerTy(DL); 960 if (Subtarget.hasVInstructions() && 961 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 962 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 963 return VT.changeVectorElementTypeToInteger(); 964 } 965 966 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 967 return Subtarget.getXLenVT(); 968 } 969 970 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 971 const CallInst &I, 972 MachineFunction &MF, 973 unsigned Intrinsic) const { 974 auto &DL = I.getModule()->getDataLayout(); 975 switch (Intrinsic) { 976 default: 977 return false; 978 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 979 case Intrinsic::riscv_masked_atomicrmw_add_i32: 980 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 981 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 982 case Intrinsic::riscv_masked_atomicrmw_max_i32: 983 case Intrinsic::riscv_masked_atomicrmw_min_i32: 984 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 985 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 986 case Intrinsic::riscv_masked_cmpxchg_i32: { 987 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 988 Info.opc = ISD::INTRINSIC_W_CHAIN; 989 Info.memVT = MVT::getVT(PtrTy->getElementType()); 990 Info.ptrVal = I.getArgOperand(0); 991 Info.offset = 0; 992 Info.align = Align(4); 993 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 994 MachineMemOperand::MOVolatile; 995 return true; 996 } 997 case Intrinsic::riscv_masked_strided_load: 998 Info.opc = ISD::INTRINSIC_W_CHAIN; 999 Info.ptrVal = I.getArgOperand(1); 1000 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1001 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1002 Info.size = MemoryLocation::UnknownSize; 1003 Info.flags |= MachineMemOperand::MOLoad; 1004 return true; 1005 case Intrinsic::riscv_masked_strided_store: 1006 Info.opc = ISD::INTRINSIC_VOID; 1007 Info.ptrVal = I.getArgOperand(1); 1008 Info.memVT = 1009 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1010 Info.align = Align( 1011 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1012 8); 1013 Info.size = MemoryLocation::UnknownSize; 1014 Info.flags |= MachineMemOperand::MOStore; 1015 return true; 1016 } 1017 } 1018 1019 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1020 const AddrMode &AM, Type *Ty, 1021 unsigned AS, 1022 Instruction *I) const { 1023 // No global is ever allowed as a base. 1024 if (AM.BaseGV) 1025 return false; 1026 1027 // Require a 12-bit signed offset. 1028 if (!isInt<12>(AM.BaseOffs)) 1029 return false; 1030 1031 switch (AM.Scale) { 1032 case 0: // "r+i" or just "i", depending on HasBaseReg. 1033 break; 1034 case 1: 1035 if (!AM.HasBaseReg) // allow "r+i". 1036 break; 1037 return false; // disallow "r+r" or "r+r+i". 1038 default: 1039 return false; 1040 } 1041 1042 return true; 1043 } 1044 1045 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1046 return isInt<12>(Imm); 1047 } 1048 1049 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1050 return isInt<12>(Imm); 1051 } 1052 1053 // On RV32, 64-bit integers are split into their high and low parts and held 1054 // in two different registers, so the trunc is free since the low register can 1055 // just be used. 1056 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1057 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1058 return false; 1059 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1060 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1061 return (SrcBits == 64 && DestBits == 32); 1062 } 1063 1064 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1065 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1066 !SrcVT.isInteger() || !DstVT.isInteger()) 1067 return false; 1068 unsigned SrcBits = SrcVT.getSizeInBits(); 1069 unsigned DestBits = DstVT.getSizeInBits(); 1070 return (SrcBits == 64 && DestBits == 32); 1071 } 1072 1073 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1074 // Zexts are free if they can be combined with a load. 1075 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1076 EVT MemVT = LD->getMemoryVT(); 1077 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1078 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1079 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1080 LD->getExtensionType() == ISD::ZEXTLOAD)) 1081 return true; 1082 } 1083 1084 return TargetLowering::isZExtFree(Val, VT2); 1085 } 1086 1087 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1088 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1089 } 1090 1091 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1092 return Subtarget.hasStdExtZbb(); 1093 } 1094 1095 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1096 return Subtarget.hasStdExtZbb(); 1097 } 1098 1099 /// Check if sinking \p I's operands to I's basic block is profitable, because 1100 /// the operands can be folded into a target instruction, e.g. 1101 /// splats of scalars can fold into vector instructions. 1102 bool RISCVTargetLowering::shouldSinkOperands( 1103 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1104 using namespace llvm::PatternMatch; 1105 1106 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1107 return false; 1108 1109 auto IsSinker = [&](Instruction *I, int Operand) { 1110 switch (I->getOpcode()) { 1111 case Instruction::Add: 1112 case Instruction::Sub: 1113 case Instruction::Mul: 1114 case Instruction::And: 1115 case Instruction::Or: 1116 case Instruction::Xor: 1117 case Instruction::FAdd: 1118 case Instruction::FSub: 1119 case Instruction::FMul: 1120 case Instruction::FDiv: 1121 case Instruction::ICmp: 1122 case Instruction::FCmp: 1123 return true; 1124 case Instruction::Shl: 1125 case Instruction::LShr: 1126 case Instruction::AShr: 1127 return Operand == 1; 1128 case Instruction::Call: 1129 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1130 switch (II->getIntrinsicID()) { 1131 case Intrinsic::fma: 1132 return Operand == 0 || Operand == 1; 1133 default: 1134 return false; 1135 } 1136 } 1137 return false; 1138 default: 1139 return false; 1140 } 1141 }; 1142 1143 for (auto OpIdx : enumerate(I->operands())) { 1144 if (!IsSinker(I, OpIdx.index())) 1145 continue; 1146 1147 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1148 // Make sure we are not already sinking this operand 1149 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1150 continue; 1151 1152 // We are looking for a splat that can be sunk. 1153 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1154 m_Undef(), m_ZeroMask()))) 1155 continue; 1156 1157 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1158 // and vector registers 1159 for (Use &U : Op->uses()) { 1160 Instruction *Insn = cast<Instruction>(U.getUser()); 1161 if (!IsSinker(Insn, U.getOperandNo())) 1162 return false; 1163 } 1164 1165 Ops.push_back(&Op->getOperandUse(0)); 1166 Ops.push_back(&OpIdx.value()); 1167 } 1168 return true; 1169 } 1170 1171 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1172 bool ForCodeSize) const { 1173 if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin()) 1174 return false; 1175 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1176 return false; 1177 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1178 return false; 1179 if (Imm.isNegZero()) 1180 return false; 1181 return Imm.isZero(); 1182 } 1183 1184 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1185 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1186 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1187 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1188 } 1189 1190 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1191 CallingConv::ID CC, 1192 EVT VT) const { 1193 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1194 // We might still end up using a GPR but that will be decided based on ABI. 1195 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1196 return MVT::f32; 1197 1198 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1199 } 1200 1201 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1202 CallingConv::ID CC, 1203 EVT VT) const { 1204 // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled. 1205 // We might still end up using a GPR but that will be decided based on ABI. 1206 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin()) 1207 return 1; 1208 1209 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1210 } 1211 1212 // Changes the condition code and swaps operands if necessary, so the SetCC 1213 // operation matches one of the comparisons supported directly by branches 1214 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1215 // with 1/-1. 1216 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1217 ISD::CondCode &CC, SelectionDAG &DAG) { 1218 // Convert X > -1 to X >= 0. 1219 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1220 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1221 CC = ISD::SETGE; 1222 return; 1223 } 1224 // Convert X < 1 to 0 >= X. 1225 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1226 RHS = LHS; 1227 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1228 CC = ISD::SETGE; 1229 return; 1230 } 1231 1232 switch (CC) { 1233 default: 1234 break; 1235 case ISD::SETGT: 1236 case ISD::SETLE: 1237 case ISD::SETUGT: 1238 case ISD::SETULE: 1239 CC = ISD::getSetCCSwappedOperands(CC); 1240 std::swap(LHS, RHS); 1241 break; 1242 } 1243 } 1244 1245 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1246 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1247 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1248 if (VT.getVectorElementType() == MVT::i1) 1249 KnownSize *= 8; 1250 1251 switch (KnownSize) { 1252 default: 1253 llvm_unreachable("Invalid LMUL."); 1254 case 8: 1255 return RISCVII::VLMUL::LMUL_F8; 1256 case 16: 1257 return RISCVII::VLMUL::LMUL_F4; 1258 case 32: 1259 return RISCVII::VLMUL::LMUL_F2; 1260 case 64: 1261 return RISCVII::VLMUL::LMUL_1; 1262 case 128: 1263 return RISCVII::VLMUL::LMUL_2; 1264 case 256: 1265 return RISCVII::VLMUL::LMUL_4; 1266 case 512: 1267 return RISCVII::VLMUL::LMUL_8; 1268 } 1269 } 1270 1271 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1272 switch (LMul) { 1273 default: 1274 llvm_unreachable("Invalid LMUL."); 1275 case RISCVII::VLMUL::LMUL_F8: 1276 case RISCVII::VLMUL::LMUL_F4: 1277 case RISCVII::VLMUL::LMUL_F2: 1278 case RISCVII::VLMUL::LMUL_1: 1279 return RISCV::VRRegClassID; 1280 case RISCVII::VLMUL::LMUL_2: 1281 return RISCV::VRM2RegClassID; 1282 case RISCVII::VLMUL::LMUL_4: 1283 return RISCV::VRM4RegClassID; 1284 case RISCVII::VLMUL::LMUL_8: 1285 return RISCV::VRM8RegClassID; 1286 } 1287 } 1288 1289 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1290 RISCVII::VLMUL LMUL = getLMUL(VT); 1291 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1292 LMUL == RISCVII::VLMUL::LMUL_F4 || 1293 LMUL == RISCVII::VLMUL::LMUL_F2 || 1294 LMUL == RISCVII::VLMUL::LMUL_1) { 1295 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1296 "Unexpected subreg numbering"); 1297 return RISCV::sub_vrm1_0 + Index; 1298 } 1299 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1300 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1301 "Unexpected subreg numbering"); 1302 return RISCV::sub_vrm2_0 + Index; 1303 } 1304 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1305 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1306 "Unexpected subreg numbering"); 1307 return RISCV::sub_vrm4_0 + Index; 1308 } 1309 llvm_unreachable("Invalid vector type."); 1310 } 1311 1312 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1313 if (VT.getVectorElementType() == MVT::i1) 1314 return RISCV::VRRegClassID; 1315 return getRegClassIDForLMUL(getLMUL(VT)); 1316 } 1317 1318 // Attempt to decompose a subvector insert/extract between VecVT and 1319 // SubVecVT via subregister indices. Returns the subregister index that 1320 // can perform the subvector insert/extract with the given element index, as 1321 // well as the index corresponding to any leftover subvectors that must be 1322 // further inserted/extracted within the register class for SubVecVT. 1323 std::pair<unsigned, unsigned> 1324 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1325 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1326 const RISCVRegisterInfo *TRI) { 1327 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1328 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1329 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1330 "Register classes not ordered"); 1331 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1332 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1333 // Try to compose a subregister index that takes us from the incoming 1334 // LMUL>1 register class down to the outgoing one. At each step we half 1335 // the LMUL: 1336 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1337 // Note that this is not guaranteed to find a subregister index, such as 1338 // when we are extracting from one VR type to another. 1339 unsigned SubRegIdx = RISCV::NoSubRegister; 1340 for (const unsigned RCID : 1341 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1342 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1343 VecVT = VecVT.getHalfNumVectorElementsVT(); 1344 bool IsHi = 1345 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1346 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1347 getSubregIndexByMVT(VecVT, IsHi)); 1348 if (IsHi) 1349 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1350 } 1351 return {SubRegIdx, InsertExtractIdx}; 1352 } 1353 1354 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1355 // stores for those types. 1356 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1357 return !Subtarget.useRVVForFixedLengthVectors() || 1358 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1359 } 1360 1361 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1362 if (ScalarTy->isPointerTy()) 1363 return true; 1364 1365 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1366 ScalarTy->isIntegerTy(32)) 1367 return true; 1368 1369 if (ScalarTy->isIntegerTy(64)) 1370 return Subtarget.hasVInstructionsI64(); 1371 1372 if (ScalarTy->isHalfTy()) 1373 return Subtarget.hasVInstructionsF16(); 1374 if (ScalarTy->isFloatTy()) 1375 return Subtarget.hasVInstructionsF32(); 1376 if (ScalarTy->isDoubleTy()) 1377 return Subtarget.hasVInstructionsF64(); 1378 1379 return false; 1380 } 1381 1382 static bool useRVVForFixedLengthVectorVT(MVT VT, 1383 const RISCVSubtarget &Subtarget) { 1384 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1385 if (!Subtarget.useRVVForFixedLengthVectors()) 1386 return false; 1387 1388 // We only support a set of vector types with a consistent maximum fixed size 1389 // across all supported vector element types to avoid legalization issues. 1390 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1391 // fixed-length vector type we support is 1024 bytes. 1392 if (VT.getFixedSizeInBits() > 1024 * 8) 1393 return false; 1394 1395 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1396 1397 MVT EltVT = VT.getVectorElementType(); 1398 1399 // Don't use RVV for vectors we cannot scalarize if required. 1400 switch (EltVT.SimpleTy) { 1401 // i1 is supported but has different rules. 1402 default: 1403 return false; 1404 case MVT::i1: 1405 // Masks can only use a single register. 1406 if (VT.getVectorNumElements() > MinVLen) 1407 return false; 1408 MinVLen /= 8; 1409 break; 1410 case MVT::i8: 1411 case MVT::i16: 1412 case MVT::i32: 1413 break; 1414 case MVT::i64: 1415 if (!Subtarget.hasVInstructionsI64()) 1416 return false; 1417 break; 1418 case MVT::f16: 1419 if (!Subtarget.hasVInstructionsF16()) 1420 return false; 1421 break; 1422 case MVT::f32: 1423 if (!Subtarget.hasVInstructionsF32()) 1424 return false; 1425 break; 1426 case MVT::f64: 1427 if (!Subtarget.hasVInstructionsF64()) 1428 return false; 1429 break; 1430 } 1431 1432 // Reject elements larger than ELEN. 1433 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1434 return false; 1435 1436 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1437 // Don't use RVV for types that don't fit. 1438 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1439 return false; 1440 1441 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1442 // the base fixed length RVV support in place. 1443 if (!VT.isPow2VectorType()) 1444 return false; 1445 1446 return true; 1447 } 1448 1449 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1450 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1451 } 1452 1453 // Return the largest legal scalable vector type that matches VT's element type. 1454 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1455 const RISCVSubtarget &Subtarget) { 1456 // This may be called before legal types are setup. 1457 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1458 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1459 "Expected legal fixed length vector!"); 1460 1461 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1462 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1463 1464 MVT EltVT = VT.getVectorElementType(); 1465 switch (EltVT.SimpleTy) { 1466 default: 1467 llvm_unreachable("unexpected element type for RVV container"); 1468 case MVT::i1: 1469 case MVT::i8: 1470 case MVT::i16: 1471 case MVT::i32: 1472 case MVT::i64: 1473 case MVT::f16: 1474 case MVT::f32: 1475 case MVT::f64: { 1476 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1477 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1478 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1479 unsigned NumElts = 1480 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1481 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1482 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1483 return MVT::getScalableVectorVT(EltVT, NumElts); 1484 } 1485 } 1486 } 1487 1488 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1489 const RISCVSubtarget &Subtarget) { 1490 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1491 Subtarget); 1492 } 1493 1494 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1495 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1496 } 1497 1498 // Grow V to consume an entire RVV register. 1499 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1500 const RISCVSubtarget &Subtarget) { 1501 assert(VT.isScalableVector() && 1502 "Expected to convert into a scalable vector!"); 1503 assert(V.getValueType().isFixedLengthVector() && 1504 "Expected a fixed length vector operand!"); 1505 SDLoc DL(V); 1506 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1507 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1508 } 1509 1510 // Shrink V so it's just big enough to maintain a VT's worth of data. 1511 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1512 const RISCVSubtarget &Subtarget) { 1513 assert(VT.isFixedLengthVector() && 1514 "Expected to convert into a fixed length vector!"); 1515 assert(V.getValueType().isScalableVector() && 1516 "Expected a scalable vector operand!"); 1517 SDLoc DL(V); 1518 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1519 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1520 } 1521 1522 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1523 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1524 // the vector type that it is contained in. 1525 static std::pair<SDValue, SDValue> 1526 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1527 const RISCVSubtarget &Subtarget) { 1528 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1529 MVT XLenVT = Subtarget.getXLenVT(); 1530 SDValue VL = VecVT.isFixedLengthVector() 1531 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1532 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1533 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1534 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1535 return {Mask, VL}; 1536 } 1537 1538 // As above but assuming the given type is a scalable vector type. 1539 static std::pair<SDValue, SDValue> 1540 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1541 const RISCVSubtarget &Subtarget) { 1542 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1543 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1544 } 1545 1546 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1547 // of either is (currently) supported. This can get us into an infinite loop 1548 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1549 // as a ..., etc. 1550 // Until either (or both) of these can reliably lower any node, reporting that 1551 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1552 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1553 // which is not desirable. 1554 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1555 EVT VT, unsigned DefinedValues) const { 1556 return false; 1557 } 1558 1559 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1560 // Only splats are currently supported. 1561 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1562 return true; 1563 1564 return false; 1565 } 1566 1567 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1568 // RISCV FP-to-int conversions saturate to the destination register size, but 1569 // don't produce 0 for nan. We can use a conversion instruction and fix the 1570 // nan case with a compare and a select. 1571 SDValue Src = Op.getOperand(0); 1572 1573 EVT DstVT = Op.getValueType(); 1574 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1575 1576 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1577 unsigned Opc; 1578 if (SatVT == DstVT) 1579 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1580 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1581 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1582 else 1583 return SDValue(); 1584 // FIXME: Support other SatVTs by clamping before or after the conversion. 1585 1586 SDLoc DL(Op); 1587 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1588 1589 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1590 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1591 } 1592 1593 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1594 const RISCVSubtarget &Subtarget) { 1595 MVT VT = Op.getSimpleValueType(); 1596 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1597 1598 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1599 1600 SDLoc DL(Op); 1601 SDValue Mask, VL; 1602 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1603 1604 unsigned Opc = 1605 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1606 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1607 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1608 } 1609 1610 struct VIDSequence { 1611 int64_t StepNumerator; 1612 unsigned StepDenominator; 1613 int64_t Addend; 1614 }; 1615 1616 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1617 // to the (non-zero) step S and start value X. This can be then lowered as the 1618 // RVV sequence (VID * S) + X, for example. 1619 // The step S is represented as an integer numerator divided by a positive 1620 // denominator. Note that the implementation currently only identifies 1621 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1622 // cannot detect 2/3, for example. 1623 // Note that this method will also match potentially unappealing index 1624 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1625 // determine whether this is worth generating code for. 1626 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1627 unsigned NumElts = Op.getNumOperands(); 1628 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1629 if (!Op.getValueType().isInteger()) 1630 return None; 1631 1632 Optional<unsigned> SeqStepDenom; 1633 Optional<int64_t> SeqStepNum, SeqAddend; 1634 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1635 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1636 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1637 // Assume undef elements match the sequence; we just have to be careful 1638 // when interpolating across them. 1639 if (Op.getOperand(Idx).isUndef()) 1640 continue; 1641 // The BUILD_VECTOR must be all constants. 1642 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1643 return None; 1644 1645 uint64_t Val = Op.getConstantOperandVal(Idx) & 1646 maskTrailingOnes<uint64_t>(EltSizeInBits); 1647 1648 if (PrevElt) { 1649 // Calculate the step since the last non-undef element, and ensure 1650 // it's consistent across the entire sequence. 1651 unsigned IdxDiff = Idx - PrevElt->second; 1652 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1653 1654 // A zero-value value difference means that we're somewhere in the middle 1655 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1656 // step change before evaluating the sequence. 1657 if (ValDiff != 0) { 1658 int64_t Remainder = ValDiff % IdxDiff; 1659 // Normalize the step if it's greater than 1. 1660 if (Remainder != ValDiff) { 1661 // The difference must cleanly divide the element span. 1662 if (Remainder != 0) 1663 return None; 1664 ValDiff /= IdxDiff; 1665 IdxDiff = 1; 1666 } 1667 1668 if (!SeqStepNum) 1669 SeqStepNum = ValDiff; 1670 else if (ValDiff != SeqStepNum) 1671 return None; 1672 1673 if (!SeqStepDenom) 1674 SeqStepDenom = IdxDiff; 1675 else if (IdxDiff != *SeqStepDenom) 1676 return None; 1677 } 1678 } 1679 1680 // Record and/or check any addend. 1681 if (SeqStepNum && SeqStepDenom) { 1682 uint64_t ExpectedVal = 1683 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1684 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1685 if (!SeqAddend) 1686 SeqAddend = Addend; 1687 else if (SeqAddend != Addend) 1688 return None; 1689 } 1690 1691 // Record this non-undef element for later. 1692 if (!PrevElt || PrevElt->first != Val) 1693 PrevElt = std::make_pair(Val, Idx); 1694 } 1695 // We need to have logged both a step and an addend for this to count as 1696 // a legal index sequence. 1697 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1698 return None; 1699 1700 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1701 } 1702 1703 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1704 const RISCVSubtarget &Subtarget) { 1705 MVT VT = Op.getSimpleValueType(); 1706 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1707 1708 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1709 1710 SDLoc DL(Op); 1711 SDValue Mask, VL; 1712 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1713 1714 MVT XLenVT = Subtarget.getXLenVT(); 1715 unsigned NumElts = Op.getNumOperands(); 1716 1717 if (VT.getVectorElementType() == MVT::i1) { 1718 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1719 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1720 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1721 } 1722 1723 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1724 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1725 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1726 } 1727 1728 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1729 // scalar integer chunks whose bit-width depends on the number of mask 1730 // bits and XLEN. 1731 // First, determine the most appropriate scalar integer type to use. This 1732 // is at most XLenVT, but may be shrunk to a smaller vector element type 1733 // according to the size of the final vector - use i8 chunks rather than 1734 // XLenVT if we're producing a v8i1. This results in more consistent 1735 // codegen across RV32 and RV64. 1736 unsigned NumViaIntegerBits = 1737 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1738 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1739 // If we have to use more than one INSERT_VECTOR_ELT then this 1740 // optimization is likely to increase code size; avoid peforming it in 1741 // such a case. We can use a load from a constant pool in this case. 1742 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1743 return SDValue(); 1744 // Now we can create our integer vector type. Note that it may be larger 1745 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1746 MVT IntegerViaVecVT = 1747 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1748 divideCeil(NumElts, NumViaIntegerBits)); 1749 1750 uint64_t Bits = 0; 1751 unsigned BitPos = 0, IntegerEltIdx = 0; 1752 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1753 1754 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1755 // Once we accumulate enough bits to fill our scalar type, insert into 1756 // our vector and clear our accumulated data. 1757 if (I != 0 && I % NumViaIntegerBits == 0) { 1758 if (NumViaIntegerBits <= 32) 1759 Bits = SignExtend64(Bits, 32); 1760 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1761 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1762 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1763 Bits = 0; 1764 BitPos = 0; 1765 IntegerEltIdx++; 1766 } 1767 SDValue V = Op.getOperand(I); 1768 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1769 Bits |= ((uint64_t)BitValue << BitPos); 1770 } 1771 1772 // Insert the (remaining) scalar value into position in our integer 1773 // vector type. 1774 if (NumViaIntegerBits <= 32) 1775 Bits = SignExtend64(Bits, 32); 1776 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1777 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1778 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1779 1780 if (NumElts < NumViaIntegerBits) { 1781 // If we're producing a smaller vector than our minimum legal integer 1782 // type, bitcast to the equivalent (known-legal) mask type, and extract 1783 // our final mask. 1784 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1785 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1786 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1787 DAG.getConstant(0, DL, XLenVT)); 1788 } else { 1789 // Else we must have produced an integer type with the same size as the 1790 // mask type; bitcast for the final result. 1791 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1792 Vec = DAG.getBitcast(VT, Vec); 1793 } 1794 1795 return Vec; 1796 } 1797 1798 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1799 // vector type, we have a legal equivalently-sized i8 type, so we can use 1800 // that. 1801 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1802 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1803 1804 SDValue WideVec; 1805 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1806 // For a splat, perform a scalar truncate before creating the wider 1807 // vector. 1808 assert(Splat.getValueType() == XLenVT && 1809 "Unexpected type for i1 splat value"); 1810 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1811 DAG.getConstant(1, DL, XLenVT)); 1812 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1813 } else { 1814 SmallVector<SDValue, 8> Ops(Op->op_values()); 1815 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1816 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1817 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1818 } 1819 1820 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1821 } 1822 1823 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1824 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1825 : RISCVISD::VMV_V_X_VL; 1826 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1827 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1828 } 1829 1830 // Try and match index sequences, which we can lower to the vid instruction 1831 // with optional modifications. An all-undef vector is matched by 1832 // getSplatValue, above. 1833 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1834 int64_t StepNumerator = SimpleVID->StepNumerator; 1835 unsigned StepDenominator = SimpleVID->StepDenominator; 1836 int64_t Addend = SimpleVID->Addend; 1837 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 1838 // threshold since it's the immediate value many RVV instructions accept. 1839 if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) && 1840 isInt<5>(Addend)) { 1841 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1842 // Convert right out of the scalable type so we can use standard ISD 1843 // nodes for the rest of the computation. If we used scalable types with 1844 // these, we'd lose the fixed-length vector info and generate worse 1845 // vsetvli code. 1846 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 1847 assert(StepNumerator != 0 && "Invalid step"); 1848 bool Negate = false; 1849 if (StepNumerator != 1) { 1850 int64_t SplatStepVal = StepNumerator; 1851 unsigned Opcode = ISD::MUL; 1852 if (isPowerOf2_64(std::abs(StepNumerator))) { 1853 Negate = StepNumerator < 0; 1854 Opcode = ISD::SHL; 1855 SplatStepVal = Log2_64(std::abs(StepNumerator)); 1856 } 1857 SDValue SplatStep = DAG.getSplatVector( 1858 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 1859 VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep); 1860 } 1861 if (StepDenominator != 1) { 1862 SDValue SplatStep = DAG.getSplatVector( 1863 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 1864 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 1865 } 1866 if (Addend != 0 || Negate) { 1867 SDValue SplatAddend = 1868 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 1869 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 1870 } 1871 return VID; 1872 } 1873 } 1874 1875 // Attempt to detect "hidden" splats, which only reveal themselves as splats 1876 // when re-interpreted as a vector with a larger element type. For example, 1877 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 1878 // could be instead splat as 1879 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 1880 // TODO: This optimization could also work on non-constant splats, but it 1881 // would require bit-manipulation instructions to construct the splat value. 1882 SmallVector<SDValue> Sequence; 1883 unsigned EltBitSize = VT.getScalarSizeInBits(); 1884 const auto *BV = cast<BuildVectorSDNode>(Op); 1885 if (VT.isInteger() && EltBitSize < 64 && 1886 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1887 BV->getRepeatedSequence(Sequence) && 1888 (Sequence.size() * EltBitSize) <= 64) { 1889 unsigned SeqLen = Sequence.size(); 1890 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 1891 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 1892 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 1893 ViaIntVT == MVT::i64) && 1894 "Unexpected sequence type"); 1895 1896 unsigned EltIdx = 0; 1897 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 1898 uint64_t SplatValue = 0; 1899 // Construct the amalgamated value which can be splatted as this larger 1900 // vector type. 1901 for (const auto &SeqV : Sequence) { 1902 if (!SeqV.isUndef()) 1903 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 1904 << (EltIdx * EltBitSize)); 1905 EltIdx++; 1906 } 1907 1908 // On RV64, sign-extend from 32 to 64 bits where possible in order to 1909 // achieve better constant materializion. 1910 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 1911 SplatValue = SignExtend64(SplatValue, 32); 1912 1913 // Since we can't introduce illegal i64 types at this stage, we can only 1914 // perform an i64 splat on RV32 if it is its own sign-extended value. That 1915 // way we can use RVV instructions to splat. 1916 assert((ViaIntVT.bitsLE(XLenVT) || 1917 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 1918 "Unexpected bitcast sequence"); 1919 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 1920 SDValue ViaVL = 1921 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 1922 MVT ViaContainerVT = 1923 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 1924 SDValue Splat = 1925 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 1926 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 1927 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 1928 return DAG.getBitcast(VT, Splat); 1929 } 1930 } 1931 1932 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1933 // which constitute a large proportion of the elements. In such cases we can 1934 // splat a vector with the dominant element and make up the shortfall with 1935 // INSERT_VECTOR_ELTs. 1936 // Note that this includes vectors of 2 elements by association. The 1937 // upper-most element is the "dominant" one, allowing us to use a splat to 1938 // "insert" the upper element, and an insert of the lower element at position 1939 // 0, which improves codegen. 1940 SDValue DominantValue; 1941 unsigned MostCommonCount = 0; 1942 DenseMap<SDValue, unsigned> ValueCounts; 1943 unsigned NumUndefElts = 1944 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1945 1946 // Track the number of scalar loads we know we'd be inserting, estimated as 1947 // any non-zero floating-point constant. Other kinds of element are either 1948 // already in registers or are materialized on demand. The threshold at which 1949 // a vector load is more desirable than several scalar materializion and 1950 // vector-insertion instructions is not known. 1951 unsigned NumScalarLoads = 0; 1952 1953 for (SDValue V : Op->op_values()) { 1954 if (V.isUndef()) 1955 continue; 1956 1957 ValueCounts.insert(std::make_pair(V, 0)); 1958 unsigned &Count = ValueCounts[V]; 1959 1960 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 1961 NumScalarLoads += !CFP->isExactlyValue(+0.0); 1962 1963 // Is this value dominant? In case of a tie, prefer the highest element as 1964 // it's cheaper to insert near the beginning of a vector than it is at the 1965 // end. 1966 if (++Count >= MostCommonCount) { 1967 DominantValue = V; 1968 MostCommonCount = Count; 1969 } 1970 } 1971 1972 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 1973 unsigned NumDefElts = NumElts - NumUndefElts; 1974 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 1975 1976 // Don't perform this optimization when optimizing for size, since 1977 // materializing elements and inserting them tends to cause code bloat. 1978 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 1979 ((MostCommonCount > DominantValueCountThreshold) || 1980 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 1981 // Start by splatting the most common element. 1982 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 1983 1984 DenseSet<SDValue> Processed{DominantValue}; 1985 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 1986 for (const auto &OpIdx : enumerate(Op->ops())) { 1987 const SDValue &V = OpIdx.value(); 1988 if (V.isUndef() || !Processed.insert(V).second) 1989 continue; 1990 if (ValueCounts[V] == 1) { 1991 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 1992 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 1993 } else { 1994 // Blend in all instances of this value using a VSELECT, using a 1995 // mask where each bit signals whether that element is the one 1996 // we're after. 1997 SmallVector<SDValue> Ops; 1998 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 1999 return DAG.getConstant(V == V1, DL, XLenVT); 2000 }); 2001 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2002 DAG.getBuildVector(SelMaskTy, DL, Ops), 2003 DAG.getSplatBuildVector(VT, DL, V), Vec); 2004 } 2005 } 2006 2007 return Vec; 2008 } 2009 2010 return SDValue(); 2011 } 2012 2013 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2014 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2015 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2016 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2017 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2018 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2019 // node in order to try and match RVV vector/scalar instructions. 2020 if ((LoC >> 31) == HiC) 2021 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2022 } 2023 2024 // Fall back to a stack store and stride x0 vector load. 2025 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2026 } 2027 2028 // Called by type legalization to handle splat of i64 on RV32. 2029 // FIXME: We can optimize this when the type has sign or zero bits in one 2030 // of the halves. 2031 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2032 SDValue VL, SelectionDAG &DAG) { 2033 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2034 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2035 DAG.getConstant(0, DL, MVT::i32)); 2036 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2037 DAG.getConstant(1, DL, MVT::i32)); 2038 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2039 } 2040 2041 // This function lowers a splat of a scalar operand Splat with the vector 2042 // length VL. It ensures the final sequence is type legal, which is useful when 2043 // lowering a splat after type legalization. 2044 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2045 SelectionDAG &DAG, 2046 const RISCVSubtarget &Subtarget) { 2047 if (VT.isFloatingPoint()) 2048 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2049 2050 MVT XLenVT = Subtarget.getXLenVT(); 2051 2052 // Simplest case is that the operand needs to be promoted to XLenVT. 2053 if (Scalar.getValueType().bitsLE(XLenVT)) { 2054 // If the operand is a constant, sign extend to increase our chances 2055 // of being able to use a .vi instruction. ANY_EXTEND would become a 2056 // a zero extend and the simm5 check in isel would fail. 2057 // FIXME: Should we ignore the upper bits in isel instead? 2058 unsigned ExtOpc = 2059 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2060 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2061 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2062 } 2063 2064 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2065 "Unexpected scalar for splat lowering!"); 2066 2067 // Otherwise use the more complicated splatting algorithm. 2068 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2069 } 2070 2071 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2072 const RISCVSubtarget &Subtarget) { 2073 SDValue V1 = Op.getOperand(0); 2074 SDValue V2 = Op.getOperand(1); 2075 SDLoc DL(Op); 2076 MVT XLenVT = Subtarget.getXLenVT(); 2077 MVT VT = Op.getSimpleValueType(); 2078 unsigned NumElts = VT.getVectorNumElements(); 2079 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2080 2081 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2082 2083 SDValue TrueMask, VL; 2084 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2085 2086 if (SVN->isSplat()) { 2087 const int Lane = SVN->getSplatIndex(); 2088 if (Lane >= 0) { 2089 MVT SVT = VT.getVectorElementType(); 2090 2091 // Turn splatted vector load into a strided load with an X0 stride. 2092 SDValue V = V1; 2093 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2094 // with undef. 2095 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2096 int Offset = Lane; 2097 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2098 int OpElements = 2099 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2100 V = V.getOperand(Offset / OpElements); 2101 Offset %= OpElements; 2102 } 2103 2104 // We need to ensure the load isn't atomic or volatile. 2105 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2106 auto *Ld = cast<LoadSDNode>(V); 2107 Offset *= SVT.getStoreSize(); 2108 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2109 TypeSize::Fixed(Offset), DL); 2110 2111 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2112 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2113 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2114 SDValue IntID = 2115 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2116 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2117 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2118 SDValue NewLoad = DAG.getMemIntrinsicNode( 2119 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2120 DAG.getMachineFunction().getMachineMemOperand( 2121 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2122 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2123 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2124 } 2125 2126 // Otherwise use a scalar load and splat. This will give the best 2127 // opportunity to fold a splat into the operation. ISel can turn it into 2128 // the x0 strided load if we aren't able to fold away the select. 2129 if (SVT.isFloatingPoint()) 2130 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2131 Ld->getPointerInfo().getWithOffset(Offset), 2132 Ld->getOriginalAlign(), 2133 Ld->getMemOperand()->getFlags()); 2134 else 2135 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2136 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2137 Ld->getOriginalAlign(), 2138 Ld->getMemOperand()->getFlags()); 2139 DAG.makeEquivalentMemoryOrdering(Ld, V); 2140 2141 unsigned Opc = 2142 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2143 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2144 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2145 } 2146 2147 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2148 assert(Lane < (int)NumElts && "Unexpected lane!"); 2149 SDValue Gather = 2150 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2151 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2152 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2153 } 2154 } 2155 2156 // Detect shuffles which can be re-expressed as vector selects; these are 2157 // shuffles in which each element in the destination is taken from an element 2158 // at the corresponding index in either source vectors. 2159 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2160 int MaskIndex = MaskIdx.value(); 2161 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2162 }); 2163 2164 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2165 2166 SmallVector<SDValue> MaskVals; 2167 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2168 // merged with a second vrgather. 2169 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2170 2171 // By default we preserve the original operand order, and use a mask to 2172 // select LHS as true and RHS as false. However, since RVV vector selects may 2173 // feature splats but only on the LHS, we may choose to invert our mask and 2174 // instead select between RHS and LHS. 2175 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2176 bool InvertMask = IsSelect == SwapOps; 2177 2178 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2179 // half. 2180 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2181 2182 // Now construct the mask that will be used by the vselect or blended 2183 // vrgather operation. For vrgathers, construct the appropriate indices into 2184 // each vector. 2185 for (int MaskIndex : SVN->getMask()) { 2186 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2187 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2188 if (!IsSelect) { 2189 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2190 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2191 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2192 : DAG.getUNDEF(XLenVT)); 2193 GatherIndicesRHS.push_back( 2194 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2195 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2196 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2197 ++LHSIndexCounts[MaskIndex]; 2198 if (!IsLHSOrUndefIndex) 2199 ++RHSIndexCounts[MaskIndex - NumElts]; 2200 } 2201 } 2202 2203 if (SwapOps) { 2204 std::swap(V1, V2); 2205 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2206 } 2207 2208 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2209 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2210 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2211 2212 if (IsSelect) 2213 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2214 2215 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2216 // On such a large vector we're unable to use i8 as the index type. 2217 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2218 // may involve vector splitting if we're already at LMUL=8, or our 2219 // user-supplied maximum fixed-length LMUL. 2220 return SDValue(); 2221 } 2222 2223 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2224 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2225 MVT IndexVT = VT.changeTypeToInteger(); 2226 // Since we can't introduce illegal index types at this stage, use i16 and 2227 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2228 // than XLenVT. 2229 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2230 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2231 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2232 } 2233 2234 MVT IndexContainerVT = 2235 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2236 2237 SDValue Gather; 2238 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2239 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2240 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2241 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2242 } else { 2243 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2244 // If only one index is used, we can use a "splat" vrgather. 2245 // TODO: We can splat the most-common index and fix-up any stragglers, if 2246 // that's beneficial. 2247 if (LHSIndexCounts.size() == 1) { 2248 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2249 Gather = 2250 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2251 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2252 } else { 2253 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2254 LHSIndices = 2255 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2256 2257 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2258 TrueMask, VL); 2259 } 2260 } 2261 2262 // If a second vector operand is used by this shuffle, blend it in with an 2263 // additional vrgather. 2264 if (!V2.isUndef()) { 2265 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2266 // If only one index is used, we can use a "splat" vrgather. 2267 // TODO: We can splat the most-common index and fix-up any stragglers, if 2268 // that's beneficial. 2269 if (RHSIndexCounts.size() == 1) { 2270 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2271 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2272 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2273 } else { 2274 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2275 RHSIndices = 2276 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2277 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2278 VL); 2279 } 2280 2281 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2282 SelectMask = 2283 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2284 2285 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2286 Gather, VL); 2287 } 2288 2289 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2290 } 2291 2292 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2293 SDLoc DL, SelectionDAG &DAG, 2294 const RISCVSubtarget &Subtarget) { 2295 if (VT.isScalableVector()) 2296 return DAG.getFPExtendOrRound(Op, DL, VT); 2297 assert(VT.isFixedLengthVector() && 2298 "Unexpected value type for RVV FP extend/round lowering"); 2299 SDValue Mask, VL; 2300 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2301 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2302 ? RISCVISD::FP_EXTEND_VL 2303 : RISCVISD::FP_ROUND_VL; 2304 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2305 } 2306 2307 // While RVV has alignment restrictions, we should always be able to load as a 2308 // legal equivalently-sized byte-typed vector instead. This method is 2309 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2310 // the load is already correctly-aligned, it returns SDValue(). 2311 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2312 SelectionDAG &DAG) const { 2313 auto *Load = cast<LoadSDNode>(Op); 2314 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2315 2316 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2317 Load->getMemoryVT(), 2318 *Load->getMemOperand())) 2319 return SDValue(); 2320 2321 SDLoc DL(Op); 2322 MVT VT = Op.getSimpleValueType(); 2323 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2324 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2325 "Unexpected unaligned RVV load type"); 2326 MVT NewVT = 2327 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2328 assert(NewVT.isValid() && 2329 "Expecting equally-sized RVV vector types to be legal"); 2330 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2331 Load->getPointerInfo(), Load->getOriginalAlign(), 2332 Load->getMemOperand()->getFlags()); 2333 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2334 } 2335 2336 // While RVV has alignment restrictions, we should always be able to store as a 2337 // legal equivalently-sized byte-typed vector instead. This method is 2338 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2339 // returns SDValue() if the store is already correctly aligned. 2340 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2341 SelectionDAG &DAG) const { 2342 auto *Store = cast<StoreSDNode>(Op); 2343 assert(Store && Store->getValue().getValueType().isVector() && 2344 "Expected vector store"); 2345 2346 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2347 Store->getMemoryVT(), 2348 *Store->getMemOperand())) 2349 return SDValue(); 2350 2351 SDLoc DL(Op); 2352 SDValue StoredVal = Store->getValue(); 2353 MVT VT = StoredVal.getSimpleValueType(); 2354 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2355 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2356 "Unexpected unaligned RVV store type"); 2357 MVT NewVT = 2358 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2359 assert(NewVT.isValid() && 2360 "Expecting equally-sized RVV vector types to be legal"); 2361 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2362 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2363 Store->getPointerInfo(), Store->getOriginalAlign(), 2364 Store->getMemOperand()->getFlags()); 2365 } 2366 2367 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2368 SelectionDAG &DAG) const { 2369 switch (Op.getOpcode()) { 2370 default: 2371 report_fatal_error("unimplemented operand"); 2372 case ISD::GlobalAddress: 2373 return lowerGlobalAddress(Op, DAG); 2374 case ISD::BlockAddress: 2375 return lowerBlockAddress(Op, DAG); 2376 case ISD::ConstantPool: 2377 return lowerConstantPool(Op, DAG); 2378 case ISD::JumpTable: 2379 return lowerJumpTable(Op, DAG); 2380 case ISD::GlobalTLSAddress: 2381 return lowerGlobalTLSAddress(Op, DAG); 2382 case ISD::SELECT: 2383 return lowerSELECT(Op, DAG); 2384 case ISD::BRCOND: 2385 return lowerBRCOND(Op, DAG); 2386 case ISD::VASTART: 2387 return lowerVASTART(Op, DAG); 2388 case ISD::FRAMEADDR: 2389 return lowerFRAMEADDR(Op, DAG); 2390 case ISD::RETURNADDR: 2391 return lowerRETURNADDR(Op, DAG); 2392 case ISD::SHL_PARTS: 2393 return lowerShiftLeftParts(Op, DAG); 2394 case ISD::SRA_PARTS: 2395 return lowerShiftRightParts(Op, DAG, true); 2396 case ISD::SRL_PARTS: 2397 return lowerShiftRightParts(Op, DAG, false); 2398 case ISD::BITCAST: { 2399 SDLoc DL(Op); 2400 EVT VT = Op.getValueType(); 2401 SDValue Op0 = Op.getOperand(0); 2402 EVT Op0VT = Op0.getValueType(); 2403 MVT XLenVT = Subtarget.getXLenVT(); 2404 if (VT.isFixedLengthVector()) { 2405 // We can handle fixed length vector bitcasts with a simple replacement 2406 // in isel. 2407 if (Op0VT.isFixedLengthVector()) 2408 return Op; 2409 // When bitcasting from scalar to fixed-length vector, insert the scalar 2410 // into a one-element vector of the result type, and perform a vector 2411 // bitcast. 2412 if (!Op0VT.isVector()) { 2413 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2414 if (!isTypeLegal(BVT)) 2415 return SDValue(); 2416 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2417 DAG.getUNDEF(BVT), Op0, 2418 DAG.getConstant(0, DL, XLenVT))); 2419 } 2420 return SDValue(); 2421 } 2422 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2423 // thus: bitcast the vector to a one-element vector type whose element type 2424 // is the same as the result type, and extract the first element. 2425 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2426 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2427 if (!isTypeLegal(BVT)) 2428 return SDValue(); 2429 SDValue BVec = DAG.getBitcast(BVT, Op0); 2430 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2431 DAG.getConstant(0, DL, XLenVT)); 2432 } 2433 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2434 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2435 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2436 return FPConv; 2437 } 2438 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2439 Subtarget.hasStdExtF()) { 2440 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2441 SDValue FPConv = 2442 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2443 return FPConv; 2444 } 2445 return SDValue(); 2446 } 2447 case ISD::INTRINSIC_WO_CHAIN: 2448 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2449 case ISD::INTRINSIC_W_CHAIN: 2450 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2451 case ISD::INTRINSIC_VOID: 2452 return LowerINTRINSIC_VOID(Op, DAG); 2453 case ISD::BSWAP: 2454 case ISD::BITREVERSE: { 2455 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2456 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2457 MVT VT = Op.getSimpleValueType(); 2458 SDLoc DL(Op); 2459 // Start with the maximum immediate value which is the bitwidth - 1. 2460 unsigned Imm = VT.getSizeInBits() - 1; 2461 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2462 if (Op.getOpcode() == ISD::BSWAP) 2463 Imm &= ~0x7U; 2464 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2465 DAG.getConstant(Imm, DL, VT)); 2466 } 2467 case ISD::FSHL: 2468 case ISD::FSHR: { 2469 MVT VT = Op.getSimpleValueType(); 2470 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2471 SDLoc DL(Op); 2472 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2473 return Op; 2474 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2475 // use log(XLen) bits. Mask the shift amount accordingly. 2476 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2477 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2478 DAG.getConstant(ShAmtWidth, DL, VT)); 2479 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2480 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2481 } 2482 case ISD::TRUNCATE: { 2483 SDLoc DL(Op); 2484 MVT VT = Op.getSimpleValueType(); 2485 // Only custom-lower vector truncates 2486 if (!VT.isVector()) 2487 return Op; 2488 2489 // Truncates to mask types are handled differently 2490 if (VT.getVectorElementType() == MVT::i1) 2491 return lowerVectorMaskTrunc(Op, DAG); 2492 2493 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2494 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2495 // truncate by one power of two at a time. 2496 MVT DstEltVT = VT.getVectorElementType(); 2497 2498 SDValue Src = Op.getOperand(0); 2499 MVT SrcVT = Src.getSimpleValueType(); 2500 MVT SrcEltVT = SrcVT.getVectorElementType(); 2501 2502 assert(DstEltVT.bitsLT(SrcEltVT) && 2503 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2504 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2505 "Unexpected vector truncate lowering"); 2506 2507 MVT ContainerVT = SrcVT; 2508 if (SrcVT.isFixedLengthVector()) { 2509 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2510 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2511 } 2512 2513 SDValue Result = Src; 2514 SDValue Mask, VL; 2515 std::tie(Mask, VL) = 2516 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2517 LLVMContext &Context = *DAG.getContext(); 2518 const ElementCount Count = ContainerVT.getVectorElementCount(); 2519 do { 2520 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2521 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2522 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2523 Mask, VL); 2524 } while (SrcEltVT != DstEltVT); 2525 2526 if (SrcVT.isFixedLengthVector()) 2527 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2528 2529 return Result; 2530 } 2531 case ISD::ANY_EXTEND: 2532 case ISD::ZERO_EXTEND: 2533 if (Op.getOperand(0).getValueType().isVector() && 2534 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2535 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2536 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2537 case ISD::SIGN_EXTEND: 2538 if (Op.getOperand(0).getValueType().isVector() && 2539 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2540 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2541 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2542 case ISD::SPLAT_VECTOR_PARTS: 2543 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2544 case ISD::INSERT_VECTOR_ELT: 2545 return lowerINSERT_VECTOR_ELT(Op, DAG); 2546 case ISD::EXTRACT_VECTOR_ELT: 2547 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2548 case ISD::VSCALE: { 2549 MVT VT = Op.getSimpleValueType(); 2550 SDLoc DL(Op); 2551 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2552 // We define our scalable vector types for lmul=1 to use a 64 bit known 2553 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2554 // vscale as VLENB / 8. 2555 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2556 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2557 // We assume VLENB is a multiple of 8. We manually choose the best shift 2558 // here because SimplifyDemandedBits isn't always able to simplify it. 2559 uint64_t Val = Op.getConstantOperandVal(0); 2560 if (isPowerOf2_64(Val)) { 2561 uint64_t Log2 = Log2_64(Val); 2562 if (Log2 < 3) 2563 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2564 DAG.getConstant(3 - Log2, DL, VT)); 2565 if (Log2 > 3) 2566 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2567 DAG.getConstant(Log2 - 3, DL, VT)); 2568 return VLENB; 2569 } 2570 // If the multiplier is a multiple of 8, scale it down to avoid needing 2571 // to shift the VLENB value. 2572 if ((Val % 8) == 0) 2573 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2574 DAG.getConstant(Val / 8, DL, VT)); 2575 } 2576 2577 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2578 DAG.getConstant(3, DL, VT)); 2579 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2580 } 2581 case ISD::FP_EXTEND: { 2582 // RVV can only do fp_extend to types double the size as the source. We 2583 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2584 // via f32. 2585 SDLoc DL(Op); 2586 MVT VT = Op.getSimpleValueType(); 2587 SDValue Src = Op.getOperand(0); 2588 MVT SrcVT = Src.getSimpleValueType(); 2589 2590 // Prepare any fixed-length vector operands. 2591 MVT ContainerVT = VT; 2592 if (SrcVT.isFixedLengthVector()) { 2593 ContainerVT = getContainerForFixedLengthVector(VT); 2594 MVT SrcContainerVT = 2595 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2596 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2597 } 2598 2599 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2600 SrcVT.getVectorElementType() != MVT::f16) { 2601 // For scalable vectors, we only need to close the gap between 2602 // vXf16->vXf64. 2603 if (!VT.isFixedLengthVector()) 2604 return Op; 2605 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2606 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2607 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2608 } 2609 2610 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2611 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2612 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2613 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2614 2615 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2616 DL, DAG, Subtarget); 2617 if (VT.isFixedLengthVector()) 2618 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2619 return Extend; 2620 } 2621 case ISD::FP_ROUND: { 2622 // RVV can only do fp_round to types half the size as the source. We 2623 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2624 // conversion instruction. 2625 SDLoc DL(Op); 2626 MVT VT = Op.getSimpleValueType(); 2627 SDValue Src = Op.getOperand(0); 2628 MVT SrcVT = Src.getSimpleValueType(); 2629 2630 // Prepare any fixed-length vector operands. 2631 MVT ContainerVT = VT; 2632 if (VT.isFixedLengthVector()) { 2633 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2634 ContainerVT = 2635 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2636 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2637 } 2638 2639 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2640 SrcVT.getVectorElementType() != MVT::f64) { 2641 // For scalable vectors, we only need to close the gap between 2642 // vXf64<->vXf16. 2643 if (!VT.isFixedLengthVector()) 2644 return Op; 2645 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2646 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2647 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2648 } 2649 2650 SDValue Mask, VL; 2651 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2652 2653 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2654 SDValue IntermediateRound = 2655 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2656 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2657 DL, DAG, Subtarget); 2658 2659 if (VT.isFixedLengthVector()) 2660 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2661 return Round; 2662 } 2663 case ISD::FP_TO_SINT: 2664 case ISD::FP_TO_UINT: 2665 case ISD::SINT_TO_FP: 2666 case ISD::UINT_TO_FP: { 2667 // RVV can only do fp<->int conversions to types half/double the size as 2668 // the source. We custom-lower any conversions that do two hops into 2669 // sequences. 2670 MVT VT = Op.getSimpleValueType(); 2671 if (!VT.isVector()) 2672 return Op; 2673 SDLoc DL(Op); 2674 SDValue Src = Op.getOperand(0); 2675 MVT EltVT = VT.getVectorElementType(); 2676 MVT SrcVT = Src.getSimpleValueType(); 2677 MVT SrcEltVT = SrcVT.getVectorElementType(); 2678 unsigned EltSize = EltVT.getSizeInBits(); 2679 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2680 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2681 "Unexpected vector element types"); 2682 2683 bool IsInt2FP = SrcEltVT.isInteger(); 2684 // Widening conversions 2685 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2686 if (IsInt2FP) { 2687 // Do a regular integer sign/zero extension then convert to float. 2688 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2689 VT.getVectorElementCount()); 2690 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2691 ? ISD::ZERO_EXTEND 2692 : ISD::SIGN_EXTEND; 2693 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2694 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2695 } 2696 // FP2Int 2697 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2698 // Do one doubling fp_extend then complete the operation by converting 2699 // to int. 2700 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2701 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2702 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2703 } 2704 2705 // Narrowing conversions 2706 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2707 if (IsInt2FP) { 2708 // One narrowing int_to_fp, then an fp_round. 2709 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2710 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2711 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2712 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2713 } 2714 // FP2Int 2715 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2716 // representable by the integer, the result is poison. 2717 MVT IVecVT = 2718 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2719 VT.getVectorElementCount()); 2720 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2721 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2722 } 2723 2724 // Scalable vectors can exit here. Patterns will handle equally-sized 2725 // conversions halving/doubling ones. 2726 if (!VT.isFixedLengthVector()) 2727 return Op; 2728 2729 // For fixed-length vectors we lower to a custom "VL" node. 2730 unsigned RVVOpc = 0; 2731 switch (Op.getOpcode()) { 2732 default: 2733 llvm_unreachable("Impossible opcode"); 2734 case ISD::FP_TO_SINT: 2735 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2736 break; 2737 case ISD::FP_TO_UINT: 2738 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2739 break; 2740 case ISD::SINT_TO_FP: 2741 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2742 break; 2743 case ISD::UINT_TO_FP: 2744 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2745 break; 2746 } 2747 2748 MVT ContainerVT, SrcContainerVT; 2749 // Derive the reference container type from the larger vector type. 2750 if (SrcEltSize > EltSize) { 2751 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2752 ContainerVT = 2753 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2754 } else { 2755 ContainerVT = getContainerForFixedLengthVector(VT); 2756 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2757 } 2758 2759 SDValue Mask, VL; 2760 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2761 2762 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2763 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 2764 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2765 } 2766 case ISD::FP_TO_SINT_SAT: 2767 case ISD::FP_TO_UINT_SAT: 2768 return lowerFP_TO_INT_SAT(Op, DAG); 2769 case ISD::VECREDUCE_ADD: 2770 case ISD::VECREDUCE_UMAX: 2771 case ISD::VECREDUCE_SMAX: 2772 case ISD::VECREDUCE_UMIN: 2773 case ISD::VECREDUCE_SMIN: 2774 return lowerVECREDUCE(Op, DAG); 2775 case ISD::VECREDUCE_AND: 2776 case ISD::VECREDUCE_OR: 2777 case ISD::VECREDUCE_XOR: 2778 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2779 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 2780 return lowerVECREDUCE(Op, DAG); 2781 case ISD::VECREDUCE_FADD: 2782 case ISD::VECREDUCE_SEQ_FADD: 2783 case ISD::VECREDUCE_FMIN: 2784 case ISD::VECREDUCE_FMAX: 2785 return lowerFPVECREDUCE(Op, DAG); 2786 case ISD::VP_REDUCE_ADD: 2787 case ISD::VP_REDUCE_UMAX: 2788 case ISD::VP_REDUCE_SMAX: 2789 case ISD::VP_REDUCE_UMIN: 2790 case ISD::VP_REDUCE_SMIN: 2791 case ISD::VP_REDUCE_FADD: 2792 case ISD::VP_REDUCE_SEQ_FADD: 2793 case ISD::VP_REDUCE_FMIN: 2794 case ISD::VP_REDUCE_FMAX: 2795 return lowerVPREDUCE(Op, DAG); 2796 case ISD::VP_REDUCE_AND: 2797 case ISD::VP_REDUCE_OR: 2798 case ISD::VP_REDUCE_XOR: 2799 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 2800 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 2801 return lowerVPREDUCE(Op, DAG); 2802 case ISD::INSERT_SUBVECTOR: 2803 return lowerINSERT_SUBVECTOR(Op, DAG); 2804 case ISD::EXTRACT_SUBVECTOR: 2805 return lowerEXTRACT_SUBVECTOR(Op, DAG); 2806 case ISD::STEP_VECTOR: 2807 return lowerSTEP_VECTOR(Op, DAG); 2808 case ISD::VECTOR_REVERSE: 2809 return lowerVECTOR_REVERSE(Op, DAG); 2810 case ISD::BUILD_VECTOR: 2811 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 2812 case ISD::SPLAT_VECTOR: 2813 if (Op.getValueType().getVectorElementType() == MVT::i1) 2814 return lowerVectorMaskSplat(Op, DAG); 2815 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 2816 case ISD::VECTOR_SHUFFLE: 2817 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 2818 case ISD::CONCAT_VECTORS: { 2819 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 2820 // better than going through the stack, as the default expansion does. 2821 SDLoc DL(Op); 2822 MVT VT = Op.getSimpleValueType(); 2823 unsigned NumOpElts = 2824 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 2825 SDValue Vec = DAG.getUNDEF(VT); 2826 for (const auto &OpIdx : enumerate(Op->ops())) 2827 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 2828 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 2829 return Vec; 2830 } 2831 case ISD::LOAD: 2832 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 2833 return V; 2834 if (Op.getValueType().isFixedLengthVector()) 2835 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 2836 return Op; 2837 case ISD::STORE: 2838 if (auto V = expandUnalignedRVVStore(Op, DAG)) 2839 return V; 2840 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 2841 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 2842 return Op; 2843 case ISD::MLOAD: 2844 case ISD::VP_LOAD: 2845 return lowerMaskedLoad(Op, DAG); 2846 case ISD::MSTORE: 2847 case ISD::VP_STORE: 2848 return lowerMaskedStore(Op, DAG); 2849 case ISD::SETCC: 2850 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 2851 case ISD::ADD: 2852 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 2853 case ISD::SUB: 2854 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 2855 case ISD::MUL: 2856 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 2857 case ISD::MULHS: 2858 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 2859 case ISD::MULHU: 2860 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 2861 case ISD::AND: 2862 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 2863 RISCVISD::AND_VL); 2864 case ISD::OR: 2865 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 2866 RISCVISD::OR_VL); 2867 case ISD::XOR: 2868 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 2869 RISCVISD::XOR_VL); 2870 case ISD::SDIV: 2871 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 2872 case ISD::SREM: 2873 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 2874 case ISD::UDIV: 2875 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 2876 case ISD::UREM: 2877 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 2878 case ISD::SHL: 2879 case ISD::SRA: 2880 case ISD::SRL: 2881 if (Op.getSimpleValueType().isFixedLengthVector()) 2882 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 2883 // This can be called for an i32 shift amount that needs to be promoted. 2884 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 2885 "Unexpected custom legalisation"); 2886 return SDValue(); 2887 case ISD::SADDSAT: 2888 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 2889 case ISD::UADDSAT: 2890 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 2891 case ISD::SSUBSAT: 2892 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 2893 case ISD::USUBSAT: 2894 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 2895 case ISD::FADD: 2896 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 2897 case ISD::FSUB: 2898 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 2899 case ISD::FMUL: 2900 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 2901 case ISD::FDIV: 2902 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 2903 case ISD::FNEG: 2904 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 2905 case ISD::FABS: 2906 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 2907 case ISD::FSQRT: 2908 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 2909 case ISD::FMA: 2910 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 2911 case ISD::SMIN: 2912 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 2913 case ISD::SMAX: 2914 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 2915 case ISD::UMIN: 2916 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 2917 case ISD::UMAX: 2918 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 2919 case ISD::FMINNUM: 2920 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 2921 case ISD::FMAXNUM: 2922 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 2923 case ISD::ABS: 2924 return lowerABS(Op, DAG); 2925 case ISD::VSELECT: 2926 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 2927 case ISD::FCOPYSIGN: 2928 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 2929 case ISD::MGATHER: 2930 case ISD::VP_GATHER: 2931 return lowerMaskedGather(Op, DAG); 2932 case ISD::MSCATTER: 2933 case ISD::VP_SCATTER: 2934 return lowerMaskedScatter(Op, DAG); 2935 case ISD::FLT_ROUNDS_: 2936 return lowerGET_ROUNDING(Op, DAG); 2937 case ISD::SET_ROUNDING: 2938 return lowerSET_ROUNDING(Op, DAG); 2939 case ISD::VP_ADD: 2940 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 2941 case ISD::VP_SUB: 2942 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 2943 case ISD::VP_MUL: 2944 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 2945 case ISD::VP_SDIV: 2946 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 2947 case ISD::VP_UDIV: 2948 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 2949 case ISD::VP_SREM: 2950 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 2951 case ISD::VP_UREM: 2952 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 2953 case ISD::VP_AND: 2954 return lowerVPOp(Op, DAG, RISCVISD::AND_VL); 2955 case ISD::VP_OR: 2956 return lowerVPOp(Op, DAG, RISCVISD::OR_VL); 2957 case ISD::VP_XOR: 2958 return lowerVPOp(Op, DAG, RISCVISD::XOR_VL); 2959 case ISD::VP_ASHR: 2960 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 2961 case ISD::VP_LSHR: 2962 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 2963 case ISD::VP_SHL: 2964 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 2965 case ISD::VP_FADD: 2966 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 2967 case ISD::VP_FSUB: 2968 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 2969 case ISD::VP_FMUL: 2970 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 2971 case ISD::VP_FDIV: 2972 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 2973 } 2974 } 2975 2976 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 2977 SelectionDAG &DAG, unsigned Flags) { 2978 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 2979 } 2980 2981 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 2982 SelectionDAG &DAG, unsigned Flags) { 2983 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 2984 Flags); 2985 } 2986 2987 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 2988 SelectionDAG &DAG, unsigned Flags) { 2989 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 2990 N->getOffset(), Flags); 2991 } 2992 2993 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 2994 SelectionDAG &DAG, unsigned Flags) { 2995 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 2996 } 2997 2998 template <class NodeTy> 2999 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3000 bool IsLocal) const { 3001 SDLoc DL(N); 3002 EVT Ty = getPointerTy(DAG.getDataLayout()); 3003 3004 if (isPositionIndependent()) { 3005 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3006 if (IsLocal) 3007 // Use PC-relative addressing to access the symbol. This generates the 3008 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3009 // %pcrel_lo(auipc)). 3010 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3011 3012 // Use PC-relative addressing to access the GOT for this symbol, then load 3013 // the address from the GOT. This generates the pattern (PseudoLA sym), 3014 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3015 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3016 } 3017 3018 switch (getTargetMachine().getCodeModel()) { 3019 default: 3020 report_fatal_error("Unsupported code model for lowering"); 3021 case CodeModel::Small: { 3022 // Generate a sequence for accessing addresses within the first 2 GiB of 3023 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3024 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3025 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3026 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3027 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3028 } 3029 case CodeModel::Medium: { 3030 // Generate a sequence for accessing addresses within any 2GiB range within 3031 // the address space. This generates the pattern (PseudoLLA sym), which 3032 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3033 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3034 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3035 } 3036 } 3037 } 3038 3039 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3040 SelectionDAG &DAG) const { 3041 SDLoc DL(Op); 3042 EVT Ty = Op.getValueType(); 3043 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3044 int64_t Offset = N->getOffset(); 3045 MVT XLenVT = Subtarget.getXLenVT(); 3046 3047 const GlobalValue *GV = N->getGlobal(); 3048 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3049 SDValue Addr = getAddr(N, DAG, IsLocal); 3050 3051 // In order to maximise the opportunity for common subexpression elimination, 3052 // emit a separate ADD node for the global address offset instead of folding 3053 // it in the global address node. Later peephole optimisations may choose to 3054 // fold it back in when profitable. 3055 if (Offset != 0) 3056 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3057 DAG.getConstant(Offset, DL, XLenVT)); 3058 return Addr; 3059 } 3060 3061 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3062 SelectionDAG &DAG) const { 3063 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3064 3065 return getAddr(N, DAG); 3066 } 3067 3068 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3069 SelectionDAG &DAG) const { 3070 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3071 3072 return getAddr(N, DAG); 3073 } 3074 3075 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3076 SelectionDAG &DAG) const { 3077 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3078 3079 return getAddr(N, DAG); 3080 } 3081 3082 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3083 SelectionDAG &DAG, 3084 bool UseGOT) const { 3085 SDLoc DL(N); 3086 EVT Ty = getPointerTy(DAG.getDataLayout()); 3087 const GlobalValue *GV = N->getGlobal(); 3088 MVT XLenVT = Subtarget.getXLenVT(); 3089 3090 if (UseGOT) { 3091 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3092 // load the address from the GOT and add the thread pointer. This generates 3093 // the pattern (PseudoLA_TLS_IE sym), which expands to 3094 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3095 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3096 SDValue Load = 3097 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3098 3099 // Add the thread pointer. 3100 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3101 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3102 } 3103 3104 // Generate a sequence for accessing the address relative to the thread 3105 // pointer, with the appropriate adjustment for the thread pointer offset. 3106 // This generates the pattern 3107 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3108 SDValue AddrHi = 3109 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3110 SDValue AddrAdd = 3111 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3112 SDValue AddrLo = 3113 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3114 3115 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3116 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3117 SDValue MNAdd = SDValue( 3118 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3119 0); 3120 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3121 } 3122 3123 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3124 SelectionDAG &DAG) const { 3125 SDLoc DL(N); 3126 EVT Ty = getPointerTy(DAG.getDataLayout()); 3127 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3128 const GlobalValue *GV = N->getGlobal(); 3129 3130 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3131 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3132 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3133 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3134 SDValue Load = 3135 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3136 3137 // Prepare argument list to generate call. 3138 ArgListTy Args; 3139 ArgListEntry Entry; 3140 Entry.Node = Load; 3141 Entry.Ty = CallTy; 3142 Args.push_back(Entry); 3143 3144 // Setup call to __tls_get_addr. 3145 TargetLowering::CallLoweringInfo CLI(DAG); 3146 CLI.setDebugLoc(DL) 3147 .setChain(DAG.getEntryNode()) 3148 .setLibCallee(CallingConv::C, CallTy, 3149 DAG.getExternalSymbol("__tls_get_addr", Ty), 3150 std::move(Args)); 3151 3152 return LowerCallTo(CLI).first; 3153 } 3154 3155 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3156 SelectionDAG &DAG) const { 3157 SDLoc DL(Op); 3158 EVT Ty = Op.getValueType(); 3159 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3160 int64_t Offset = N->getOffset(); 3161 MVT XLenVT = Subtarget.getXLenVT(); 3162 3163 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3164 3165 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3166 CallingConv::GHC) 3167 report_fatal_error("In GHC calling convention TLS is not supported"); 3168 3169 SDValue Addr; 3170 switch (Model) { 3171 case TLSModel::LocalExec: 3172 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3173 break; 3174 case TLSModel::InitialExec: 3175 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3176 break; 3177 case TLSModel::LocalDynamic: 3178 case TLSModel::GeneralDynamic: 3179 Addr = getDynamicTLSAddr(N, DAG); 3180 break; 3181 } 3182 3183 // In order to maximise the opportunity for common subexpression elimination, 3184 // emit a separate ADD node for the global address offset instead of folding 3185 // it in the global address node. Later peephole optimisations may choose to 3186 // fold it back in when profitable. 3187 if (Offset != 0) 3188 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3189 DAG.getConstant(Offset, DL, XLenVT)); 3190 return Addr; 3191 } 3192 3193 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3194 SDValue CondV = Op.getOperand(0); 3195 SDValue TrueV = Op.getOperand(1); 3196 SDValue FalseV = Op.getOperand(2); 3197 SDLoc DL(Op); 3198 MVT VT = Op.getSimpleValueType(); 3199 MVT XLenVT = Subtarget.getXLenVT(); 3200 3201 // Lower vector SELECTs to VSELECTs by splatting the condition. 3202 if (VT.isVector()) { 3203 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3204 SDValue CondSplat = VT.isScalableVector() 3205 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3206 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3207 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3208 } 3209 3210 // If the result type is XLenVT and CondV is the output of a SETCC node 3211 // which also operated on XLenVT inputs, then merge the SETCC node into the 3212 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3213 // compare+branch instructions. i.e.: 3214 // (select (setcc lhs, rhs, cc), truev, falsev) 3215 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3216 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3217 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3218 SDValue LHS = CondV.getOperand(0); 3219 SDValue RHS = CondV.getOperand(1); 3220 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3221 ISD::CondCode CCVal = CC->get(); 3222 3223 // Special case for a select of 2 constants that have a diffence of 1. 3224 // Normally this is done by DAGCombine, but if the select is introduced by 3225 // type legalization or op legalization, we miss it. Restricting to SETLT 3226 // case for now because that is what signed saturating add/sub need. 3227 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3228 // but we would probably want to swap the true/false values if the condition 3229 // is SETGE/SETLE to avoid an XORI. 3230 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3231 CCVal == ISD::SETLT) { 3232 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3233 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3234 if (TrueVal - 1 == FalseVal) 3235 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3236 if (TrueVal + 1 == FalseVal) 3237 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3238 } 3239 3240 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3241 3242 SDValue TargetCC = DAG.getCondCode(CCVal); 3243 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3244 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3245 } 3246 3247 // Otherwise: 3248 // (select condv, truev, falsev) 3249 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3250 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3251 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3252 3253 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3254 3255 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3256 } 3257 3258 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3259 SDValue CondV = Op.getOperand(1); 3260 SDLoc DL(Op); 3261 MVT XLenVT = Subtarget.getXLenVT(); 3262 3263 if (CondV.getOpcode() == ISD::SETCC && 3264 CondV.getOperand(0).getValueType() == XLenVT) { 3265 SDValue LHS = CondV.getOperand(0); 3266 SDValue RHS = CondV.getOperand(1); 3267 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3268 3269 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3270 3271 SDValue TargetCC = DAG.getCondCode(CCVal); 3272 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3273 LHS, RHS, TargetCC, Op.getOperand(2)); 3274 } 3275 3276 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3277 CondV, DAG.getConstant(0, DL, XLenVT), 3278 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3279 } 3280 3281 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3282 MachineFunction &MF = DAG.getMachineFunction(); 3283 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3284 3285 SDLoc DL(Op); 3286 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3287 getPointerTy(MF.getDataLayout())); 3288 3289 // vastart just stores the address of the VarArgsFrameIndex slot into the 3290 // memory location argument. 3291 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3292 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3293 MachinePointerInfo(SV)); 3294 } 3295 3296 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3297 SelectionDAG &DAG) const { 3298 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3299 MachineFunction &MF = DAG.getMachineFunction(); 3300 MachineFrameInfo &MFI = MF.getFrameInfo(); 3301 MFI.setFrameAddressIsTaken(true); 3302 Register FrameReg = RI.getFrameRegister(MF); 3303 int XLenInBytes = Subtarget.getXLen() / 8; 3304 3305 EVT VT = Op.getValueType(); 3306 SDLoc DL(Op); 3307 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3308 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3309 while (Depth--) { 3310 int Offset = -(XLenInBytes * 2); 3311 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3312 DAG.getIntPtrConstant(Offset, DL)); 3313 FrameAddr = 3314 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3315 } 3316 return FrameAddr; 3317 } 3318 3319 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3320 SelectionDAG &DAG) const { 3321 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3322 MachineFunction &MF = DAG.getMachineFunction(); 3323 MachineFrameInfo &MFI = MF.getFrameInfo(); 3324 MFI.setReturnAddressIsTaken(true); 3325 MVT XLenVT = Subtarget.getXLenVT(); 3326 int XLenInBytes = Subtarget.getXLen() / 8; 3327 3328 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3329 return SDValue(); 3330 3331 EVT VT = Op.getValueType(); 3332 SDLoc DL(Op); 3333 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3334 if (Depth) { 3335 int Off = -XLenInBytes; 3336 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3337 SDValue Offset = DAG.getConstant(Off, DL, VT); 3338 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3339 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3340 MachinePointerInfo()); 3341 } 3342 3343 // Return the value of the return address register, marking it an implicit 3344 // live-in. 3345 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3346 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3347 } 3348 3349 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3350 SelectionDAG &DAG) const { 3351 SDLoc DL(Op); 3352 SDValue Lo = Op.getOperand(0); 3353 SDValue Hi = Op.getOperand(1); 3354 SDValue Shamt = Op.getOperand(2); 3355 EVT VT = Lo.getValueType(); 3356 3357 // if Shamt-XLEN < 0: // Shamt < XLEN 3358 // Lo = Lo << Shamt 3359 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3360 // else: 3361 // Lo = 0 3362 // Hi = Lo << (Shamt-XLEN) 3363 3364 SDValue Zero = DAG.getConstant(0, DL, VT); 3365 SDValue One = DAG.getConstant(1, DL, VT); 3366 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3367 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3368 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3369 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3370 3371 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3372 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3373 SDValue ShiftRightLo = 3374 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3375 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3376 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3377 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3378 3379 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3380 3381 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3382 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3383 3384 SDValue Parts[2] = {Lo, Hi}; 3385 return DAG.getMergeValues(Parts, DL); 3386 } 3387 3388 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3389 bool IsSRA) const { 3390 SDLoc DL(Op); 3391 SDValue Lo = Op.getOperand(0); 3392 SDValue Hi = Op.getOperand(1); 3393 SDValue Shamt = Op.getOperand(2); 3394 EVT VT = Lo.getValueType(); 3395 3396 // SRA expansion: 3397 // if Shamt-XLEN < 0: // Shamt < XLEN 3398 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3399 // Hi = Hi >>s Shamt 3400 // else: 3401 // Lo = Hi >>s (Shamt-XLEN); 3402 // Hi = Hi >>s (XLEN-1) 3403 // 3404 // SRL expansion: 3405 // if Shamt-XLEN < 0: // Shamt < XLEN 3406 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3407 // Hi = Hi >>u Shamt 3408 // else: 3409 // Lo = Hi >>u (Shamt-XLEN); 3410 // Hi = 0; 3411 3412 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3413 3414 SDValue Zero = DAG.getConstant(0, DL, VT); 3415 SDValue One = DAG.getConstant(1, DL, VT); 3416 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3417 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3418 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3419 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3420 3421 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3422 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3423 SDValue ShiftLeftHi = 3424 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3425 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3426 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3427 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3428 SDValue HiFalse = 3429 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3430 3431 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3432 3433 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3434 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3435 3436 SDValue Parts[2] = {Lo, Hi}; 3437 return DAG.getMergeValues(Parts, DL); 3438 } 3439 3440 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3441 // legal equivalently-sized i8 type, so we can use that as a go-between. 3442 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3443 SelectionDAG &DAG) const { 3444 SDLoc DL(Op); 3445 MVT VT = Op.getSimpleValueType(); 3446 SDValue SplatVal = Op.getOperand(0); 3447 // All-zeros or all-ones splats are handled specially. 3448 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3449 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3450 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3451 } 3452 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3453 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3454 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3455 } 3456 MVT XLenVT = Subtarget.getXLenVT(); 3457 assert(SplatVal.getValueType() == XLenVT && 3458 "Unexpected type for i1 splat value"); 3459 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3460 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3461 DAG.getConstant(1, DL, XLenVT)); 3462 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3463 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3464 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3465 } 3466 3467 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3468 // illegal (currently only vXi64 RV32). 3469 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3470 // them to SPLAT_VECTOR_I64 3471 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3472 SelectionDAG &DAG) const { 3473 SDLoc DL(Op); 3474 MVT VecVT = Op.getSimpleValueType(); 3475 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3476 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3477 3478 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3479 SDValue Lo = Op.getOperand(0); 3480 SDValue Hi = Op.getOperand(1); 3481 3482 if (VecVT.isFixedLengthVector()) { 3483 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3484 SDLoc DL(Op); 3485 SDValue Mask, VL; 3486 std::tie(Mask, VL) = 3487 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3488 3489 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3490 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3491 } 3492 3493 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3494 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3495 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3496 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3497 // node in order to try and match RVV vector/scalar instructions. 3498 if ((LoC >> 31) == HiC) 3499 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3500 } 3501 3502 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3503 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3504 isa<ConstantSDNode>(Hi.getOperand(1)) && 3505 Hi.getConstantOperandVal(1) == 31) 3506 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3507 3508 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3509 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3510 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3511 } 3512 3513 // Custom-lower extensions from mask vectors by using a vselect either with 1 3514 // for zero/any-extension or -1 for sign-extension: 3515 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3516 // Note that any-extension is lowered identically to zero-extension. 3517 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3518 int64_t ExtTrueVal) const { 3519 SDLoc DL(Op); 3520 MVT VecVT = Op.getSimpleValueType(); 3521 SDValue Src = Op.getOperand(0); 3522 // Only custom-lower extensions from mask types 3523 assert(Src.getValueType().isVector() && 3524 Src.getValueType().getVectorElementType() == MVT::i1); 3525 3526 MVT XLenVT = Subtarget.getXLenVT(); 3527 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3528 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3529 3530 if (VecVT.isScalableVector()) { 3531 // Be careful not to introduce illegal scalar types at this stage, and be 3532 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3533 // illegal and must be expanded. Since we know that the constants are 3534 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3535 bool IsRV32E64 = 3536 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3537 3538 if (!IsRV32E64) { 3539 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3540 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3541 } else { 3542 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3543 SplatTrueVal = 3544 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3545 } 3546 3547 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3548 } 3549 3550 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3551 MVT I1ContainerVT = 3552 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3553 3554 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3555 3556 SDValue Mask, VL; 3557 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3558 3559 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3560 SplatTrueVal = 3561 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3562 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3563 SplatTrueVal, SplatZero, VL); 3564 3565 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3566 } 3567 3568 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3569 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3570 MVT ExtVT = Op.getSimpleValueType(); 3571 // Only custom-lower extensions from fixed-length vector types. 3572 if (!ExtVT.isFixedLengthVector()) 3573 return Op; 3574 MVT VT = Op.getOperand(0).getSimpleValueType(); 3575 // Grab the canonical container type for the extended type. Infer the smaller 3576 // type from that to ensure the same number of vector elements, as we know 3577 // the LMUL will be sufficient to hold the smaller type. 3578 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3579 // Get the extended container type manually to ensure the same number of 3580 // vector elements between source and dest. 3581 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3582 ContainerExtVT.getVectorElementCount()); 3583 3584 SDValue Op1 = 3585 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3586 3587 SDLoc DL(Op); 3588 SDValue Mask, VL; 3589 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3590 3591 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3592 3593 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3594 } 3595 3596 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3597 // setcc operation: 3598 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3599 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3600 SelectionDAG &DAG) const { 3601 SDLoc DL(Op); 3602 EVT MaskVT = Op.getValueType(); 3603 // Only expect to custom-lower truncations to mask types 3604 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3605 "Unexpected type for vector mask lowering"); 3606 SDValue Src = Op.getOperand(0); 3607 MVT VecVT = Src.getSimpleValueType(); 3608 3609 // If this is a fixed vector, we need to convert it to a scalable vector. 3610 MVT ContainerVT = VecVT; 3611 if (VecVT.isFixedLengthVector()) { 3612 ContainerVT = getContainerForFixedLengthVector(VecVT); 3613 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3614 } 3615 3616 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3617 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3618 3619 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3620 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3621 3622 if (VecVT.isScalableVector()) { 3623 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3624 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3625 } 3626 3627 SDValue Mask, VL; 3628 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3629 3630 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3631 SDValue Trunc = 3632 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3633 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3634 DAG.getCondCode(ISD::SETNE), Mask, VL); 3635 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3636 } 3637 3638 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3639 // first position of a vector, and that vector is slid up to the insert index. 3640 // By limiting the active vector length to index+1 and merging with the 3641 // original vector (with an undisturbed tail policy for elements >= VL), we 3642 // achieve the desired result of leaving all elements untouched except the one 3643 // at VL-1, which is replaced with the desired value. 3644 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3645 SelectionDAG &DAG) const { 3646 SDLoc DL(Op); 3647 MVT VecVT = Op.getSimpleValueType(); 3648 SDValue Vec = Op.getOperand(0); 3649 SDValue Val = Op.getOperand(1); 3650 SDValue Idx = Op.getOperand(2); 3651 3652 if (VecVT.getVectorElementType() == MVT::i1) { 3653 // FIXME: For now we just promote to an i8 vector and insert into that, 3654 // but this is probably not optimal. 3655 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3656 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3657 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3658 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3659 } 3660 3661 MVT ContainerVT = VecVT; 3662 // If the operand is a fixed-length vector, convert to a scalable one. 3663 if (VecVT.isFixedLengthVector()) { 3664 ContainerVT = getContainerForFixedLengthVector(VecVT); 3665 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3666 } 3667 3668 MVT XLenVT = Subtarget.getXLenVT(); 3669 3670 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3671 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3672 // Even i64-element vectors on RV32 can be lowered without scalar 3673 // legalization if the most-significant 32 bits of the value are not affected 3674 // by the sign-extension of the lower 32 bits. 3675 // TODO: We could also catch sign extensions of a 32-bit value. 3676 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3677 const auto *CVal = cast<ConstantSDNode>(Val); 3678 if (isInt<32>(CVal->getSExtValue())) { 3679 IsLegalInsert = true; 3680 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3681 } 3682 } 3683 3684 SDValue Mask, VL; 3685 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3686 3687 SDValue ValInVec; 3688 3689 if (IsLegalInsert) { 3690 unsigned Opc = 3691 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3692 if (isNullConstant(Idx)) { 3693 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3694 if (!VecVT.isFixedLengthVector()) 3695 return Vec; 3696 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3697 } 3698 ValInVec = 3699 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3700 } else { 3701 // On RV32, i64-element vectors must be specially handled to place the 3702 // value at element 0, by using two vslide1up instructions in sequence on 3703 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3704 // this. 3705 SDValue One = DAG.getConstant(1, DL, XLenVT); 3706 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3707 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3708 MVT I32ContainerVT = 3709 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3710 SDValue I32Mask = 3711 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3712 // Limit the active VL to two. 3713 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3714 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3715 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3716 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3717 InsertI64VL); 3718 // First slide in the hi value, then the lo in underneath it. 3719 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3720 ValHi, I32Mask, InsertI64VL); 3721 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3722 ValLo, I32Mask, InsertI64VL); 3723 // Bitcast back to the right container type. 3724 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3725 } 3726 3727 // Now that the value is in a vector, slide it into position. 3728 SDValue InsertVL = 3729 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3730 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3731 ValInVec, Idx, Mask, InsertVL); 3732 if (!VecVT.isFixedLengthVector()) 3733 return Slideup; 3734 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3735 } 3736 3737 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3738 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3739 // types this is done using VMV_X_S to allow us to glean information about the 3740 // sign bits of the result. 3741 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3742 SelectionDAG &DAG) const { 3743 SDLoc DL(Op); 3744 SDValue Idx = Op.getOperand(1); 3745 SDValue Vec = Op.getOperand(0); 3746 EVT EltVT = Op.getValueType(); 3747 MVT VecVT = Vec.getSimpleValueType(); 3748 MVT XLenVT = Subtarget.getXLenVT(); 3749 3750 if (VecVT.getVectorElementType() == MVT::i1) { 3751 // FIXME: For now we just promote to an i8 vector and extract from 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 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 3756 } 3757 3758 // If this is a fixed vector, we need to convert it to a scalable vector. 3759 MVT ContainerVT = VecVT; 3760 if (VecVT.isFixedLengthVector()) { 3761 ContainerVT = getContainerForFixedLengthVector(VecVT); 3762 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3763 } 3764 3765 // If the index is 0, the vector is already in the right position. 3766 if (!isNullConstant(Idx)) { 3767 // Use a VL of 1 to avoid processing more elements than we need. 3768 SDValue VL = DAG.getConstant(1, DL, XLenVT); 3769 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3770 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3771 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3772 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 3773 } 3774 3775 if (!EltVT.isInteger()) { 3776 // Floating-point extracts are handled in TableGen. 3777 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 3778 DAG.getConstant(0, DL, XLenVT)); 3779 } 3780 3781 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 3782 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 3783 } 3784 3785 // Some RVV intrinsics may claim that they want an integer operand to be 3786 // promoted or expanded. 3787 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 3788 const RISCVSubtarget &Subtarget) { 3789 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3790 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 3791 "Unexpected opcode"); 3792 3793 if (!Subtarget.hasVInstructions()) 3794 return SDValue(); 3795 3796 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 3797 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 3798 SDLoc DL(Op); 3799 3800 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 3801 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 3802 if (!II || !II->SplatOperand) 3803 return SDValue(); 3804 3805 unsigned SplatOp = II->SplatOperand + HasChain; 3806 assert(SplatOp < Op.getNumOperands()); 3807 3808 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 3809 SDValue &ScalarOp = Operands[SplatOp]; 3810 MVT OpVT = ScalarOp.getSimpleValueType(); 3811 MVT XLenVT = Subtarget.getXLenVT(); 3812 3813 // If this isn't a scalar, or its type is XLenVT we're done. 3814 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 3815 return SDValue(); 3816 3817 // Simplest case is that the operand needs to be promoted to XLenVT. 3818 if (OpVT.bitsLT(XLenVT)) { 3819 // If the operand is a constant, sign extend to increase our chances 3820 // of being able to use a .vi instruction. ANY_EXTEND would become a 3821 // a zero extend and the simm5 check in isel would fail. 3822 // FIXME: Should we ignore the upper bits in isel instead? 3823 unsigned ExtOpc = 3824 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 3825 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 3826 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3827 } 3828 3829 // Use the previous operand to get the vXi64 VT. The result might be a mask 3830 // VT for compares. Using the previous operand assumes that the previous 3831 // operand will never have a smaller element size than a scalar operand and 3832 // that a widening operation never uses SEW=64. 3833 // NOTE: If this fails the below assert, we can probably just find the 3834 // element count from any operand or result and use it to construct the VT. 3835 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 3836 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 3837 3838 // The more complex case is when the scalar is larger than XLenVT. 3839 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 3840 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 3841 3842 // If this is a sign-extended 32-bit constant, we can truncate it and rely 3843 // on the instruction to sign-extend since SEW>XLEN. 3844 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 3845 if (isInt<32>(CVal->getSExtValue())) { 3846 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3847 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3848 } 3849 } 3850 3851 // We need to convert the scalar to a splat vector. 3852 // FIXME: Can we implicitly truncate the scalar if it is known to 3853 // be sign extended? 3854 // VL should be the last operand. 3855 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 3856 assert(VL.getValueType() == XLenVT); 3857 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 3858 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3859 } 3860 3861 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3862 SelectionDAG &DAG) const { 3863 unsigned IntNo = Op.getConstantOperandVal(0); 3864 SDLoc DL(Op); 3865 MVT XLenVT = Subtarget.getXLenVT(); 3866 3867 switch (IntNo) { 3868 default: 3869 break; // Don't custom lower most intrinsics. 3870 case Intrinsic::thread_pointer: { 3871 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3872 return DAG.getRegister(RISCV::X4, PtrVT); 3873 } 3874 case Intrinsic::riscv_orc_b: 3875 // Lower to the GORCI encoding for orc.b. 3876 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 3877 DAG.getConstant(7, DL, XLenVT)); 3878 case Intrinsic::riscv_grev: 3879 case Intrinsic::riscv_gorc: { 3880 unsigned Opc = 3881 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 3882 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3883 } 3884 case Intrinsic::riscv_shfl: 3885 case Intrinsic::riscv_unshfl: { 3886 unsigned Opc = 3887 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 3888 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3889 } 3890 case Intrinsic::riscv_bcompress: 3891 case Intrinsic::riscv_bdecompress: { 3892 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 3893 : RISCVISD::BDECOMPRESS; 3894 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3895 } 3896 case Intrinsic::riscv_vmv_x_s: 3897 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 3898 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 3899 Op.getOperand(1)); 3900 case Intrinsic::riscv_vmv_v_x: 3901 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 3902 Op.getSimpleValueType(), DL, DAG, Subtarget); 3903 case Intrinsic::riscv_vfmv_v_f: 3904 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 3905 Op.getOperand(1), Op.getOperand(2)); 3906 case Intrinsic::riscv_vmv_s_x: { 3907 SDValue Scalar = Op.getOperand(2); 3908 3909 if (Scalar.getValueType().bitsLE(XLenVT)) { 3910 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 3911 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 3912 Op.getOperand(1), Scalar, Op.getOperand(3)); 3913 } 3914 3915 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 3916 3917 // This is an i64 value that lives in two scalar registers. We have to 3918 // insert this in a convoluted way. First we build vXi64 splat containing 3919 // the/ two values that we assemble using some bit math. Next we'll use 3920 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 3921 // to merge element 0 from our splat into the source vector. 3922 // FIXME: This is probably not the best way to do this, but it is 3923 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 3924 // point. 3925 // sw lo, (a0) 3926 // sw hi, 4(a0) 3927 // vlse vX, (a0) 3928 // 3929 // vid.v vVid 3930 // vmseq.vx mMask, vVid, 0 3931 // vmerge.vvm vDest, vSrc, vVal, mMask 3932 MVT VT = Op.getSimpleValueType(); 3933 SDValue Vec = Op.getOperand(1); 3934 SDValue VL = Op.getOperand(3); 3935 3936 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 3937 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 3938 DAG.getConstant(0, DL, MVT::i32), VL); 3939 3940 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 3941 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3942 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 3943 SDValue SelectCond = 3944 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 3945 DAG.getCondCode(ISD::SETEQ), Mask, VL); 3946 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 3947 Vec, VL); 3948 } 3949 case Intrinsic::riscv_vslide1up: 3950 case Intrinsic::riscv_vslide1down: 3951 case Intrinsic::riscv_vslide1up_mask: 3952 case Intrinsic::riscv_vslide1down_mask: { 3953 // We need to special case these when the scalar is larger than XLen. 3954 unsigned NumOps = Op.getNumOperands(); 3955 bool IsMasked = NumOps == 7; 3956 unsigned OpOffset = IsMasked ? 1 : 0; 3957 SDValue Scalar = Op.getOperand(2 + OpOffset); 3958 if (Scalar.getValueType().bitsLE(XLenVT)) 3959 break; 3960 3961 // Splatting a sign extended constant is fine. 3962 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 3963 if (isInt<32>(CVal->getSExtValue())) 3964 break; 3965 3966 MVT VT = Op.getSimpleValueType(); 3967 assert(VT.getVectorElementType() == MVT::i64 && 3968 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 3969 3970 // Convert the vector source to the equivalent nxvXi32 vector. 3971 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 3972 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 3973 3974 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3975 DAG.getConstant(0, DL, XLenVT)); 3976 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3977 DAG.getConstant(1, DL, XLenVT)); 3978 3979 // Double the VL since we halved SEW. 3980 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 3981 SDValue I32VL = 3982 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 3983 3984 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 3985 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 3986 3987 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 3988 // instructions. 3989 if (IntNo == Intrinsic::riscv_vslide1up || 3990 IntNo == Intrinsic::riscv_vslide1up_mask) { 3991 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 3992 I32Mask, I32VL); 3993 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 3994 I32Mask, I32VL); 3995 } else { 3996 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 3997 I32Mask, I32VL); 3998 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 3999 I32Mask, I32VL); 4000 } 4001 4002 // Convert back to nxvXi64. 4003 Vec = DAG.getBitcast(VT, Vec); 4004 4005 if (!IsMasked) 4006 return Vec; 4007 4008 // Apply mask after the operation. 4009 SDValue Mask = Op.getOperand(NumOps - 3); 4010 SDValue MaskedOff = Op.getOperand(1); 4011 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4012 } 4013 } 4014 4015 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4016 } 4017 4018 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4019 SelectionDAG &DAG) const { 4020 unsigned IntNo = Op.getConstantOperandVal(1); 4021 switch (IntNo) { 4022 default: 4023 break; 4024 case Intrinsic::riscv_masked_strided_load: { 4025 SDLoc DL(Op); 4026 MVT XLenVT = Subtarget.getXLenVT(); 4027 4028 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4029 // the selection of the masked intrinsics doesn't do this for us. 4030 SDValue Mask = Op.getOperand(5); 4031 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4032 4033 MVT VT = Op->getSimpleValueType(0); 4034 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4035 4036 SDValue PassThru = Op.getOperand(2); 4037 if (!IsUnmasked) { 4038 MVT MaskVT = 4039 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4040 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4041 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4042 } 4043 4044 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4045 4046 SDValue IntID = DAG.getTargetConstant( 4047 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4048 XLenVT); 4049 4050 auto *Load = cast<MemIntrinsicSDNode>(Op); 4051 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4052 if (!IsUnmasked) 4053 Ops.push_back(PassThru); 4054 Ops.push_back(Op.getOperand(3)); // Ptr 4055 Ops.push_back(Op.getOperand(4)); // Stride 4056 if (!IsUnmasked) 4057 Ops.push_back(Mask); 4058 Ops.push_back(VL); 4059 if (!IsUnmasked) { 4060 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4061 Ops.push_back(Policy); 4062 } 4063 4064 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4065 SDValue Result = 4066 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4067 Load->getMemoryVT(), Load->getMemOperand()); 4068 SDValue Chain = Result.getValue(1); 4069 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4070 return DAG.getMergeValues({Result, Chain}, DL); 4071 } 4072 } 4073 4074 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4075 } 4076 4077 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4078 SelectionDAG &DAG) const { 4079 unsigned IntNo = Op.getConstantOperandVal(1); 4080 switch (IntNo) { 4081 default: 4082 break; 4083 case Intrinsic::riscv_masked_strided_store: { 4084 SDLoc DL(Op); 4085 MVT XLenVT = Subtarget.getXLenVT(); 4086 4087 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4088 // the selection of the masked intrinsics doesn't do this for us. 4089 SDValue Mask = Op.getOperand(5); 4090 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4091 4092 SDValue Val = Op.getOperand(2); 4093 MVT VT = Val.getSimpleValueType(); 4094 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4095 4096 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4097 if (!IsUnmasked) { 4098 MVT MaskVT = 4099 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4100 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4101 } 4102 4103 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4104 4105 SDValue IntID = DAG.getTargetConstant( 4106 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4107 XLenVT); 4108 4109 auto *Store = cast<MemIntrinsicSDNode>(Op); 4110 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4111 Ops.push_back(Val); 4112 Ops.push_back(Op.getOperand(3)); // Ptr 4113 Ops.push_back(Op.getOperand(4)); // Stride 4114 if (!IsUnmasked) 4115 Ops.push_back(Mask); 4116 Ops.push_back(VL); 4117 4118 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4119 Ops, Store->getMemoryVT(), 4120 Store->getMemOperand()); 4121 } 4122 } 4123 4124 return SDValue(); 4125 } 4126 4127 static MVT getLMUL1VT(MVT VT) { 4128 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4129 "Unexpected vector MVT"); 4130 return MVT::getScalableVectorVT( 4131 VT.getVectorElementType(), 4132 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4133 } 4134 4135 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4136 switch (ISDOpcode) { 4137 default: 4138 llvm_unreachable("Unhandled reduction"); 4139 case ISD::VECREDUCE_ADD: 4140 return RISCVISD::VECREDUCE_ADD_VL; 4141 case ISD::VECREDUCE_UMAX: 4142 return RISCVISD::VECREDUCE_UMAX_VL; 4143 case ISD::VECREDUCE_SMAX: 4144 return RISCVISD::VECREDUCE_SMAX_VL; 4145 case ISD::VECREDUCE_UMIN: 4146 return RISCVISD::VECREDUCE_UMIN_VL; 4147 case ISD::VECREDUCE_SMIN: 4148 return RISCVISD::VECREDUCE_SMIN_VL; 4149 case ISD::VECREDUCE_AND: 4150 return RISCVISD::VECREDUCE_AND_VL; 4151 case ISD::VECREDUCE_OR: 4152 return RISCVISD::VECREDUCE_OR_VL; 4153 case ISD::VECREDUCE_XOR: 4154 return RISCVISD::VECREDUCE_XOR_VL; 4155 } 4156 } 4157 4158 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4159 SelectionDAG &DAG, 4160 bool IsVP) const { 4161 SDLoc DL(Op); 4162 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4163 MVT VecVT = Vec.getSimpleValueType(); 4164 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4165 Op.getOpcode() == ISD::VECREDUCE_OR || 4166 Op.getOpcode() == ISD::VECREDUCE_XOR || 4167 Op.getOpcode() == ISD::VP_REDUCE_AND || 4168 Op.getOpcode() == ISD::VP_REDUCE_OR || 4169 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4170 "Unexpected reduction lowering"); 4171 4172 MVT XLenVT = Subtarget.getXLenVT(); 4173 assert(Op.getValueType() == XLenVT && 4174 "Expected reduction output to be legalized to XLenVT"); 4175 4176 MVT ContainerVT = VecVT; 4177 if (VecVT.isFixedLengthVector()) { 4178 ContainerVT = getContainerForFixedLengthVector(VecVT); 4179 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4180 } 4181 4182 SDValue Mask, VL; 4183 if (IsVP) { 4184 Mask = Op.getOperand(2); 4185 VL = Op.getOperand(3); 4186 } else { 4187 std::tie(Mask, VL) = 4188 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4189 } 4190 4191 unsigned BaseOpc; 4192 ISD::CondCode CC; 4193 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4194 4195 switch (Op.getOpcode()) { 4196 default: 4197 llvm_unreachable("Unhandled reduction"); 4198 case ISD::VECREDUCE_AND: 4199 case ISD::VP_REDUCE_AND: { 4200 // vcpop ~x == 0 4201 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4202 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4203 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4204 CC = ISD::SETEQ; 4205 BaseOpc = ISD::AND; 4206 break; 4207 } 4208 case ISD::VECREDUCE_OR: 4209 case ISD::VP_REDUCE_OR: 4210 // vcpop x != 0 4211 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4212 CC = ISD::SETNE; 4213 BaseOpc = ISD::OR; 4214 break; 4215 case ISD::VECREDUCE_XOR: 4216 case ISD::VP_REDUCE_XOR: { 4217 // ((vcpop x) & 1) != 0 4218 SDValue One = DAG.getConstant(1, DL, XLenVT); 4219 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4220 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4221 CC = ISD::SETNE; 4222 BaseOpc = ISD::XOR; 4223 break; 4224 } 4225 } 4226 4227 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4228 4229 if (!IsVP) 4230 return SetCC; 4231 4232 // Now include the start value in the operation. 4233 // Note that we must return the start value when no elements are operated 4234 // upon. The vcpop instructions we've emitted in each case above will return 4235 // 0 for an inactive vector, and so we've already received the neutral value: 4236 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4237 // can simply include the start value. 4238 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4239 } 4240 4241 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4242 SelectionDAG &DAG) const { 4243 SDLoc DL(Op); 4244 SDValue Vec = Op.getOperand(0); 4245 EVT VecEVT = Vec.getValueType(); 4246 4247 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4248 4249 // Due to ordering in legalize types we may have a vector type that needs to 4250 // be split. Do that manually so we can get down to a legal type. 4251 while (getTypeAction(*DAG.getContext(), VecEVT) == 4252 TargetLowering::TypeSplitVector) { 4253 SDValue Lo, Hi; 4254 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4255 VecEVT = Lo.getValueType(); 4256 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4257 } 4258 4259 // TODO: The type may need to be widened rather than split. Or widened before 4260 // it can be split. 4261 if (!isTypeLegal(VecEVT)) 4262 return SDValue(); 4263 4264 MVT VecVT = VecEVT.getSimpleVT(); 4265 MVT VecEltVT = VecVT.getVectorElementType(); 4266 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4267 4268 MVT ContainerVT = VecVT; 4269 if (VecVT.isFixedLengthVector()) { 4270 ContainerVT = getContainerForFixedLengthVector(VecVT); 4271 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4272 } 4273 4274 MVT M1VT = getLMUL1VT(ContainerVT); 4275 4276 SDValue Mask, VL; 4277 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4278 4279 // FIXME: This is a VLMAX splat which might be too large and can prevent 4280 // vsetvli removal. 4281 SDValue NeutralElem = 4282 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4283 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 4284 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4285 IdentitySplat, Mask, VL); 4286 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4287 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4288 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4289 } 4290 4291 // Given a reduction op, this function returns the matching reduction opcode, 4292 // the vector SDValue and the scalar SDValue required to lower this to a 4293 // RISCVISD node. 4294 static std::tuple<unsigned, SDValue, SDValue> 4295 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4296 SDLoc DL(Op); 4297 auto Flags = Op->getFlags(); 4298 unsigned Opcode = Op.getOpcode(); 4299 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4300 switch (Opcode) { 4301 default: 4302 llvm_unreachable("Unhandled reduction"); 4303 case ISD::VECREDUCE_FADD: 4304 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 4305 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4306 case ISD::VECREDUCE_SEQ_FADD: 4307 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4308 Op.getOperand(0)); 4309 case ISD::VECREDUCE_FMIN: 4310 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4311 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4312 case ISD::VECREDUCE_FMAX: 4313 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4314 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4315 } 4316 } 4317 4318 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4319 SelectionDAG &DAG) const { 4320 SDLoc DL(Op); 4321 MVT VecEltVT = Op.getSimpleValueType(); 4322 4323 unsigned RVVOpcode; 4324 SDValue VectorVal, ScalarVal; 4325 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4326 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4327 MVT VecVT = VectorVal.getSimpleValueType(); 4328 4329 MVT ContainerVT = VecVT; 4330 if (VecVT.isFixedLengthVector()) { 4331 ContainerVT = getContainerForFixedLengthVector(VecVT); 4332 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4333 } 4334 4335 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4336 4337 SDValue Mask, VL; 4338 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4339 4340 // FIXME: This is a VLMAX splat which might be too large and can prevent 4341 // vsetvli removal. 4342 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 4343 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4344 VectorVal, ScalarSplat, Mask, VL); 4345 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4346 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4347 } 4348 4349 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4350 switch (ISDOpcode) { 4351 default: 4352 llvm_unreachable("Unhandled reduction"); 4353 case ISD::VP_REDUCE_ADD: 4354 return RISCVISD::VECREDUCE_ADD_VL; 4355 case ISD::VP_REDUCE_UMAX: 4356 return RISCVISD::VECREDUCE_UMAX_VL; 4357 case ISD::VP_REDUCE_SMAX: 4358 return RISCVISD::VECREDUCE_SMAX_VL; 4359 case ISD::VP_REDUCE_UMIN: 4360 return RISCVISD::VECREDUCE_UMIN_VL; 4361 case ISD::VP_REDUCE_SMIN: 4362 return RISCVISD::VECREDUCE_SMIN_VL; 4363 case ISD::VP_REDUCE_AND: 4364 return RISCVISD::VECREDUCE_AND_VL; 4365 case ISD::VP_REDUCE_OR: 4366 return RISCVISD::VECREDUCE_OR_VL; 4367 case ISD::VP_REDUCE_XOR: 4368 return RISCVISD::VECREDUCE_XOR_VL; 4369 case ISD::VP_REDUCE_FADD: 4370 return RISCVISD::VECREDUCE_FADD_VL; 4371 case ISD::VP_REDUCE_SEQ_FADD: 4372 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4373 case ISD::VP_REDUCE_FMAX: 4374 return RISCVISD::VECREDUCE_FMAX_VL; 4375 case ISD::VP_REDUCE_FMIN: 4376 return RISCVISD::VECREDUCE_FMIN_VL; 4377 } 4378 } 4379 4380 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4381 SelectionDAG &DAG) const { 4382 SDLoc DL(Op); 4383 SDValue Vec = Op.getOperand(1); 4384 EVT VecEVT = Vec.getValueType(); 4385 4386 // TODO: The type may need to be widened rather than split. Or widened before 4387 // it can be split. 4388 if (!isTypeLegal(VecEVT)) 4389 return SDValue(); 4390 4391 MVT VecVT = VecEVT.getSimpleVT(); 4392 MVT VecEltVT = VecVT.getVectorElementType(); 4393 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4394 4395 MVT ContainerVT = VecVT; 4396 if (VecVT.isFixedLengthVector()) { 4397 ContainerVT = getContainerForFixedLengthVector(VecVT); 4398 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4399 } 4400 4401 SDValue VL = Op.getOperand(3); 4402 SDValue Mask = Op.getOperand(2); 4403 4404 MVT M1VT = getLMUL1VT(ContainerVT); 4405 MVT XLenVT = Subtarget.getXLenVT(); 4406 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4407 4408 // FIXME: This is a VLMAX splat which might be too large and can prevent 4409 // vsetvli removal. 4410 SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0)); 4411 SDValue Reduction = 4412 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4413 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4414 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4415 if (!VecVT.isInteger()) 4416 return Elt0; 4417 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4418 } 4419 4420 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4421 SelectionDAG &DAG) const { 4422 SDValue Vec = Op.getOperand(0); 4423 SDValue SubVec = Op.getOperand(1); 4424 MVT VecVT = Vec.getSimpleValueType(); 4425 MVT SubVecVT = SubVec.getSimpleValueType(); 4426 4427 SDLoc DL(Op); 4428 MVT XLenVT = Subtarget.getXLenVT(); 4429 unsigned OrigIdx = Op.getConstantOperandVal(2); 4430 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4431 4432 // We don't have the ability to slide mask vectors up indexed by their i1 4433 // elements; the smallest we can do is i8. Often we are able to bitcast to 4434 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4435 // into a scalable one, we might not necessarily have enough scalable 4436 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4437 if (SubVecVT.getVectorElementType() == MVT::i1 && 4438 (OrigIdx != 0 || !Vec.isUndef())) { 4439 if (VecVT.getVectorMinNumElements() >= 8 && 4440 SubVecVT.getVectorMinNumElements() >= 8) { 4441 assert(OrigIdx % 8 == 0 && "Invalid index"); 4442 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4443 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4444 "Unexpected mask vector lowering"); 4445 OrigIdx /= 8; 4446 SubVecVT = 4447 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4448 SubVecVT.isScalableVector()); 4449 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4450 VecVT.isScalableVector()); 4451 Vec = DAG.getBitcast(VecVT, Vec); 4452 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4453 } else { 4454 // We can't slide this mask vector up indexed by its i1 elements. 4455 // This poses a problem when we wish to insert a scalable vector which 4456 // can't be re-expressed as a larger type. Just choose the slow path and 4457 // extend to a larger type, then truncate back down. 4458 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4459 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4460 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4461 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4462 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4463 Op.getOperand(2)); 4464 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4465 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4466 } 4467 } 4468 4469 // If the subvector vector is a fixed-length type, we cannot use subregister 4470 // manipulation to simplify the codegen; we don't know which register of a 4471 // LMUL group contains the specific subvector as we only know the minimum 4472 // register size. Therefore we must slide the vector group up the full 4473 // amount. 4474 if (SubVecVT.isFixedLengthVector()) { 4475 if (OrigIdx == 0 && Vec.isUndef()) 4476 return Op; 4477 MVT ContainerVT = VecVT; 4478 if (VecVT.isFixedLengthVector()) { 4479 ContainerVT = getContainerForFixedLengthVector(VecVT); 4480 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4481 } 4482 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4483 DAG.getUNDEF(ContainerVT), SubVec, 4484 DAG.getConstant(0, DL, XLenVT)); 4485 SDValue Mask = 4486 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4487 // Set the vector length to only the number of elements we care about. Note 4488 // that for slideup this includes the offset. 4489 SDValue VL = 4490 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4491 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4492 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4493 SubVec, SlideupAmt, Mask, VL); 4494 if (VecVT.isFixedLengthVector()) 4495 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4496 return DAG.getBitcast(Op.getValueType(), Slideup); 4497 } 4498 4499 unsigned SubRegIdx, RemIdx; 4500 std::tie(SubRegIdx, RemIdx) = 4501 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4502 VecVT, SubVecVT, OrigIdx, TRI); 4503 4504 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4505 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4506 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4507 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4508 4509 // 1. If the Idx has been completely eliminated and this subvector's size is 4510 // a vector register or a multiple thereof, or the surrounding elements are 4511 // undef, then this is a subvector insert which naturally aligns to a vector 4512 // register. These can easily be handled using subregister manipulation. 4513 // 2. If the subvector is smaller than a vector register, then the insertion 4514 // must preserve the undisturbed elements of the register. We do this by 4515 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4516 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4517 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4518 // LMUL=1 type back into the larger vector (resolving to another subregister 4519 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4520 // to avoid allocating a large register group to hold our subvector. 4521 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4522 return Op; 4523 4524 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4525 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4526 // (in our case undisturbed). This means we can set up a subvector insertion 4527 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4528 // size of the subvector. 4529 MVT InterSubVT = VecVT; 4530 SDValue AlignedExtract = Vec; 4531 unsigned AlignedIdx = OrigIdx - RemIdx; 4532 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4533 InterSubVT = getLMUL1VT(VecVT); 4534 // Extract a subvector equal to the nearest full vector register type. This 4535 // should resolve to a EXTRACT_SUBREG instruction. 4536 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4537 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4538 } 4539 4540 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4541 // For scalable vectors this must be further multiplied by vscale. 4542 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4543 4544 SDValue Mask, VL; 4545 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4546 4547 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4548 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4549 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4550 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4551 4552 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4553 DAG.getUNDEF(InterSubVT), SubVec, 4554 DAG.getConstant(0, DL, XLenVT)); 4555 4556 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4557 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4558 4559 // If required, insert this subvector back into the correct vector register. 4560 // This should resolve to an INSERT_SUBREG instruction. 4561 if (VecVT.bitsGT(InterSubVT)) 4562 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4563 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4564 4565 // We might have bitcast from a mask type: cast back to the original type if 4566 // required. 4567 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4568 } 4569 4570 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4571 SelectionDAG &DAG) const { 4572 SDValue Vec = Op.getOperand(0); 4573 MVT SubVecVT = Op.getSimpleValueType(); 4574 MVT VecVT = Vec.getSimpleValueType(); 4575 4576 SDLoc DL(Op); 4577 MVT XLenVT = Subtarget.getXLenVT(); 4578 unsigned OrigIdx = Op.getConstantOperandVal(1); 4579 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4580 4581 // We don't have the ability to slide mask vectors down indexed by their i1 4582 // elements; the smallest we can do is i8. Often we are able to bitcast to 4583 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4584 // from a scalable one, we might not necessarily have enough scalable 4585 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4586 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4587 if (VecVT.getVectorMinNumElements() >= 8 && 4588 SubVecVT.getVectorMinNumElements() >= 8) { 4589 assert(OrigIdx % 8 == 0 && "Invalid index"); 4590 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4591 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4592 "Unexpected mask vector lowering"); 4593 OrigIdx /= 8; 4594 SubVecVT = 4595 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4596 SubVecVT.isScalableVector()); 4597 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4598 VecVT.isScalableVector()); 4599 Vec = DAG.getBitcast(VecVT, Vec); 4600 } else { 4601 // We can't slide this mask vector down, indexed by its i1 elements. 4602 // This poses a problem when we wish to extract a scalable vector which 4603 // can't be re-expressed as a larger type. Just choose the slow path and 4604 // extend to a larger type, then truncate back down. 4605 // TODO: We could probably improve this when extracting certain fixed 4606 // from fixed, where we can extract as i8 and shift the correct element 4607 // right to reach the desired subvector? 4608 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4609 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4610 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4611 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4612 Op.getOperand(1)); 4613 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4614 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4615 } 4616 } 4617 4618 // If the subvector vector is a fixed-length type, we cannot use subregister 4619 // manipulation to simplify the codegen; we don't know which register of a 4620 // LMUL group contains the specific subvector as we only know the minimum 4621 // register size. Therefore we must slide the vector group down the full 4622 // amount. 4623 if (SubVecVT.isFixedLengthVector()) { 4624 // With an index of 0 this is a cast-like subvector, which can be performed 4625 // with subregister operations. 4626 if (OrigIdx == 0) 4627 return Op; 4628 MVT ContainerVT = VecVT; 4629 if (VecVT.isFixedLengthVector()) { 4630 ContainerVT = getContainerForFixedLengthVector(VecVT); 4631 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4632 } 4633 SDValue Mask = 4634 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4635 // Set the vector length to only the number of elements we care about. This 4636 // avoids sliding down elements we're going to discard straight away. 4637 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4638 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4639 SDValue Slidedown = 4640 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4641 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4642 // Now we can use a cast-like subvector extract to get the result. 4643 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4644 DAG.getConstant(0, DL, XLenVT)); 4645 return DAG.getBitcast(Op.getValueType(), Slidedown); 4646 } 4647 4648 unsigned SubRegIdx, RemIdx; 4649 std::tie(SubRegIdx, RemIdx) = 4650 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4651 VecVT, SubVecVT, OrigIdx, TRI); 4652 4653 // If the Idx has been completely eliminated then this is a subvector extract 4654 // which naturally aligns to a vector register. These can easily be handled 4655 // using subregister manipulation. 4656 if (RemIdx == 0) 4657 return Op; 4658 4659 // Else we must shift our vector register directly to extract the subvector. 4660 // Do this using VSLIDEDOWN. 4661 4662 // If the vector type is an LMUL-group type, extract a subvector equal to the 4663 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4664 // instruction. 4665 MVT InterSubVT = VecVT; 4666 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4667 InterSubVT = getLMUL1VT(VecVT); 4668 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4669 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4670 } 4671 4672 // Slide this vector register down by the desired number of elements in order 4673 // to place the desired subvector starting at element 0. 4674 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4675 // For scalable vectors this must be further multiplied by vscale. 4676 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4677 4678 SDValue Mask, VL; 4679 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4680 SDValue Slidedown = 4681 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4682 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4683 4684 // Now the vector is in the right position, extract our final subvector. This 4685 // should resolve to a COPY. 4686 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4687 DAG.getConstant(0, DL, XLenVT)); 4688 4689 // We might have bitcast from a mask type: cast back to the original type if 4690 // required. 4691 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4692 } 4693 4694 // Lower step_vector to the vid instruction. Any non-identity step value must 4695 // be accounted for my manual expansion. 4696 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4697 SelectionDAG &DAG) const { 4698 SDLoc DL(Op); 4699 MVT VT = Op.getSimpleValueType(); 4700 MVT XLenVT = Subtarget.getXLenVT(); 4701 SDValue Mask, VL; 4702 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4703 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4704 uint64_t StepValImm = Op.getConstantOperandVal(0); 4705 if (StepValImm != 1) { 4706 if (isPowerOf2_64(StepValImm)) { 4707 SDValue StepVal = 4708 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4709 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4710 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4711 } else { 4712 SDValue StepVal = lowerScalarSplat( 4713 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4714 DL, DAG, Subtarget); 4715 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4716 } 4717 } 4718 return StepVec; 4719 } 4720 4721 // Implement vector_reverse using vrgather.vv with indices determined by 4722 // subtracting the id of each element from (VLMAX-1). This will convert 4723 // the indices like so: 4724 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4725 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4726 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4727 SelectionDAG &DAG) const { 4728 SDLoc DL(Op); 4729 MVT VecVT = Op.getSimpleValueType(); 4730 unsigned EltSize = VecVT.getScalarSizeInBits(); 4731 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4732 4733 unsigned MaxVLMAX = 0; 4734 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4735 if (VectorBitsMax != 0) 4736 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4737 4738 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4739 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4740 4741 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4742 // to use vrgatherei16.vv. 4743 // TODO: It's also possible to use vrgatherei16.vv for other types to 4744 // decrease register width for the index calculation. 4745 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4746 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4747 // Reverse each half, then reassemble them in reverse order. 4748 // NOTE: It's also possible that after splitting that VLMAX no longer 4749 // requires vrgatherei16.vv. 4750 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4751 SDValue Lo, Hi; 4752 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4753 EVT LoVT, HiVT; 4754 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 4755 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 4756 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 4757 // Reassemble the low and high pieces reversed. 4758 // FIXME: This is a CONCAT_VECTORS. 4759 SDValue Res = 4760 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 4761 DAG.getIntPtrConstant(0, DL)); 4762 return DAG.getNode( 4763 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 4764 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 4765 } 4766 4767 // Just promote the int type to i16 which will double the LMUL. 4768 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 4769 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 4770 } 4771 4772 MVT XLenVT = Subtarget.getXLenVT(); 4773 SDValue Mask, VL; 4774 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4775 4776 // Calculate VLMAX-1 for the desired SEW. 4777 unsigned MinElts = VecVT.getVectorMinNumElements(); 4778 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 4779 DAG.getConstant(MinElts, DL, XLenVT)); 4780 SDValue VLMinus1 = 4781 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 4782 4783 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 4784 bool IsRV32E64 = 4785 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 4786 SDValue SplatVL; 4787 if (!IsRV32E64) 4788 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 4789 else 4790 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 4791 4792 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 4793 SDValue Indices = 4794 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 4795 4796 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 4797 } 4798 4799 SDValue 4800 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 4801 SelectionDAG &DAG) const { 4802 SDLoc DL(Op); 4803 auto *Load = cast<LoadSDNode>(Op); 4804 4805 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4806 Load->getMemoryVT(), 4807 *Load->getMemOperand()) && 4808 "Expecting a correctly-aligned load"); 4809 4810 MVT VT = Op.getSimpleValueType(); 4811 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4812 4813 SDValue VL = 4814 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4815 4816 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4817 SDValue NewLoad = DAG.getMemIntrinsicNode( 4818 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 4819 Load->getMemoryVT(), Load->getMemOperand()); 4820 4821 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 4822 return DAG.getMergeValues({Result, Load->getChain()}, DL); 4823 } 4824 4825 SDValue 4826 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 4827 SelectionDAG &DAG) const { 4828 SDLoc DL(Op); 4829 auto *Store = cast<StoreSDNode>(Op); 4830 4831 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4832 Store->getMemoryVT(), 4833 *Store->getMemOperand()) && 4834 "Expecting a correctly-aligned store"); 4835 4836 SDValue StoreVal = Store->getValue(); 4837 MVT VT = StoreVal.getSimpleValueType(); 4838 4839 // If the size less than a byte, we need to pad with zeros to make a byte. 4840 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 4841 VT = MVT::v8i1; 4842 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 4843 DAG.getConstant(0, DL, VT), StoreVal, 4844 DAG.getIntPtrConstant(0, DL)); 4845 } 4846 4847 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4848 4849 SDValue VL = 4850 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4851 4852 SDValue NewValue = 4853 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 4854 return DAG.getMemIntrinsicNode( 4855 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 4856 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 4857 Store->getMemoryVT(), Store->getMemOperand()); 4858 } 4859 4860 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 4861 SelectionDAG &DAG) const { 4862 SDLoc DL(Op); 4863 MVT VT = Op.getSimpleValueType(); 4864 4865 const auto *MemSD = cast<MemSDNode>(Op); 4866 EVT MemVT = MemSD->getMemoryVT(); 4867 MachineMemOperand *MMO = MemSD->getMemOperand(); 4868 SDValue Chain = MemSD->getChain(); 4869 SDValue BasePtr = MemSD->getBasePtr(); 4870 4871 SDValue Mask, PassThru, VL; 4872 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 4873 Mask = VPLoad->getMask(); 4874 PassThru = DAG.getUNDEF(VT); 4875 VL = VPLoad->getVectorLength(); 4876 } else { 4877 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 4878 Mask = MLoad->getMask(); 4879 PassThru = MLoad->getPassThru(); 4880 } 4881 4882 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4883 4884 MVT XLenVT = Subtarget.getXLenVT(); 4885 4886 MVT ContainerVT = VT; 4887 if (VT.isFixedLengthVector()) { 4888 ContainerVT = getContainerForFixedLengthVector(VT); 4889 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4890 if (!IsUnmasked) { 4891 MVT MaskVT = 4892 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4893 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4894 } 4895 } 4896 4897 if (!VL) 4898 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4899 4900 unsigned IntID = 4901 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 4902 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 4903 if (!IsUnmasked) 4904 Ops.push_back(PassThru); 4905 Ops.push_back(BasePtr); 4906 if (!IsUnmasked) 4907 Ops.push_back(Mask); 4908 Ops.push_back(VL); 4909 if (!IsUnmasked) 4910 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 4911 4912 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4913 4914 SDValue Result = 4915 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 4916 Chain = Result.getValue(1); 4917 4918 if (VT.isFixedLengthVector()) 4919 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4920 4921 return DAG.getMergeValues({Result, Chain}, DL); 4922 } 4923 4924 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 4925 SelectionDAG &DAG) const { 4926 SDLoc DL(Op); 4927 4928 const auto *MemSD = cast<MemSDNode>(Op); 4929 EVT MemVT = MemSD->getMemoryVT(); 4930 MachineMemOperand *MMO = MemSD->getMemOperand(); 4931 SDValue Chain = MemSD->getChain(); 4932 SDValue BasePtr = MemSD->getBasePtr(); 4933 SDValue Val, Mask, VL; 4934 4935 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 4936 Val = VPStore->getValue(); 4937 Mask = VPStore->getMask(); 4938 VL = VPStore->getVectorLength(); 4939 } else { 4940 const auto *MStore = cast<MaskedStoreSDNode>(Op); 4941 Val = MStore->getValue(); 4942 Mask = MStore->getMask(); 4943 } 4944 4945 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4946 4947 MVT VT = Val.getSimpleValueType(); 4948 MVT XLenVT = Subtarget.getXLenVT(); 4949 4950 MVT ContainerVT = VT; 4951 if (VT.isFixedLengthVector()) { 4952 ContainerVT = getContainerForFixedLengthVector(VT); 4953 4954 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4955 if (!IsUnmasked) { 4956 MVT MaskVT = 4957 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4958 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4959 } 4960 } 4961 4962 if (!VL) 4963 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4964 4965 unsigned IntID = 4966 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 4967 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 4968 Ops.push_back(Val); 4969 Ops.push_back(BasePtr); 4970 if (!IsUnmasked) 4971 Ops.push_back(Mask); 4972 Ops.push_back(VL); 4973 4974 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 4975 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 4976 } 4977 4978 SDValue 4979 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 4980 SelectionDAG &DAG) const { 4981 MVT InVT = Op.getOperand(0).getSimpleValueType(); 4982 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 4983 4984 MVT VT = Op.getSimpleValueType(); 4985 4986 SDValue Op1 = 4987 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4988 SDValue Op2 = 4989 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 4990 4991 SDLoc DL(Op); 4992 SDValue VL = 4993 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4994 4995 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4996 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4997 4998 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 4999 Op.getOperand(2), Mask, VL); 5000 5001 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5002 } 5003 5004 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5005 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5006 MVT VT = Op.getSimpleValueType(); 5007 5008 if (VT.getVectorElementType() == MVT::i1) 5009 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5010 5011 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5012 } 5013 5014 SDValue 5015 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5016 SelectionDAG &DAG) const { 5017 unsigned Opc; 5018 switch (Op.getOpcode()) { 5019 default: llvm_unreachable("Unexpected opcode!"); 5020 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5021 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5022 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5023 } 5024 5025 return lowerToScalableOp(Op, DAG, Opc); 5026 } 5027 5028 // Lower vector ABS to smax(X, sub(0, X)). 5029 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5030 SDLoc DL(Op); 5031 MVT VT = Op.getSimpleValueType(); 5032 SDValue X = Op.getOperand(0); 5033 5034 assert(VT.isFixedLengthVector() && "Unexpected type"); 5035 5036 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5037 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5038 5039 SDValue Mask, VL; 5040 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5041 5042 SDValue SplatZero = 5043 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5044 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5045 SDValue NegX = 5046 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5047 SDValue Max = 5048 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5049 5050 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5051 } 5052 5053 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5054 SDValue Op, SelectionDAG &DAG) const { 5055 SDLoc DL(Op); 5056 MVT VT = Op.getSimpleValueType(); 5057 SDValue Mag = Op.getOperand(0); 5058 SDValue Sign = Op.getOperand(1); 5059 assert(Mag.getValueType() == Sign.getValueType() && 5060 "Can only handle COPYSIGN with matching types."); 5061 5062 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5063 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5064 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5065 5066 SDValue Mask, VL; 5067 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5068 5069 SDValue CopySign = 5070 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5071 5072 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5073 } 5074 5075 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5076 SDValue Op, SelectionDAG &DAG) const { 5077 MVT VT = Op.getSimpleValueType(); 5078 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5079 5080 MVT I1ContainerVT = 5081 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5082 5083 SDValue CC = 5084 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5085 SDValue Op1 = 5086 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5087 SDValue Op2 = 5088 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5089 5090 SDLoc DL(Op); 5091 SDValue Mask, VL; 5092 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5093 5094 SDValue Select = 5095 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5096 5097 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5098 } 5099 5100 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5101 unsigned NewOpc, 5102 bool HasMask) const { 5103 MVT VT = Op.getSimpleValueType(); 5104 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5105 5106 // Create list of operands by converting existing ones to scalable types. 5107 SmallVector<SDValue, 6> Ops; 5108 for (const SDValue &V : Op->op_values()) { 5109 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5110 5111 // Pass through non-vector operands. 5112 if (!V.getValueType().isVector()) { 5113 Ops.push_back(V); 5114 continue; 5115 } 5116 5117 // "cast" fixed length vector to a scalable vector. 5118 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5119 "Only fixed length vectors are supported!"); 5120 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5121 } 5122 5123 SDLoc DL(Op); 5124 SDValue Mask, VL; 5125 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5126 if (HasMask) 5127 Ops.push_back(Mask); 5128 Ops.push_back(VL); 5129 5130 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5131 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5132 } 5133 5134 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5135 // * Operands of each node are assumed to be in the same order. 5136 // * The EVL operand is promoted from i32 to i64 on RV64. 5137 // * Fixed-length vectors are converted to their scalable-vector container 5138 // types. 5139 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5140 unsigned RISCVISDOpc) const { 5141 SDLoc DL(Op); 5142 MVT VT = Op.getSimpleValueType(); 5143 SmallVector<SDValue, 4> Ops; 5144 5145 for (const auto &OpIdx : enumerate(Op->ops())) { 5146 SDValue V = OpIdx.value(); 5147 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5148 // Pass through operands which aren't fixed-length vectors. 5149 if (!V.getValueType().isFixedLengthVector()) { 5150 Ops.push_back(V); 5151 continue; 5152 } 5153 // "cast" fixed length vector to a scalable vector. 5154 MVT OpVT = V.getSimpleValueType(); 5155 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5156 assert(useRVVForFixedLengthVectorVT(OpVT) && 5157 "Only fixed length vectors are supported!"); 5158 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5159 } 5160 5161 if (!VT.isFixedLengthVector()) 5162 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5163 5164 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5165 5166 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5167 5168 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5169 } 5170 5171 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5172 // matched to a RVV indexed load. The RVV indexed load instructions only 5173 // support the "unsigned unscaled" addressing mode; indices are implicitly 5174 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5175 // signed or scaled indexing is extended to the XLEN value type and scaled 5176 // accordingly. 5177 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5178 SelectionDAG &DAG) const { 5179 SDLoc DL(Op); 5180 MVT VT = Op.getSimpleValueType(); 5181 5182 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5183 EVT MemVT = MemSD->getMemoryVT(); 5184 MachineMemOperand *MMO = MemSD->getMemOperand(); 5185 SDValue Chain = MemSD->getChain(); 5186 SDValue BasePtr = MemSD->getBasePtr(); 5187 5188 ISD::LoadExtType LoadExtType; 5189 SDValue Index, Mask, PassThru, VL; 5190 5191 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5192 Index = VPGN->getIndex(); 5193 Mask = VPGN->getMask(); 5194 PassThru = DAG.getUNDEF(VT); 5195 VL = VPGN->getVectorLength(); 5196 // VP doesn't support extending loads. 5197 LoadExtType = ISD::NON_EXTLOAD; 5198 } else { 5199 // Else it must be a MGATHER. 5200 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5201 Index = MGN->getIndex(); 5202 Mask = MGN->getMask(); 5203 PassThru = MGN->getPassThru(); 5204 LoadExtType = MGN->getExtensionType(); 5205 } 5206 5207 MVT IndexVT = Index.getSimpleValueType(); 5208 MVT XLenVT = Subtarget.getXLenVT(); 5209 5210 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5211 "Unexpected VTs!"); 5212 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5213 // Targets have to explicitly opt-in for extending vector loads. 5214 assert(LoadExtType == ISD::NON_EXTLOAD && 5215 "Unexpected extending MGATHER/VP_GATHER"); 5216 (void)LoadExtType; 5217 5218 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5219 // the selection of the masked intrinsics doesn't do this for us. 5220 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5221 5222 MVT ContainerVT = VT; 5223 if (VT.isFixedLengthVector()) { 5224 // We need to use the larger of the result and index type to determine the 5225 // scalable type to use so we don't increase LMUL for any operand/result. 5226 if (VT.bitsGE(IndexVT)) { 5227 ContainerVT = getContainerForFixedLengthVector(VT); 5228 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5229 ContainerVT.getVectorElementCount()); 5230 } else { 5231 IndexVT = getContainerForFixedLengthVector(IndexVT); 5232 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5233 IndexVT.getVectorElementCount()); 5234 } 5235 5236 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5237 5238 if (!IsUnmasked) { 5239 MVT MaskVT = 5240 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5241 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5242 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5243 } 5244 } 5245 5246 if (!VL) 5247 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5248 5249 unsigned IntID = 5250 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5251 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5252 if (!IsUnmasked) 5253 Ops.push_back(PassThru); 5254 Ops.push_back(BasePtr); 5255 Ops.push_back(Index); 5256 if (!IsUnmasked) 5257 Ops.push_back(Mask); 5258 Ops.push_back(VL); 5259 if (!IsUnmasked) 5260 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5261 5262 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5263 SDValue Result = 5264 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5265 Chain = Result.getValue(1); 5266 5267 if (VT.isFixedLengthVector()) 5268 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5269 5270 return DAG.getMergeValues({Result, Chain}, DL); 5271 } 5272 5273 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5274 // matched to a RVV indexed store. The RVV indexed store instructions only 5275 // support the "unsigned unscaled" addressing mode; indices are implicitly 5276 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5277 // signed or scaled indexing is extended to the XLEN value type and scaled 5278 // accordingly. 5279 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5280 SelectionDAG &DAG) const { 5281 SDLoc DL(Op); 5282 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5283 EVT MemVT = MemSD->getMemoryVT(); 5284 MachineMemOperand *MMO = MemSD->getMemOperand(); 5285 SDValue Chain = MemSD->getChain(); 5286 SDValue BasePtr = MemSD->getBasePtr(); 5287 5288 bool IsTruncatingStore = false; 5289 SDValue Index, Mask, Val, VL; 5290 5291 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5292 Index = VPSN->getIndex(); 5293 Mask = VPSN->getMask(); 5294 Val = VPSN->getValue(); 5295 VL = VPSN->getVectorLength(); 5296 // VP doesn't support truncating stores. 5297 IsTruncatingStore = false; 5298 } else { 5299 // Else it must be a MSCATTER. 5300 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5301 Index = MSN->getIndex(); 5302 Mask = MSN->getMask(); 5303 Val = MSN->getValue(); 5304 IsTruncatingStore = MSN->isTruncatingStore(); 5305 } 5306 5307 MVT VT = Val.getSimpleValueType(); 5308 MVT IndexVT = Index.getSimpleValueType(); 5309 MVT XLenVT = Subtarget.getXLenVT(); 5310 5311 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5312 "Unexpected VTs!"); 5313 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5314 // Targets have to explicitly opt-in for extending vector loads and 5315 // truncating vector stores. 5316 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5317 (void)IsTruncatingStore; 5318 5319 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5320 // the selection of the masked intrinsics doesn't do this for us. 5321 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5322 5323 MVT ContainerVT = VT; 5324 if (VT.isFixedLengthVector()) { 5325 // We need to use the larger of the value and index type to determine the 5326 // scalable type to use so we don't increase LMUL for any operand/result. 5327 if (VT.bitsGE(IndexVT)) { 5328 ContainerVT = getContainerForFixedLengthVector(VT); 5329 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5330 ContainerVT.getVectorElementCount()); 5331 } else { 5332 IndexVT = getContainerForFixedLengthVector(IndexVT); 5333 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5334 IndexVT.getVectorElementCount()); 5335 } 5336 5337 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5338 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5339 5340 if (!IsUnmasked) { 5341 MVT MaskVT = 5342 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5343 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5344 } 5345 } 5346 5347 if (!VL) 5348 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5349 5350 unsigned IntID = 5351 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5352 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5353 Ops.push_back(Val); 5354 Ops.push_back(BasePtr); 5355 Ops.push_back(Index); 5356 if (!IsUnmasked) 5357 Ops.push_back(Mask); 5358 Ops.push_back(VL); 5359 5360 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5361 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5362 } 5363 5364 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5365 SelectionDAG &DAG) const { 5366 const MVT XLenVT = Subtarget.getXLenVT(); 5367 SDLoc DL(Op); 5368 SDValue Chain = Op->getOperand(0); 5369 SDValue SysRegNo = DAG.getTargetConstant( 5370 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5371 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5372 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5373 5374 // Encoding used for rounding mode in RISCV differs from that used in 5375 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5376 // table, which consists of a sequence of 4-bit fields, each representing 5377 // corresponding FLT_ROUNDS mode. 5378 static const int Table = 5379 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5380 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5381 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5382 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5383 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5384 5385 SDValue Shift = 5386 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5387 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5388 DAG.getConstant(Table, DL, XLenVT), Shift); 5389 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5390 DAG.getConstant(7, DL, XLenVT)); 5391 5392 return DAG.getMergeValues({Masked, Chain}, DL); 5393 } 5394 5395 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5396 SelectionDAG &DAG) const { 5397 const MVT XLenVT = Subtarget.getXLenVT(); 5398 SDLoc DL(Op); 5399 SDValue Chain = Op->getOperand(0); 5400 SDValue RMValue = Op->getOperand(1); 5401 SDValue SysRegNo = DAG.getTargetConstant( 5402 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5403 5404 // Encoding used for rounding mode in RISCV differs from that used in 5405 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5406 // a table, which consists of a sequence of 4-bit fields, each representing 5407 // corresponding RISCV mode. 5408 static const unsigned Table = 5409 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5410 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5411 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5412 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5413 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5414 5415 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5416 DAG.getConstant(2, DL, XLenVT)); 5417 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5418 DAG.getConstant(Table, DL, XLenVT), Shift); 5419 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5420 DAG.getConstant(0x7, DL, XLenVT)); 5421 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5422 RMValue); 5423 } 5424 5425 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5426 // form of the given Opcode. 5427 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5428 switch (Opcode) { 5429 default: 5430 llvm_unreachable("Unexpected opcode"); 5431 case ISD::SHL: 5432 return RISCVISD::SLLW; 5433 case ISD::SRA: 5434 return RISCVISD::SRAW; 5435 case ISD::SRL: 5436 return RISCVISD::SRLW; 5437 case ISD::SDIV: 5438 return RISCVISD::DIVW; 5439 case ISD::UDIV: 5440 return RISCVISD::DIVUW; 5441 case ISD::UREM: 5442 return RISCVISD::REMUW; 5443 case ISD::ROTL: 5444 return RISCVISD::ROLW; 5445 case ISD::ROTR: 5446 return RISCVISD::RORW; 5447 case RISCVISD::GREV: 5448 return RISCVISD::GREVW; 5449 case RISCVISD::GORC: 5450 return RISCVISD::GORCW; 5451 } 5452 } 5453 5454 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5455 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5456 // otherwise be promoted to i64, making it difficult to select the 5457 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5458 // type i8/i16/i32 is lost. 5459 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5460 unsigned ExtOpc = ISD::ANY_EXTEND) { 5461 SDLoc DL(N); 5462 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5463 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5464 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5465 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5466 // ReplaceNodeResults requires we maintain the same type for the return value. 5467 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5468 } 5469 5470 // Converts the given 32-bit operation to a i64 operation with signed extension 5471 // semantic to reduce the signed extension instructions. 5472 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5473 SDLoc DL(N); 5474 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5475 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5476 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5477 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5478 DAG.getValueType(MVT::i32)); 5479 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5480 } 5481 5482 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5483 SmallVectorImpl<SDValue> &Results, 5484 SelectionDAG &DAG) const { 5485 SDLoc DL(N); 5486 switch (N->getOpcode()) { 5487 default: 5488 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5489 case ISD::STRICT_FP_TO_SINT: 5490 case ISD::STRICT_FP_TO_UINT: 5491 case ISD::FP_TO_SINT: 5492 case ISD::FP_TO_UINT: { 5493 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5494 "Unexpected custom legalisation"); 5495 bool IsStrict = N->isStrictFPOpcode(); 5496 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5497 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5498 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5499 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5500 TargetLowering::TypeSoftenFloat) { 5501 // FIXME: Support strict FP. 5502 if (IsStrict) 5503 return; 5504 if (!isTypeLegal(Op0.getValueType())) 5505 return; 5506 unsigned Opc = 5507 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5508 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5509 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5510 return; 5511 } 5512 // If the FP type needs to be softened, emit a library call using the 'si' 5513 // version. If we left it to default legalization we'd end up with 'di'. If 5514 // the FP type doesn't need to be softened just let generic type 5515 // legalization promote the result type. 5516 RTLIB::Libcall LC; 5517 if (IsSigned) 5518 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5519 else 5520 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5521 MakeLibCallOptions CallOptions; 5522 EVT OpVT = Op0.getValueType(); 5523 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5524 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5525 SDValue Result; 5526 std::tie(Result, Chain) = 5527 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5528 Results.push_back(Result); 5529 if (IsStrict) 5530 Results.push_back(Chain); 5531 break; 5532 } 5533 case ISD::READCYCLECOUNTER: { 5534 assert(!Subtarget.is64Bit() && 5535 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5536 5537 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5538 SDValue RCW = 5539 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5540 5541 Results.push_back( 5542 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5543 Results.push_back(RCW.getValue(2)); 5544 break; 5545 } 5546 case ISD::MUL: { 5547 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5548 unsigned XLen = Subtarget.getXLen(); 5549 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5550 if (Size > XLen) { 5551 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5552 SDValue LHS = N->getOperand(0); 5553 SDValue RHS = N->getOperand(1); 5554 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5555 5556 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5557 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5558 // We need exactly one side to be unsigned. 5559 if (LHSIsU == RHSIsU) 5560 return; 5561 5562 auto MakeMULPair = [&](SDValue S, SDValue U) { 5563 MVT XLenVT = Subtarget.getXLenVT(); 5564 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5565 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5566 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5567 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5568 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5569 }; 5570 5571 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5572 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5573 5574 // The other operand should be signed, but still prefer MULH when 5575 // possible. 5576 if (RHSIsU && LHSIsS && !RHSIsS) 5577 Results.push_back(MakeMULPair(LHS, RHS)); 5578 else if (LHSIsU && RHSIsS && !LHSIsS) 5579 Results.push_back(MakeMULPair(RHS, LHS)); 5580 5581 return; 5582 } 5583 LLVM_FALLTHROUGH; 5584 } 5585 case ISD::ADD: 5586 case ISD::SUB: 5587 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5588 "Unexpected custom legalisation"); 5589 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5590 break; 5591 case ISD::SHL: 5592 case ISD::SRA: 5593 case ISD::SRL: 5594 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5595 "Unexpected custom legalisation"); 5596 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5597 Results.push_back(customLegalizeToWOp(N, DAG)); 5598 break; 5599 } 5600 5601 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5602 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5603 // shift amount. 5604 if (N->getOpcode() == ISD::SHL) { 5605 SDLoc DL(N); 5606 SDValue NewOp0 = 5607 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5608 SDValue NewOp1 = 5609 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5610 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5611 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5612 DAG.getValueType(MVT::i32)); 5613 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5614 } 5615 5616 break; 5617 case ISD::ROTL: 5618 case ISD::ROTR: 5619 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5620 "Unexpected custom legalisation"); 5621 Results.push_back(customLegalizeToWOp(N, DAG)); 5622 break; 5623 case ISD::CTTZ: 5624 case ISD::CTTZ_ZERO_UNDEF: 5625 case ISD::CTLZ: 5626 case ISD::CTLZ_ZERO_UNDEF: { 5627 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5628 "Unexpected custom legalisation"); 5629 5630 SDValue NewOp0 = 5631 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5632 bool IsCTZ = 5633 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5634 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5635 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5636 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5637 return; 5638 } 5639 case ISD::SDIV: 5640 case ISD::UDIV: 5641 case ISD::UREM: { 5642 MVT VT = N->getSimpleValueType(0); 5643 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5644 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5645 "Unexpected custom legalisation"); 5646 // Don't promote division/remainder by constant since we should expand those 5647 // to multiply by magic constant. 5648 // FIXME: What if the expansion is disabled for minsize. 5649 if (N->getOperand(1).getOpcode() == ISD::Constant) 5650 return; 5651 5652 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5653 // the upper 32 bits. For other types we need to sign or zero extend 5654 // based on the opcode. 5655 unsigned ExtOpc = ISD::ANY_EXTEND; 5656 if (VT != MVT::i32) 5657 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5658 : ISD::ZERO_EXTEND; 5659 5660 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5661 break; 5662 } 5663 case ISD::UADDO: 5664 case ISD::USUBO: { 5665 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5666 "Unexpected custom legalisation"); 5667 bool IsAdd = N->getOpcode() == ISD::UADDO; 5668 // Create an ADDW or SUBW. 5669 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5670 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5671 SDValue Res = 5672 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5673 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5674 DAG.getValueType(MVT::i32)); 5675 5676 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5677 // Since the inputs are sign extended from i32, this is equivalent to 5678 // comparing the lower 32 bits. 5679 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5680 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5681 IsAdd ? ISD::SETULT : ISD::SETUGT); 5682 5683 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5684 Results.push_back(Overflow); 5685 return; 5686 } 5687 case ISD::UADDSAT: 5688 case ISD::USUBSAT: { 5689 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5690 "Unexpected custom legalisation"); 5691 if (Subtarget.hasStdExtZbb()) { 5692 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5693 // sign extend allows overflow of the lower 32 bits to be detected on 5694 // the promoted size. 5695 SDValue LHS = 5696 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5697 SDValue RHS = 5698 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5699 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5700 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5701 return; 5702 } 5703 5704 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5705 // promotion for UADDO/USUBO. 5706 Results.push_back(expandAddSubSat(N, DAG)); 5707 return; 5708 } 5709 case ISD::BITCAST: { 5710 EVT VT = N->getValueType(0); 5711 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5712 SDValue Op0 = N->getOperand(0); 5713 EVT Op0VT = Op0.getValueType(); 5714 MVT XLenVT = Subtarget.getXLenVT(); 5715 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5716 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5717 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5718 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 5719 Subtarget.hasStdExtF()) { 5720 SDValue FPConv = 5721 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 5722 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 5723 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 5724 isTypeLegal(Op0VT)) { 5725 // Custom-legalize bitcasts from fixed-length vector types to illegal 5726 // scalar types in order to improve codegen. Bitcast the vector to a 5727 // one-element vector type whose element type is the same as the result 5728 // type, and extract the first element. 5729 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 5730 if (isTypeLegal(BVT)) { 5731 SDValue BVec = DAG.getBitcast(BVT, Op0); 5732 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 5733 DAG.getConstant(0, DL, XLenVT))); 5734 } 5735 } 5736 break; 5737 } 5738 case RISCVISD::GREV: 5739 case RISCVISD::GORC: { 5740 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5741 "Unexpected custom legalisation"); 5742 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5743 // This is similar to customLegalizeToWOp, except that we pass the second 5744 // operand (a TargetConstant) straight through: it is already of type 5745 // XLenVT. 5746 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5747 SDValue NewOp0 = 5748 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5749 SDValue NewOp1 = 5750 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5751 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5752 // ReplaceNodeResults requires we maintain the same type for the return 5753 // value. 5754 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5755 break; 5756 } 5757 case RISCVISD::SHFL: { 5758 // There is no SHFLIW instruction, but we can just promote the operation. 5759 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5760 "Unexpected custom legalisation"); 5761 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5762 SDValue NewOp0 = 5763 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5764 SDValue NewOp1 = 5765 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5766 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 5767 // ReplaceNodeResults requires we maintain the same type for the return 5768 // value. 5769 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5770 break; 5771 } 5772 case ISD::BSWAP: 5773 case ISD::BITREVERSE: { 5774 MVT VT = N->getSimpleValueType(0); 5775 MVT XLenVT = Subtarget.getXLenVT(); 5776 assert((VT == MVT::i8 || VT == MVT::i16 || 5777 (VT == MVT::i32 && Subtarget.is64Bit())) && 5778 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 5779 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 5780 unsigned Imm = VT.getSizeInBits() - 1; 5781 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 5782 if (N->getOpcode() == ISD::BSWAP) 5783 Imm &= ~0x7U; 5784 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 5785 SDValue GREVI = 5786 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 5787 // ReplaceNodeResults requires we maintain the same type for the return 5788 // value. 5789 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 5790 break; 5791 } 5792 case ISD::FSHL: 5793 case ISD::FSHR: { 5794 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5795 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 5796 SDValue NewOp0 = 5797 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5798 SDValue NewOp1 = 5799 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5800 SDValue NewOp2 = 5801 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5802 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 5803 // Mask the shift amount to 5 bits. 5804 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5805 DAG.getConstant(0x1f, DL, MVT::i64)); 5806 unsigned Opc = 5807 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 5808 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 5809 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 5810 break; 5811 } 5812 case ISD::EXTRACT_VECTOR_ELT: { 5813 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 5814 // type is illegal (currently only vXi64 RV32). 5815 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 5816 // transferred to the destination register. We issue two of these from the 5817 // upper- and lower- halves of the SEW-bit vector element, slid down to the 5818 // first element. 5819 SDValue Vec = N->getOperand(0); 5820 SDValue Idx = N->getOperand(1); 5821 5822 // The vector type hasn't been legalized yet so we can't issue target 5823 // specific nodes if it needs legalization. 5824 // FIXME: We would manually legalize if it's important. 5825 if (!isTypeLegal(Vec.getValueType())) 5826 return; 5827 5828 MVT VecVT = Vec.getSimpleValueType(); 5829 5830 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 5831 VecVT.getVectorElementType() == MVT::i64 && 5832 "Unexpected EXTRACT_VECTOR_ELT legalization"); 5833 5834 // If this is a fixed vector, we need to convert it to a scalable vector. 5835 MVT ContainerVT = VecVT; 5836 if (VecVT.isFixedLengthVector()) { 5837 ContainerVT = getContainerForFixedLengthVector(VecVT); 5838 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5839 } 5840 5841 MVT XLenVT = Subtarget.getXLenVT(); 5842 5843 // Use a VL of 1 to avoid processing more elements than we need. 5844 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5845 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5846 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5847 5848 // Unless the index is known to be 0, we must slide the vector down to get 5849 // the desired element into index 0. 5850 if (!isNullConstant(Idx)) { 5851 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5852 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5853 } 5854 5855 // Extract the lower XLEN bits of the correct vector element. 5856 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5857 5858 // To extract the upper XLEN bits of the vector element, shift the first 5859 // element right by 32 bits and re-extract the lower XLEN bits. 5860 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5861 DAG.getConstant(32, DL, XLenVT), VL); 5862 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 5863 ThirtyTwoV, Mask, VL); 5864 5865 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5866 5867 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5868 break; 5869 } 5870 case ISD::INTRINSIC_WO_CHAIN: { 5871 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5872 switch (IntNo) { 5873 default: 5874 llvm_unreachable( 5875 "Don't know how to custom type legalize this intrinsic!"); 5876 case Intrinsic::riscv_orc_b: { 5877 // Lower to the GORCI encoding for orc.b with the operand extended. 5878 SDValue NewOp = 5879 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5880 // If Zbp is enabled, use GORCIW which will sign extend the result. 5881 unsigned Opc = 5882 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 5883 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 5884 DAG.getConstant(7, DL, MVT::i64)); 5885 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5886 return; 5887 } 5888 case Intrinsic::riscv_grev: 5889 case Intrinsic::riscv_gorc: { 5890 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5891 "Unexpected custom legalisation"); 5892 SDValue NewOp1 = 5893 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5894 SDValue NewOp2 = 5895 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5896 unsigned Opc = 5897 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 5898 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5899 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5900 break; 5901 } 5902 case Intrinsic::riscv_shfl: 5903 case Intrinsic::riscv_unshfl: { 5904 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5905 "Unexpected custom legalisation"); 5906 SDValue NewOp1 = 5907 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5908 SDValue NewOp2 = 5909 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5910 unsigned Opc = 5911 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 5912 if (isa<ConstantSDNode>(N->getOperand(2))) { 5913 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5914 DAG.getConstant(0xf, DL, MVT::i64)); 5915 Opc = 5916 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 5917 } 5918 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5919 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5920 break; 5921 } 5922 case Intrinsic::riscv_bcompress: 5923 case Intrinsic::riscv_bdecompress: { 5924 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5925 "Unexpected custom legalisation"); 5926 SDValue NewOp1 = 5927 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5928 SDValue NewOp2 = 5929 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5930 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 5931 ? RISCVISD::BCOMPRESSW 5932 : RISCVISD::BDECOMPRESSW; 5933 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5934 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5935 break; 5936 } 5937 case Intrinsic::riscv_vmv_x_s: { 5938 EVT VT = N->getValueType(0); 5939 MVT XLenVT = Subtarget.getXLenVT(); 5940 if (VT.bitsLT(XLenVT)) { 5941 // Simple case just extract using vmv.x.s and truncate. 5942 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 5943 Subtarget.getXLenVT(), N->getOperand(1)); 5944 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 5945 return; 5946 } 5947 5948 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 5949 "Unexpected custom legalization"); 5950 5951 // We need to do the move in two steps. 5952 SDValue Vec = N->getOperand(1); 5953 MVT VecVT = Vec.getSimpleValueType(); 5954 5955 // First extract the lower XLEN bits of the element. 5956 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5957 5958 // To extract the upper XLEN bits of the vector element, shift the first 5959 // element right by 32 bits and re-extract the lower XLEN bits. 5960 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5961 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5962 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5963 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 5964 DAG.getConstant(32, DL, XLenVT), VL); 5965 SDValue LShr32 = 5966 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 5967 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5968 5969 Results.push_back( 5970 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5971 break; 5972 } 5973 } 5974 break; 5975 } 5976 case ISD::VECREDUCE_ADD: 5977 case ISD::VECREDUCE_AND: 5978 case ISD::VECREDUCE_OR: 5979 case ISD::VECREDUCE_XOR: 5980 case ISD::VECREDUCE_SMAX: 5981 case ISD::VECREDUCE_UMAX: 5982 case ISD::VECREDUCE_SMIN: 5983 case ISD::VECREDUCE_UMIN: 5984 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 5985 Results.push_back(V); 5986 break; 5987 case ISD::VP_REDUCE_ADD: 5988 case ISD::VP_REDUCE_AND: 5989 case ISD::VP_REDUCE_OR: 5990 case ISD::VP_REDUCE_XOR: 5991 case ISD::VP_REDUCE_SMAX: 5992 case ISD::VP_REDUCE_UMAX: 5993 case ISD::VP_REDUCE_SMIN: 5994 case ISD::VP_REDUCE_UMIN: 5995 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 5996 Results.push_back(V); 5997 break; 5998 case ISD::FLT_ROUNDS_: { 5999 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6000 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6001 Results.push_back(Res.getValue(0)); 6002 Results.push_back(Res.getValue(1)); 6003 break; 6004 } 6005 } 6006 } 6007 6008 // A structure to hold one of the bit-manipulation patterns below. Together, a 6009 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6010 // (or (and (shl x, 1), 0xAAAAAAAA), 6011 // (and (srl x, 1), 0x55555555)) 6012 struct RISCVBitmanipPat { 6013 SDValue Op; 6014 unsigned ShAmt; 6015 bool IsSHL; 6016 6017 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6018 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6019 } 6020 }; 6021 6022 // Matches patterns of the form 6023 // (and (shl x, C2), (C1 << C2)) 6024 // (and (srl x, C2), C1) 6025 // (shl (and x, C1), C2) 6026 // (srl (and x, (C1 << C2)), C2) 6027 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6028 // The expected masks for each shift amount are specified in BitmanipMasks where 6029 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6030 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6031 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6032 // XLen is 64. 6033 static Optional<RISCVBitmanipPat> 6034 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6035 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6036 "Unexpected number of masks"); 6037 Optional<uint64_t> Mask; 6038 // Optionally consume a mask around the shift operation. 6039 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6040 Mask = Op.getConstantOperandVal(1); 6041 Op = Op.getOperand(0); 6042 } 6043 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6044 return None; 6045 bool IsSHL = Op.getOpcode() == ISD::SHL; 6046 6047 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6048 return None; 6049 uint64_t ShAmt = Op.getConstantOperandVal(1); 6050 6051 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6052 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6053 return None; 6054 // If we don't have enough masks for 64 bit, then we must be trying to 6055 // match SHFL so we're only allowed to shift 1/4 of the width. 6056 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6057 return None; 6058 6059 SDValue Src = Op.getOperand(0); 6060 6061 // The expected mask is shifted left when the AND is found around SHL 6062 // patterns. 6063 // ((x >> 1) & 0x55555555) 6064 // ((x << 1) & 0xAAAAAAAA) 6065 bool SHLExpMask = IsSHL; 6066 6067 if (!Mask) { 6068 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6069 // the mask is all ones: consume that now. 6070 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6071 Mask = Src.getConstantOperandVal(1); 6072 Src = Src.getOperand(0); 6073 // The expected mask is now in fact shifted left for SRL, so reverse the 6074 // decision. 6075 // ((x & 0xAAAAAAAA) >> 1) 6076 // ((x & 0x55555555) << 1) 6077 SHLExpMask = !SHLExpMask; 6078 } else { 6079 // Use a default shifted mask of all-ones if there's no AND, truncated 6080 // down to the expected width. This simplifies the logic later on. 6081 Mask = maskTrailingOnes<uint64_t>(Width); 6082 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6083 } 6084 } 6085 6086 unsigned MaskIdx = Log2_32(ShAmt); 6087 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6088 6089 if (SHLExpMask) 6090 ExpMask <<= ShAmt; 6091 6092 if (Mask != ExpMask) 6093 return None; 6094 6095 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6096 } 6097 6098 // Matches any of the following bit-manipulation patterns: 6099 // (and (shl x, 1), (0x55555555 << 1)) 6100 // (and (srl x, 1), 0x55555555) 6101 // (shl (and x, 0x55555555), 1) 6102 // (srl (and x, (0x55555555 << 1)), 1) 6103 // where the shift amount and mask may vary thus: 6104 // [1] = 0x55555555 / 0xAAAAAAAA 6105 // [2] = 0x33333333 / 0xCCCCCCCC 6106 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6107 // [8] = 0x00FF00FF / 0xFF00FF00 6108 // [16] = 0x0000FFFF / 0xFFFFFFFF 6109 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6110 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6111 // These are the unshifted masks which we use to match bit-manipulation 6112 // patterns. They may be shifted left in certain circumstances. 6113 static const uint64_t BitmanipMasks[] = { 6114 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6115 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6116 6117 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6118 } 6119 6120 // Match the following pattern as a GREVI(W) operation 6121 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6122 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6123 const RISCVSubtarget &Subtarget) { 6124 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6125 EVT VT = Op.getValueType(); 6126 6127 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6128 auto LHS = matchGREVIPat(Op.getOperand(0)); 6129 auto RHS = matchGREVIPat(Op.getOperand(1)); 6130 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6131 SDLoc DL(Op); 6132 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6133 DAG.getConstant(LHS->ShAmt, DL, VT)); 6134 } 6135 } 6136 return SDValue(); 6137 } 6138 6139 // Matches any the following pattern as a GORCI(W) operation 6140 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6141 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6142 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6143 // Note that with the variant of 3., 6144 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6145 // the inner pattern will first be matched as GREVI and then the outer 6146 // pattern will be matched to GORC via the first rule above. 6147 // 4. (or (rotl/rotr x, bitwidth/2), x) 6148 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6149 const RISCVSubtarget &Subtarget) { 6150 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6151 EVT VT = Op.getValueType(); 6152 6153 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6154 SDLoc DL(Op); 6155 SDValue Op0 = Op.getOperand(0); 6156 SDValue Op1 = Op.getOperand(1); 6157 6158 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6159 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6160 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6161 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6162 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6163 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6164 if ((Reverse.getOpcode() == ISD::ROTL || 6165 Reverse.getOpcode() == ISD::ROTR) && 6166 Reverse.getOperand(0) == X && 6167 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6168 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6169 if (RotAmt == (VT.getSizeInBits() / 2)) 6170 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6171 DAG.getConstant(RotAmt, DL, VT)); 6172 } 6173 return SDValue(); 6174 }; 6175 6176 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6177 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6178 return V; 6179 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6180 return V; 6181 6182 // OR is commutable so canonicalize its OR operand to the left 6183 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6184 std::swap(Op0, Op1); 6185 if (Op0.getOpcode() != ISD::OR) 6186 return SDValue(); 6187 SDValue OrOp0 = Op0.getOperand(0); 6188 SDValue OrOp1 = Op0.getOperand(1); 6189 auto LHS = matchGREVIPat(OrOp0); 6190 // OR is commutable so swap the operands and try again: x might have been 6191 // on the left 6192 if (!LHS) { 6193 std::swap(OrOp0, OrOp1); 6194 LHS = matchGREVIPat(OrOp0); 6195 } 6196 auto RHS = matchGREVIPat(Op1); 6197 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6198 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6199 DAG.getConstant(LHS->ShAmt, DL, VT)); 6200 } 6201 } 6202 return SDValue(); 6203 } 6204 6205 // Matches any of the following bit-manipulation patterns: 6206 // (and (shl x, 1), (0x22222222 << 1)) 6207 // (and (srl x, 1), 0x22222222) 6208 // (shl (and x, 0x22222222), 1) 6209 // (srl (and x, (0x22222222 << 1)), 1) 6210 // where the shift amount and mask may vary thus: 6211 // [1] = 0x22222222 / 0x44444444 6212 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6213 // [4] = 0x00F000F0 / 0x0F000F00 6214 // [8] = 0x0000FF00 / 0x00FF0000 6215 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6216 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6217 // These are the unshifted masks which we use to match bit-manipulation 6218 // patterns. They may be shifted left in certain circumstances. 6219 static const uint64_t BitmanipMasks[] = { 6220 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6221 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6222 6223 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6224 } 6225 6226 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6227 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6228 const RISCVSubtarget &Subtarget) { 6229 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6230 EVT VT = Op.getValueType(); 6231 6232 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6233 return SDValue(); 6234 6235 SDValue Op0 = Op.getOperand(0); 6236 SDValue Op1 = Op.getOperand(1); 6237 6238 // Or is commutable so canonicalize the second OR to the LHS. 6239 if (Op0.getOpcode() != ISD::OR) 6240 std::swap(Op0, Op1); 6241 if (Op0.getOpcode() != ISD::OR) 6242 return SDValue(); 6243 6244 // We found an inner OR, so our operands are the operands of the inner OR 6245 // and the other operand of the outer OR. 6246 SDValue A = Op0.getOperand(0); 6247 SDValue B = Op0.getOperand(1); 6248 SDValue C = Op1; 6249 6250 auto Match1 = matchSHFLPat(A); 6251 auto Match2 = matchSHFLPat(B); 6252 6253 // If neither matched, we failed. 6254 if (!Match1 && !Match2) 6255 return SDValue(); 6256 6257 // We had at least one match. if one failed, try the remaining C operand. 6258 if (!Match1) { 6259 std::swap(A, C); 6260 Match1 = matchSHFLPat(A); 6261 if (!Match1) 6262 return SDValue(); 6263 } else if (!Match2) { 6264 std::swap(B, C); 6265 Match2 = matchSHFLPat(B); 6266 if (!Match2) 6267 return SDValue(); 6268 } 6269 assert(Match1 && Match2); 6270 6271 // Make sure our matches pair up. 6272 if (!Match1->formsPairWith(*Match2)) 6273 return SDValue(); 6274 6275 // All the remains is to make sure C is an AND with the same input, that masks 6276 // out the bits that are being shuffled. 6277 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6278 C.getOperand(0) != Match1->Op) 6279 return SDValue(); 6280 6281 uint64_t Mask = C.getConstantOperandVal(1); 6282 6283 static const uint64_t BitmanipMasks[] = { 6284 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6285 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6286 }; 6287 6288 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6289 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6290 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6291 6292 if (Mask != ExpMask) 6293 return SDValue(); 6294 6295 SDLoc DL(Op); 6296 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6297 DAG.getConstant(Match1->ShAmt, DL, VT)); 6298 } 6299 6300 // Optimize (add (shl x, c0), (shl y, c1)) -> 6301 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6302 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6303 const RISCVSubtarget &Subtarget) { 6304 // Perform this optimization only in the zba extension. 6305 if (!Subtarget.hasStdExtZba()) 6306 return SDValue(); 6307 6308 // Skip for vector types and larger types. 6309 EVT VT = N->getValueType(0); 6310 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6311 return SDValue(); 6312 6313 // The two operand nodes must be SHL and have no other use. 6314 SDValue N0 = N->getOperand(0); 6315 SDValue N1 = N->getOperand(1); 6316 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6317 !N0->hasOneUse() || !N1->hasOneUse()) 6318 return SDValue(); 6319 6320 // Check c0 and c1. 6321 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6322 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6323 if (!N0C || !N1C) 6324 return SDValue(); 6325 int64_t C0 = N0C->getSExtValue(); 6326 int64_t C1 = N1C->getSExtValue(); 6327 if (C0 <= 0 || C1 <= 0) 6328 return SDValue(); 6329 6330 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6331 int64_t Bits = std::min(C0, C1); 6332 int64_t Diff = std::abs(C0 - C1); 6333 if (Diff != 1 && Diff != 2 && Diff != 3) 6334 return SDValue(); 6335 6336 // Build nodes. 6337 SDLoc DL(N); 6338 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6339 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6340 SDValue NA0 = 6341 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6342 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6343 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6344 } 6345 6346 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6347 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6348 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6349 // not undo itself, but they are redundant. 6350 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6351 SDValue Src = N->getOperand(0); 6352 6353 if (Src.getOpcode() != N->getOpcode()) 6354 return SDValue(); 6355 6356 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6357 !isa<ConstantSDNode>(Src.getOperand(1))) 6358 return SDValue(); 6359 6360 unsigned ShAmt1 = N->getConstantOperandVal(1); 6361 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6362 Src = Src.getOperand(0); 6363 6364 unsigned CombinedShAmt; 6365 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6366 CombinedShAmt = ShAmt1 | ShAmt2; 6367 else 6368 CombinedShAmt = ShAmt1 ^ ShAmt2; 6369 6370 if (CombinedShAmt == 0) 6371 return Src; 6372 6373 SDLoc DL(N); 6374 return DAG.getNode( 6375 N->getOpcode(), DL, N->getValueType(0), Src, 6376 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6377 } 6378 6379 // Combine a constant select operand into its use: 6380 // 6381 // (and (select cond, -1, c), x) 6382 // -> (select cond, x, (and x, c)) [AllOnes=1] 6383 // (or (select cond, 0, c), x) 6384 // -> (select cond, x, (or x, c)) [AllOnes=0] 6385 // (xor (select cond, 0, c), x) 6386 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6387 // (add (select cond, 0, c), x) 6388 // -> (select cond, x, (add x, c)) [AllOnes=0] 6389 // (sub x, (select cond, 0, c)) 6390 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6391 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6392 SelectionDAG &DAG, bool AllOnes) { 6393 EVT VT = N->getValueType(0); 6394 6395 // Skip vectors. 6396 if (VT.isVector()) 6397 return SDValue(); 6398 6399 if ((Slct.getOpcode() != ISD::SELECT && 6400 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6401 !Slct.hasOneUse()) 6402 return SDValue(); 6403 6404 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6405 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6406 }; 6407 6408 bool SwapSelectOps; 6409 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6410 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6411 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6412 SDValue NonConstantVal; 6413 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6414 SwapSelectOps = false; 6415 NonConstantVal = FalseVal; 6416 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6417 SwapSelectOps = true; 6418 NonConstantVal = TrueVal; 6419 } else 6420 return SDValue(); 6421 6422 // Slct is now know to be the desired identity constant when CC is true. 6423 TrueVal = OtherOp; 6424 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6425 // Unless SwapSelectOps says the condition should be false. 6426 if (SwapSelectOps) 6427 std::swap(TrueVal, FalseVal); 6428 6429 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6430 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6431 {Slct.getOperand(0), Slct.getOperand(1), 6432 Slct.getOperand(2), TrueVal, FalseVal}); 6433 6434 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6435 {Slct.getOperand(0), TrueVal, FalseVal}); 6436 } 6437 6438 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6439 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6440 bool AllOnes) { 6441 SDValue N0 = N->getOperand(0); 6442 SDValue N1 = N->getOperand(1); 6443 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6444 return Result; 6445 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6446 return Result; 6447 return SDValue(); 6448 } 6449 6450 // Transform (add (mul x, c0), c1) -> 6451 // (add (mul (add x, c1/c0), c0), c1%c0). 6452 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6453 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6454 // to an infinite loop in DAGCombine if transformed. 6455 // Or transform (add (mul x, c0), c1) -> 6456 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6457 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6458 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6459 // lead to an infinite loop in DAGCombine if transformed. 6460 // Or transform (add (mul x, c0), c1) -> 6461 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6462 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6463 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6464 // lead to an infinite loop in DAGCombine if transformed. 6465 // Or transform (add (mul x, c0), c1) -> 6466 // (mul (add x, c1/c0), c0). 6467 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6468 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6469 const RISCVSubtarget &Subtarget) { 6470 // Skip for vector types and larger types. 6471 EVT VT = N->getValueType(0); 6472 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6473 return SDValue(); 6474 // The first operand node must be a MUL and has no other use. 6475 SDValue N0 = N->getOperand(0); 6476 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6477 return SDValue(); 6478 // Check if c0 and c1 match above conditions. 6479 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6480 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6481 if (!N0C || !N1C) 6482 return SDValue(); 6483 int64_t C0 = N0C->getSExtValue(); 6484 int64_t C1 = N1C->getSExtValue(); 6485 int64_t CA, CB; 6486 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6487 return SDValue(); 6488 // Search for proper CA (non-zero) and CB that both are simm12. 6489 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6490 !isInt<12>(C0 * (C1 / C0))) { 6491 CA = C1 / C0; 6492 CB = C1 % C0; 6493 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6494 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6495 CA = C1 / C0 + 1; 6496 CB = C1 % C0 - C0; 6497 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6498 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6499 CA = C1 / C0 - 1; 6500 CB = C1 % C0 + C0; 6501 } else 6502 return SDValue(); 6503 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6504 SDLoc DL(N); 6505 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6506 DAG.getConstant(CA, DL, VT)); 6507 SDValue New1 = 6508 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6509 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6510 } 6511 6512 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6513 const RISCVSubtarget &Subtarget) { 6514 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6515 return V; 6516 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6517 return V; 6518 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6519 // (select lhs, rhs, cc, x, (add x, y)) 6520 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6521 } 6522 6523 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6524 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6525 // (select lhs, rhs, cc, x, (sub x, y)) 6526 SDValue N0 = N->getOperand(0); 6527 SDValue N1 = N->getOperand(1); 6528 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6529 } 6530 6531 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6532 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6533 // (select lhs, rhs, cc, x, (and x, y)) 6534 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6535 } 6536 6537 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6538 const RISCVSubtarget &Subtarget) { 6539 if (Subtarget.hasStdExtZbp()) { 6540 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6541 return GREV; 6542 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6543 return GORC; 6544 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6545 return SHFL; 6546 } 6547 6548 // fold (or (select cond, 0, y), x) -> 6549 // (select cond, x, (or x, y)) 6550 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6551 } 6552 6553 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6554 // fold (xor (select cond, 0, y), x) -> 6555 // (select cond, x, (xor x, y)) 6556 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6557 } 6558 6559 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6560 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6561 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6562 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6563 // ADDW/SUBW/MULW. 6564 static SDValue performANY_EXTENDCombine(SDNode *N, 6565 TargetLowering::DAGCombinerInfo &DCI, 6566 const RISCVSubtarget &Subtarget) { 6567 if (!Subtarget.is64Bit()) 6568 return SDValue(); 6569 6570 SelectionDAG &DAG = DCI.DAG; 6571 6572 SDValue Src = N->getOperand(0); 6573 EVT VT = N->getValueType(0); 6574 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6575 return SDValue(); 6576 6577 // The opcode must be one that can implicitly sign_extend. 6578 // FIXME: Additional opcodes. 6579 switch (Src.getOpcode()) { 6580 default: 6581 return SDValue(); 6582 case ISD::MUL: 6583 if (!Subtarget.hasStdExtM()) 6584 return SDValue(); 6585 LLVM_FALLTHROUGH; 6586 case ISD::ADD: 6587 case ISD::SUB: 6588 break; 6589 } 6590 6591 // Only handle cases where the result is used by a CopyToReg. That likely 6592 // means the value is a liveout of the basic block. This helps prevent 6593 // infinite combine loops like PR51206. 6594 if (none_of(N->uses(), 6595 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6596 return SDValue(); 6597 6598 SmallVector<SDNode *, 4> SetCCs; 6599 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6600 UE = Src.getNode()->use_end(); 6601 UI != UE; ++UI) { 6602 SDNode *User = *UI; 6603 if (User == N) 6604 continue; 6605 if (UI.getUse().getResNo() != Src.getResNo()) 6606 continue; 6607 // All i32 setccs are legalized by sign extending operands. 6608 if (User->getOpcode() == ISD::SETCC) { 6609 SetCCs.push_back(User); 6610 continue; 6611 } 6612 // We don't know if we can extend this user. 6613 break; 6614 } 6615 6616 // If we don't have any SetCCs, this isn't worthwhile. 6617 if (SetCCs.empty()) 6618 return SDValue(); 6619 6620 SDLoc DL(N); 6621 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6622 DCI.CombineTo(N, SExt); 6623 6624 // Promote all the setccs. 6625 for (SDNode *SetCC : SetCCs) { 6626 SmallVector<SDValue, 4> Ops; 6627 6628 for (unsigned j = 0; j != 2; ++j) { 6629 SDValue SOp = SetCC->getOperand(j); 6630 if (SOp == Src) 6631 Ops.push_back(SExt); 6632 else 6633 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6634 } 6635 6636 Ops.push_back(SetCC->getOperand(2)); 6637 DCI.CombineTo(SetCC, 6638 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6639 } 6640 return SDValue(N, 0); 6641 } 6642 6643 // Try to form VWMUL or VWMULU. 6644 // FIXME: Support VWMULSU. 6645 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6646 SelectionDAG &DAG) { 6647 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6648 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6649 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6650 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6651 return SDValue(); 6652 6653 SDValue Mask = N->getOperand(2); 6654 SDValue VL = N->getOperand(3); 6655 6656 // Make sure the mask and VL match. 6657 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6658 return SDValue(); 6659 6660 MVT VT = N->getSimpleValueType(0); 6661 6662 // Determine the narrow size for a widening multiply. 6663 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 6664 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 6665 VT.getVectorElementCount()); 6666 6667 SDLoc DL(N); 6668 6669 // See if the other operand is the same opcode. 6670 if (Op0.getOpcode() == Op1.getOpcode()) { 6671 if (!Op1.hasOneUse()) 6672 return SDValue(); 6673 6674 // Make sure the mask and VL match. 6675 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 6676 return SDValue(); 6677 6678 Op1 = Op1.getOperand(0); 6679 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 6680 // The operand is a splat of a scalar. 6681 6682 // The VL must be the same. 6683 if (Op1.getOperand(1) != VL) 6684 return SDValue(); 6685 6686 // Get the scalar value. 6687 Op1 = Op1.getOperand(0); 6688 6689 // See if have enough sign bits or zero bits in the scalar to use a 6690 // widening multiply by splatting to smaller element size. 6691 unsigned EltBits = VT.getScalarSizeInBits(); 6692 unsigned ScalarBits = Op1.getValueSizeInBits(); 6693 // Make sure we're getting all element bits from the scalar register. 6694 // FIXME: Support implicit sign extension of vmv.v.x? 6695 if (ScalarBits < EltBits) 6696 return SDValue(); 6697 6698 if (IsSignExt) { 6699 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 6700 return SDValue(); 6701 } else { 6702 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 6703 if (!DAG.MaskedValueIsZero(Op1, Mask)) 6704 return SDValue(); 6705 } 6706 6707 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 6708 } else 6709 return SDValue(); 6710 6711 Op0 = Op0.getOperand(0); 6712 6713 // Re-introduce narrower extends if needed. 6714 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 6715 if (Op0.getValueType() != NarrowVT) 6716 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 6717 if (Op1.getValueType() != NarrowVT) 6718 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 6719 6720 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 6721 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 6722 } 6723 6724 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 6725 DAGCombinerInfo &DCI) const { 6726 SelectionDAG &DAG = DCI.DAG; 6727 6728 // Helper to call SimplifyDemandedBits on an operand of N where only some low 6729 // bits are demanded. N will be added to the Worklist if it was not deleted. 6730 // Caller should return SDValue(N, 0) if this returns true. 6731 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 6732 SDValue Op = N->getOperand(OpNo); 6733 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 6734 if (!SimplifyDemandedBits(Op, Mask, DCI)) 6735 return false; 6736 6737 if (N->getOpcode() != ISD::DELETED_NODE) 6738 DCI.AddToWorklist(N); 6739 return true; 6740 }; 6741 6742 switch (N->getOpcode()) { 6743 default: 6744 break; 6745 case RISCVISD::SplitF64: { 6746 SDValue Op0 = N->getOperand(0); 6747 // If the input to SplitF64 is just BuildPairF64 then the operation is 6748 // redundant. Instead, use BuildPairF64's operands directly. 6749 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 6750 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 6751 6752 SDLoc DL(N); 6753 6754 // It's cheaper to materialise two 32-bit integers than to load a double 6755 // from the constant pool and transfer it to integer registers through the 6756 // stack. 6757 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 6758 APInt V = C->getValueAPF().bitcastToAPInt(); 6759 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 6760 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 6761 return DCI.CombineTo(N, Lo, Hi); 6762 } 6763 6764 // This is a target-specific version of a DAGCombine performed in 6765 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6766 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6767 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6768 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6769 !Op0.getNode()->hasOneUse()) 6770 break; 6771 SDValue NewSplitF64 = 6772 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 6773 Op0.getOperand(0)); 6774 SDValue Lo = NewSplitF64.getValue(0); 6775 SDValue Hi = NewSplitF64.getValue(1); 6776 APInt SignBit = APInt::getSignMask(32); 6777 if (Op0.getOpcode() == ISD::FNEG) { 6778 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 6779 DAG.getConstant(SignBit, DL, MVT::i32)); 6780 return DCI.CombineTo(N, Lo, NewHi); 6781 } 6782 assert(Op0.getOpcode() == ISD::FABS); 6783 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 6784 DAG.getConstant(~SignBit, DL, MVT::i32)); 6785 return DCI.CombineTo(N, Lo, NewHi); 6786 } 6787 case RISCVISD::SLLW: 6788 case RISCVISD::SRAW: 6789 case RISCVISD::SRLW: 6790 case RISCVISD::ROLW: 6791 case RISCVISD::RORW: { 6792 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6793 if (SimplifyDemandedLowBitsHelper(0, 32) || 6794 SimplifyDemandedLowBitsHelper(1, 5)) 6795 return SDValue(N, 0); 6796 break; 6797 } 6798 case RISCVISD::CLZW: 6799 case RISCVISD::CTZW: { 6800 // Only the lower 32 bits of the first operand are read 6801 if (SimplifyDemandedLowBitsHelper(0, 32)) 6802 return SDValue(N, 0); 6803 break; 6804 } 6805 case RISCVISD::FSL: 6806 case RISCVISD::FSR: { 6807 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 6808 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 6809 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6810 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 6811 return SDValue(N, 0); 6812 break; 6813 } 6814 case RISCVISD::FSLW: 6815 case RISCVISD::FSRW: { 6816 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 6817 // read. 6818 if (SimplifyDemandedLowBitsHelper(0, 32) || 6819 SimplifyDemandedLowBitsHelper(1, 32) || 6820 SimplifyDemandedLowBitsHelper(2, 6)) 6821 return SDValue(N, 0); 6822 break; 6823 } 6824 case RISCVISD::GREV: 6825 case RISCVISD::GORC: { 6826 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 6827 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6828 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6829 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 6830 return SDValue(N, 0); 6831 6832 return combineGREVI_GORCI(N, DCI.DAG); 6833 } 6834 case RISCVISD::GREVW: 6835 case RISCVISD::GORCW: { 6836 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6837 if (SimplifyDemandedLowBitsHelper(0, 32) || 6838 SimplifyDemandedLowBitsHelper(1, 5)) 6839 return SDValue(N, 0); 6840 6841 return combineGREVI_GORCI(N, DCI.DAG); 6842 } 6843 case RISCVISD::SHFL: 6844 case RISCVISD::UNSHFL: { 6845 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 6846 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6847 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6848 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 6849 return SDValue(N, 0); 6850 6851 break; 6852 } 6853 case RISCVISD::SHFLW: 6854 case RISCVISD::UNSHFLW: { 6855 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 6856 SDValue LHS = N->getOperand(0); 6857 SDValue RHS = N->getOperand(1); 6858 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 6859 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 6860 if (SimplifyDemandedLowBitsHelper(0, 32) || 6861 SimplifyDemandedLowBitsHelper(1, 4)) 6862 return SDValue(N, 0); 6863 6864 break; 6865 } 6866 case RISCVISD::BCOMPRESSW: 6867 case RISCVISD::BDECOMPRESSW: { 6868 // Only the lower 32 bits of LHS and RHS are read. 6869 if (SimplifyDemandedLowBitsHelper(0, 32) || 6870 SimplifyDemandedLowBitsHelper(1, 32)) 6871 return SDValue(N, 0); 6872 6873 break; 6874 } 6875 case RISCVISD::FMV_X_ANYEXTH: 6876 case RISCVISD::FMV_X_ANYEXTW_RV64: { 6877 SDLoc DL(N); 6878 SDValue Op0 = N->getOperand(0); 6879 MVT VT = N->getSimpleValueType(0); 6880 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 6881 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 6882 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 6883 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 6884 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 6885 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 6886 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 6887 assert(Op0.getOperand(0).getValueType() == VT && 6888 "Unexpected value type!"); 6889 return Op0.getOperand(0); 6890 } 6891 6892 // This is a target-specific version of a DAGCombine performed in 6893 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6894 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6895 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6896 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6897 !Op0.getNode()->hasOneUse()) 6898 break; 6899 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 6900 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 6901 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 6902 if (Op0.getOpcode() == ISD::FNEG) 6903 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 6904 DAG.getConstant(SignBit, DL, VT)); 6905 6906 assert(Op0.getOpcode() == ISD::FABS); 6907 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 6908 DAG.getConstant(~SignBit, DL, VT)); 6909 } 6910 case ISD::ADD: 6911 return performADDCombine(N, DAG, Subtarget); 6912 case ISD::SUB: 6913 return performSUBCombine(N, DAG); 6914 case ISD::AND: 6915 return performANDCombine(N, DAG); 6916 case ISD::OR: 6917 return performORCombine(N, DAG, Subtarget); 6918 case ISD::XOR: 6919 return performXORCombine(N, DAG); 6920 case ISD::ANY_EXTEND: 6921 return performANY_EXTENDCombine(N, DCI, Subtarget); 6922 case ISD::ZERO_EXTEND: 6923 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 6924 // type legalization. This is safe because fp_to_uint produces poison if 6925 // it overflows. 6926 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() && 6927 N->getOperand(0).getOpcode() == ISD::FP_TO_UINT && 6928 isTypeLegal(N->getOperand(0).getOperand(0).getValueType())) 6929 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 6930 N->getOperand(0).getOperand(0)); 6931 return SDValue(); 6932 case RISCVISD::SELECT_CC: { 6933 // Transform 6934 SDValue LHS = N->getOperand(0); 6935 SDValue RHS = N->getOperand(1); 6936 SDValue TrueV = N->getOperand(3); 6937 SDValue FalseV = N->getOperand(4); 6938 6939 // If the True and False values are the same, we don't need a select_cc. 6940 if (TrueV == FalseV) 6941 return TrueV; 6942 6943 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6944 if (!ISD::isIntEqualitySetCC(CCVal)) 6945 break; 6946 6947 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 6948 // (select_cc X, Y, lt, trueV, falseV) 6949 // Sometimes the setcc is introduced after select_cc has been formed. 6950 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6951 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6952 // If we're looking for eq 0 instead of ne 0, we need to invert the 6953 // condition. 6954 bool Invert = CCVal == ISD::SETEQ; 6955 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6956 if (Invert) 6957 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6958 6959 SDLoc DL(N); 6960 RHS = LHS.getOperand(1); 6961 LHS = LHS.getOperand(0); 6962 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6963 6964 SDValue TargetCC = DAG.getCondCode(CCVal); 6965 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6966 {LHS, RHS, TargetCC, TrueV, FalseV}); 6967 } 6968 6969 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 6970 // (select_cc X, Y, eq/ne, trueV, falseV) 6971 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6972 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 6973 {LHS.getOperand(0), LHS.getOperand(1), 6974 N->getOperand(2), TrueV, FalseV}); 6975 // (select_cc X, 1, setne, trueV, falseV) -> 6976 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 6977 // This can occur when legalizing some floating point comparisons. 6978 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6979 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6980 SDLoc DL(N); 6981 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6982 SDValue TargetCC = DAG.getCondCode(CCVal); 6983 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6984 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6985 {LHS, RHS, TargetCC, TrueV, FalseV}); 6986 } 6987 6988 break; 6989 } 6990 case RISCVISD::BR_CC: { 6991 SDValue LHS = N->getOperand(1); 6992 SDValue RHS = N->getOperand(2); 6993 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 6994 if (!ISD::isIntEqualitySetCC(CCVal)) 6995 break; 6996 6997 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 6998 // (br_cc X, Y, lt, dest) 6999 // Sometimes the setcc is introduced after br_cc has been formed. 7000 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7001 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7002 // If we're looking for eq 0 instead of ne 0, we need to invert the 7003 // condition. 7004 bool Invert = CCVal == ISD::SETEQ; 7005 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7006 if (Invert) 7007 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7008 7009 SDLoc DL(N); 7010 RHS = LHS.getOperand(1); 7011 LHS = LHS.getOperand(0); 7012 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7013 7014 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7015 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7016 N->getOperand(4)); 7017 } 7018 7019 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7020 // (br_cc X, Y, eq/ne, trueV, falseV) 7021 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7022 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7023 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7024 N->getOperand(3), N->getOperand(4)); 7025 7026 // (br_cc X, 1, setne, br_cc) -> 7027 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7028 // This can occur when legalizing some floating point comparisons. 7029 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7030 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7031 SDLoc DL(N); 7032 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7033 SDValue TargetCC = DAG.getCondCode(CCVal); 7034 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7035 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7036 N->getOperand(0), LHS, RHS, TargetCC, 7037 N->getOperand(4)); 7038 } 7039 break; 7040 } 7041 case ISD::FCOPYSIGN: { 7042 EVT VT = N->getValueType(0); 7043 if (!VT.isVector()) 7044 break; 7045 // There is a form of VFSGNJ which injects the negated sign of its second 7046 // operand. Try and bubble any FNEG up after the extend/round to produce 7047 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7048 // TRUNC=1. 7049 SDValue In2 = N->getOperand(1); 7050 // Avoid cases where the extend/round has multiple uses, as duplicating 7051 // those is typically more expensive than removing a fneg. 7052 if (!In2.hasOneUse()) 7053 break; 7054 if (In2.getOpcode() != ISD::FP_EXTEND && 7055 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7056 break; 7057 In2 = In2.getOperand(0); 7058 if (In2.getOpcode() != ISD::FNEG) 7059 break; 7060 SDLoc DL(N); 7061 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7062 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7063 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7064 } 7065 case ISD::MGATHER: 7066 case ISD::MSCATTER: 7067 case ISD::VP_GATHER: 7068 case ISD::VP_SCATTER: { 7069 if (!DCI.isBeforeLegalize()) 7070 break; 7071 SDValue Index, ScaleOp; 7072 bool IsIndexScaled = false; 7073 bool IsIndexSigned = false; 7074 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7075 Index = VPGSN->getIndex(); 7076 ScaleOp = VPGSN->getScale(); 7077 IsIndexScaled = VPGSN->isIndexScaled(); 7078 IsIndexSigned = VPGSN->isIndexSigned(); 7079 } else { 7080 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7081 Index = MGSN->getIndex(); 7082 ScaleOp = MGSN->getScale(); 7083 IsIndexScaled = MGSN->isIndexScaled(); 7084 IsIndexSigned = MGSN->isIndexSigned(); 7085 } 7086 EVT IndexVT = Index.getValueType(); 7087 MVT XLenVT = Subtarget.getXLenVT(); 7088 // RISCV indexed loads only support the "unsigned unscaled" addressing 7089 // mode, so anything else must be manually legalized. 7090 bool NeedsIdxLegalization = 7091 IsIndexScaled || 7092 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7093 if (!NeedsIdxLegalization) 7094 break; 7095 7096 SDLoc DL(N); 7097 7098 // Any index legalization should first promote to XLenVT, so we don't lose 7099 // bits when scaling. This may create an illegal index type so we let 7100 // LLVM's legalization take care of the splitting. 7101 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7102 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7103 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7104 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7105 DL, IndexVT, Index); 7106 } 7107 7108 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7109 if (IsIndexScaled && Scale != 1) { 7110 // Manually scale the indices by the element size. 7111 // TODO: Sanitize the scale operand here? 7112 // TODO: For VP nodes, should we use VP_SHL here? 7113 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7114 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7115 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7116 } 7117 7118 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7119 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7120 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7121 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7122 VPGN->getScale(), VPGN->getMask(), 7123 VPGN->getVectorLength()}, 7124 VPGN->getMemOperand(), NewIndexTy); 7125 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7126 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7127 {VPSN->getChain(), VPSN->getValue(), 7128 VPSN->getBasePtr(), Index, VPSN->getScale(), 7129 VPSN->getMask(), VPSN->getVectorLength()}, 7130 VPSN->getMemOperand(), NewIndexTy); 7131 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7132 return DAG.getMaskedGather( 7133 N->getVTList(), MGN->getMemoryVT(), DL, 7134 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7135 MGN->getBasePtr(), Index, MGN->getScale()}, 7136 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7137 const auto *MSN = cast<MaskedScatterSDNode>(N); 7138 return DAG.getMaskedScatter( 7139 N->getVTList(), MSN->getMemoryVT(), DL, 7140 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7141 Index, MSN->getScale()}, 7142 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7143 } 7144 case RISCVISD::SRA_VL: 7145 case RISCVISD::SRL_VL: 7146 case RISCVISD::SHL_VL: { 7147 SDValue ShAmt = N->getOperand(1); 7148 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7149 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7150 SDLoc DL(N); 7151 SDValue VL = N->getOperand(3); 7152 EVT VT = N->getValueType(0); 7153 ShAmt = 7154 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7155 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7156 N->getOperand(2), N->getOperand(3)); 7157 } 7158 break; 7159 } 7160 case ISD::SRA: 7161 case ISD::SRL: 7162 case ISD::SHL: { 7163 SDValue ShAmt = N->getOperand(1); 7164 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7165 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7166 SDLoc DL(N); 7167 EVT VT = N->getValueType(0); 7168 ShAmt = 7169 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7170 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7171 } 7172 break; 7173 } 7174 case RISCVISD::MUL_VL: { 7175 SDValue Op0 = N->getOperand(0); 7176 SDValue Op1 = N->getOperand(1); 7177 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7178 return V; 7179 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7180 return V; 7181 return SDValue(); 7182 } 7183 case ISD::STORE: { 7184 auto *Store = cast<StoreSDNode>(N); 7185 SDValue Val = Store->getValue(); 7186 // Combine store of vmv.x.s to vse with VL of 1. 7187 // FIXME: Support FP. 7188 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7189 SDValue Src = Val.getOperand(0); 7190 EVT VecVT = Src.getValueType(); 7191 EVT MemVT = Store->getMemoryVT(); 7192 // The memory VT and the element type must match. 7193 if (VecVT.getVectorElementType() == MemVT) { 7194 SDLoc DL(N); 7195 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7196 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7197 DAG.getConstant(1, DL, MaskVT), 7198 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7199 Store->getPointerInfo(), 7200 Store->getOriginalAlign(), 7201 Store->getMemOperand()->getFlags()); 7202 } 7203 } 7204 7205 break; 7206 } 7207 } 7208 7209 return SDValue(); 7210 } 7211 7212 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7213 const SDNode *N, CombineLevel Level) const { 7214 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7215 // materialised in fewer instructions than `(OP _, c1)`: 7216 // 7217 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7218 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7219 SDValue N0 = N->getOperand(0); 7220 EVT Ty = N0.getValueType(); 7221 if (Ty.isScalarInteger() && 7222 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7223 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7224 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7225 if (C1 && C2) { 7226 const APInt &C1Int = C1->getAPIntValue(); 7227 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7228 7229 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7230 // and the combine should happen, to potentially allow further combines 7231 // later. 7232 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7233 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7234 return true; 7235 7236 // We can materialise `c1` in an add immediate, so it's "free", and the 7237 // combine should be prevented. 7238 if (C1Int.getMinSignedBits() <= 64 && 7239 isLegalAddImmediate(C1Int.getSExtValue())) 7240 return false; 7241 7242 // Neither constant will fit into an immediate, so find materialisation 7243 // costs. 7244 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7245 Subtarget.getFeatureBits(), 7246 /*CompressionCost*/true); 7247 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7248 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7249 /*CompressionCost*/true); 7250 7251 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7252 // combine should be prevented. 7253 if (C1Cost < ShiftedC1Cost) 7254 return false; 7255 } 7256 } 7257 return true; 7258 } 7259 7260 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7261 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7262 TargetLoweringOpt &TLO) const { 7263 // Delay this optimization as late as possible. 7264 if (!TLO.LegalOps) 7265 return false; 7266 7267 EVT VT = Op.getValueType(); 7268 if (VT.isVector()) 7269 return false; 7270 7271 // Only handle AND for now. 7272 if (Op.getOpcode() != ISD::AND) 7273 return false; 7274 7275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7276 if (!C) 7277 return false; 7278 7279 const APInt &Mask = C->getAPIntValue(); 7280 7281 // Clear all non-demanded bits initially. 7282 APInt ShrunkMask = Mask & DemandedBits; 7283 7284 // Try to make a smaller immediate by setting undemanded bits. 7285 7286 APInt ExpandedMask = Mask | ~DemandedBits; 7287 7288 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7289 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7290 }; 7291 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7292 if (NewMask == Mask) 7293 return true; 7294 SDLoc DL(Op); 7295 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7296 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7297 return TLO.CombineTo(Op, NewOp); 7298 }; 7299 7300 // If the shrunk mask fits in sign extended 12 bits, let the target 7301 // independent code apply it. 7302 if (ShrunkMask.isSignedIntN(12)) 7303 return false; 7304 7305 // Preserve (and X, 0xffff) when zext.h is supported. 7306 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7307 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7308 if (IsLegalMask(NewMask)) 7309 return UseMask(NewMask); 7310 } 7311 7312 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7313 if (VT == MVT::i64) { 7314 APInt NewMask = APInt(64, 0xffffffff); 7315 if (IsLegalMask(NewMask)) 7316 return UseMask(NewMask); 7317 } 7318 7319 // For the remaining optimizations, we need to be able to make a negative 7320 // number through a combination of mask and undemanded bits. 7321 if (!ExpandedMask.isNegative()) 7322 return false; 7323 7324 // What is the fewest number of bits we need to represent the negative number. 7325 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7326 7327 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7328 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7329 APInt NewMask = ShrunkMask; 7330 if (MinSignedBits <= 12) 7331 NewMask.setBitsFrom(11); 7332 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7333 NewMask.setBitsFrom(31); 7334 else 7335 return false; 7336 7337 // Sanity check that our new mask is a subset of the demanded mask. 7338 assert(IsLegalMask(NewMask)); 7339 return UseMask(NewMask); 7340 } 7341 7342 static void computeGREV(APInt &Src, unsigned ShAmt) { 7343 ShAmt &= Src.getBitWidth() - 1; 7344 uint64_t x = Src.getZExtValue(); 7345 if (ShAmt & 1) 7346 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7347 if (ShAmt & 2) 7348 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7349 if (ShAmt & 4) 7350 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7351 if (ShAmt & 8) 7352 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7353 if (ShAmt & 16) 7354 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7355 if (ShAmt & 32) 7356 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7357 Src = x; 7358 } 7359 7360 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7361 KnownBits &Known, 7362 const APInt &DemandedElts, 7363 const SelectionDAG &DAG, 7364 unsigned Depth) const { 7365 unsigned BitWidth = Known.getBitWidth(); 7366 unsigned Opc = Op.getOpcode(); 7367 assert((Opc >= ISD::BUILTIN_OP_END || 7368 Opc == ISD::INTRINSIC_WO_CHAIN || 7369 Opc == ISD::INTRINSIC_W_CHAIN || 7370 Opc == ISD::INTRINSIC_VOID) && 7371 "Should use MaskedValueIsZero if you don't know whether Op" 7372 " is a target node!"); 7373 7374 Known.resetAll(); 7375 switch (Opc) { 7376 default: break; 7377 case RISCVISD::SELECT_CC: { 7378 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7379 // If we don't know any bits, early out. 7380 if (Known.isUnknown()) 7381 break; 7382 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7383 7384 // Only known if known in both the LHS and RHS. 7385 Known = KnownBits::commonBits(Known, Known2); 7386 break; 7387 } 7388 case RISCVISD::REMUW: { 7389 KnownBits Known2; 7390 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7391 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7392 // We only care about the lower 32 bits. 7393 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7394 // Restore the original width by sign extending. 7395 Known = Known.sext(BitWidth); 7396 break; 7397 } 7398 case RISCVISD::DIVUW: { 7399 KnownBits Known2; 7400 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7401 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7402 // We only care about the lower 32 bits. 7403 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7404 // Restore the original width by sign extending. 7405 Known = Known.sext(BitWidth); 7406 break; 7407 } 7408 case RISCVISD::CTZW: { 7409 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7410 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7411 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7412 Known.Zero.setBitsFrom(LowBits); 7413 break; 7414 } 7415 case RISCVISD::CLZW: { 7416 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7417 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7418 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7419 Known.Zero.setBitsFrom(LowBits); 7420 break; 7421 } 7422 case RISCVISD::GREV: 7423 case RISCVISD::GREVW: { 7424 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7425 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7426 if (Opc == RISCVISD::GREVW) 7427 Known = Known.trunc(32); 7428 unsigned ShAmt = C->getZExtValue(); 7429 computeGREV(Known.Zero, ShAmt); 7430 computeGREV(Known.One, ShAmt); 7431 if (Opc == RISCVISD::GREVW) 7432 Known = Known.sext(BitWidth); 7433 } 7434 break; 7435 } 7436 case RISCVISD::READ_VLENB: 7437 // We assume VLENB is at least 16 bytes. 7438 Known.Zero.setLowBits(4); 7439 // We assume VLENB is no more than 65536 / 8 bytes. 7440 Known.Zero.setBitsFrom(14); 7441 break; 7442 case ISD::INTRINSIC_W_CHAIN: { 7443 unsigned IntNo = Op.getConstantOperandVal(1); 7444 switch (IntNo) { 7445 default: 7446 // We can't do anything for most intrinsics. 7447 break; 7448 case Intrinsic::riscv_vsetvli: 7449 case Intrinsic::riscv_vsetvlimax: 7450 // Assume that VL output is positive and would fit in an int32_t. 7451 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7452 if (BitWidth >= 32) 7453 Known.Zero.setBitsFrom(31); 7454 break; 7455 } 7456 break; 7457 } 7458 } 7459 } 7460 7461 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7462 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7463 unsigned Depth) const { 7464 switch (Op.getOpcode()) { 7465 default: 7466 break; 7467 case RISCVISD::SELECT_CC: { 7468 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7469 if (Tmp == 1) return 1; // Early out. 7470 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7471 return std::min(Tmp, Tmp2); 7472 } 7473 case RISCVISD::SLLW: 7474 case RISCVISD::SRAW: 7475 case RISCVISD::SRLW: 7476 case RISCVISD::DIVW: 7477 case RISCVISD::DIVUW: 7478 case RISCVISD::REMUW: 7479 case RISCVISD::ROLW: 7480 case RISCVISD::RORW: 7481 case RISCVISD::GREVW: 7482 case RISCVISD::GORCW: 7483 case RISCVISD::FSLW: 7484 case RISCVISD::FSRW: 7485 case RISCVISD::SHFLW: 7486 case RISCVISD::UNSHFLW: 7487 case RISCVISD::BCOMPRESSW: 7488 case RISCVISD::BDECOMPRESSW: 7489 case RISCVISD::FCVT_W_RTZ_RV64: 7490 case RISCVISD::FCVT_WU_RTZ_RV64: 7491 // TODO: As the result is sign-extended, this is conservatively correct. A 7492 // more precise answer could be calculated for SRAW depending on known 7493 // bits in the shift amount. 7494 return 33; 7495 case RISCVISD::SHFL: 7496 case RISCVISD::UNSHFL: { 7497 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7498 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7499 // will stay within the upper 32 bits. If there were more than 32 sign bits 7500 // before there will be at least 33 sign bits after. 7501 if (Op.getValueType() == MVT::i64 && 7502 isa<ConstantSDNode>(Op.getOperand(1)) && 7503 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7504 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7505 if (Tmp > 32) 7506 return 33; 7507 } 7508 break; 7509 } 7510 case RISCVISD::VMV_X_S: 7511 // The number of sign bits of the scalar result is computed by obtaining the 7512 // element type of the input vector operand, subtracting its width from the 7513 // XLEN, and then adding one (sign bit within the element type). If the 7514 // element type is wider than XLen, the least-significant XLEN bits are 7515 // taken. 7516 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7517 return 1; 7518 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7519 } 7520 7521 return 1; 7522 } 7523 7524 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7525 MachineBasicBlock *BB) { 7526 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7527 7528 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7529 // Should the count have wrapped while it was being read, we need to try 7530 // again. 7531 // ... 7532 // read: 7533 // rdcycleh x3 # load high word of cycle 7534 // rdcycle x2 # load low word of cycle 7535 // rdcycleh x4 # load high word of cycle 7536 // bne x3, x4, read # check if high word reads match, otherwise try again 7537 // ... 7538 7539 MachineFunction &MF = *BB->getParent(); 7540 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7541 MachineFunction::iterator It = ++BB->getIterator(); 7542 7543 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7544 MF.insert(It, LoopMBB); 7545 7546 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7547 MF.insert(It, DoneMBB); 7548 7549 // Transfer the remainder of BB and its successor edges to DoneMBB. 7550 DoneMBB->splice(DoneMBB->begin(), BB, 7551 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7552 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7553 7554 BB->addSuccessor(LoopMBB); 7555 7556 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7557 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7558 Register LoReg = MI.getOperand(0).getReg(); 7559 Register HiReg = MI.getOperand(1).getReg(); 7560 DebugLoc DL = MI.getDebugLoc(); 7561 7562 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7563 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7564 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7565 .addReg(RISCV::X0); 7566 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7567 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7568 .addReg(RISCV::X0); 7569 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7570 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7571 .addReg(RISCV::X0); 7572 7573 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7574 .addReg(HiReg) 7575 .addReg(ReadAgainReg) 7576 .addMBB(LoopMBB); 7577 7578 LoopMBB->addSuccessor(LoopMBB); 7579 LoopMBB->addSuccessor(DoneMBB); 7580 7581 MI.eraseFromParent(); 7582 7583 return DoneMBB; 7584 } 7585 7586 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7587 MachineBasicBlock *BB) { 7588 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7589 7590 MachineFunction &MF = *BB->getParent(); 7591 DebugLoc DL = MI.getDebugLoc(); 7592 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7593 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7594 Register LoReg = MI.getOperand(0).getReg(); 7595 Register HiReg = MI.getOperand(1).getReg(); 7596 Register SrcReg = MI.getOperand(2).getReg(); 7597 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7598 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7599 7600 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7601 RI); 7602 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7603 MachineMemOperand *MMOLo = 7604 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7605 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7606 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7607 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7608 .addFrameIndex(FI) 7609 .addImm(0) 7610 .addMemOperand(MMOLo); 7611 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7612 .addFrameIndex(FI) 7613 .addImm(4) 7614 .addMemOperand(MMOHi); 7615 MI.eraseFromParent(); // The pseudo instruction is gone now. 7616 return BB; 7617 } 7618 7619 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7620 MachineBasicBlock *BB) { 7621 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7622 "Unexpected instruction"); 7623 7624 MachineFunction &MF = *BB->getParent(); 7625 DebugLoc DL = MI.getDebugLoc(); 7626 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7627 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7628 Register DstReg = MI.getOperand(0).getReg(); 7629 Register LoReg = MI.getOperand(1).getReg(); 7630 Register HiReg = MI.getOperand(2).getReg(); 7631 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7632 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7633 7634 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7635 MachineMemOperand *MMOLo = 7636 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7637 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7638 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7639 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7640 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7641 .addFrameIndex(FI) 7642 .addImm(0) 7643 .addMemOperand(MMOLo); 7644 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7645 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7646 .addFrameIndex(FI) 7647 .addImm(4) 7648 .addMemOperand(MMOHi); 7649 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7650 MI.eraseFromParent(); // The pseudo instruction is gone now. 7651 return BB; 7652 } 7653 7654 static bool isSelectPseudo(MachineInstr &MI) { 7655 switch (MI.getOpcode()) { 7656 default: 7657 return false; 7658 case RISCV::Select_GPR_Using_CC_GPR: 7659 case RISCV::Select_FPR16_Using_CC_GPR: 7660 case RISCV::Select_FPR32_Using_CC_GPR: 7661 case RISCV::Select_FPR64_Using_CC_GPR: 7662 return true; 7663 } 7664 } 7665 7666 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7667 MachineBasicBlock *BB, 7668 const RISCVSubtarget &Subtarget) { 7669 // To "insert" Select_* instructions, we actually have to insert the triangle 7670 // control-flow pattern. The incoming instructions know the destination vreg 7671 // to set, the condition code register to branch on, the true/false values to 7672 // select between, and the condcode to use to select the appropriate branch. 7673 // 7674 // We produce the following control flow: 7675 // HeadMBB 7676 // | \ 7677 // | IfFalseMBB 7678 // | / 7679 // TailMBB 7680 // 7681 // When we find a sequence of selects we attempt to optimize their emission 7682 // by sharing the control flow. Currently we only handle cases where we have 7683 // multiple selects with the exact same condition (same LHS, RHS and CC). 7684 // The selects may be interleaved with other instructions if the other 7685 // instructions meet some requirements we deem safe: 7686 // - They are debug instructions. Otherwise, 7687 // - They do not have side-effects, do not access memory and their inputs do 7688 // not depend on the results of the select pseudo-instructions. 7689 // The TrueV/FalseV operands of the selects cannot depend on the result of 7690 // previous selects in the sequence. 7691 // These conditions could be further relaxed. See the X86 target for a 7692 // related approach and more information. 7693 Register LHS = MI.getOperand(1).getReg(); 7694 Register RHS = MI.getOperand(2).getReg(); 7695 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 7696 7697 SmallVector<MachineInstr *, 4> SelectDebugValues; 7698 SmallSet<Register, 4> SelectDests; 7699 SelectDests.insert(MI.getOperand(0).getReg()); 7700 7701 MachineInstr *LastSelectPseudo = &MI; 7702 7703 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 7704 SequenceMBBI != E; ++SequenceMBBI) { 7705 if (SequenceMBBI->isDebugInstr()) 7706 continue; 7707 else if (isSelectPseudo(*SequenceMBBI)) { 7708 if (SequenceMBBI->getOperand(1).getReg() != LHS || 7709 SequenceMBBI->getOperand(2).getReg() != RHS || 7710 SequenceMBBI->getOperand(3).getImm() != CC || 7711 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 7712 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 7713 break; 7714 LastSelectPseudo = &*SequenceMBBI; 7715 SequenceMBBI->collectDebugValues(SelectDebugValues); 7716 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 7717 } else { 7718 if (SequenceMBBI->hasUnmodeledSideEffects() || 7719 SequenceMBBI->mayLoadOrStore()) 7720 break; 7721 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 7722 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 7723 })) 7724 break; 7725 } 7726 } 7727 7728 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 7729 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7730 DebugLoc DL = MI.getDebugLoc(); 7731 MachineFunction::iterator I = ++BB->getIterator(); 7732 7733 MachineBasicBlock *HeadMBB = BB; 7734 MachineFunction *F = BB->getParent(); 7735 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 7736 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 7737 7738 F->insert(I, IfFalseMBB); 7739 F->insert(I, TailMBB); 7740 7741 // Transfer debug instructions associated with the selects to TailMBB. 7742 for (MachineInstr *DebugInstr : SelectDebugValues) { 7743 TailMBB->push_back(DebugInstr->removeFromParent()); 7744 } 7745 7746 // Move all instructions after the sequence to TailMBB. 7747 TailMBB->splice(TailMBB->end(), HeadMBB, 7748 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 7749 // Update machine-CFG edges by transferring all successors of the current 7750 // block to the new block which will contain the Phi nodes for the selects. 7751 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 7752 // Set the successors for HeadMBB. 7753 HeadMBB->addSuccessor(IfFalseMBB); 7754 HeadMBB->addSuccessor(TailMBB); 7755 7756 // Insert appropriate branch. 7757 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 7758 .addReg(LHS) 7759 .addReg(RHS) 7760 .addMBB(TailMBB); 7761 7762 // IfFalseMBB just falls through to TailMBB. 7763 IfFalseMBB->addSuccessor(TailMBB); 7764 7765 // Create PHIs for all of the select pseudo-instructions. 7766 auto SelectMBBI = MI.getIterator(); 7767 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 7768 auto InsertionPoint = TailMBB->begin(); 7769 while (SelectMBBI != SelectEnd) { 7770 auto Next = std::next(SelectMBBI); 7771 if (isSelectPseudo(*SelectMBBI)) { 7772 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 7773 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 7774 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 7775 .addReg(SelectMBBI->getOperand(4).getReg()) 7776 .addMBB(HeadMBB) 7777 .addReg(SelectMBBI->getOperand(5).getReg()) 7778 .addMBB(IfFalseMBB); 7779 SelectMBBI->eraseFromParent(); 7780 } 7781 SelectMBBI = Next; 7782 } 7783 7784 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 7785 return TailMBB; 7786 } 7787 7788 MachineBasicBlock * 7789 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 7790 MachineBasicBlock *BB) const { 7791 switch (MI.getOpcode()) { 7792 default: 7793 llvm_unreachable("Unexpected instr type to insert"); 7794 case RISCV::ReadCycleWide: 7795 assert(!Subtarget.is64Bit() && 7796 "ReadCycleWrite is only to be used on riscv32"); 7797 return emitReadCycleWidePseudo(MI, BB); 7798 case RISCV::Select_GPR_Using_CC_GPR: 7799 case RISCV::Select_FPR16_Using_CC_GPR: 7800 case RISCV::Select_FPR32_Using_CC_GPR: 7801 case RISCV::Select_FPR64_Using_CC_GPR: 7802 return emitSelectPseudo(MI, BB, Subtarget); 7803 case RISCV::BuildPairF64Pseudo: 7804 return emitBuildPairF64Pseudo(MI, BB); 7805 case RISCV::SplitF64Pseudo: 7806 return emitSplitF64Pseudo(MI, BB); 7807 } 7808 } 7809 7810 // Calling Convention Implementation. 7811 // The expectations for frontend ABI lowering vary from target to target. 7812 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 7813 // details, but this is a longer term goal. For now, we simply try to keep the 7814 // role of the frontend as simple and well-defined as possible. The rules can 7815 // be summarised as: 7816 // * Never split up large scalar arguments. We handle them here. 7817 // * If a hardfloat calling convention is being used, and the struct may be 7818 // passed in a pair of registers (fp+fp, int+fp), and both registers are 7819 // available, then pass as two separate arguments. If either the GPRs or FPRs 7820 // are exhausted, then pass according to the rule below. 7821 // * If a struct could never be passed in registers or directly in a stack 7822 // slot (as it is larger than 2*XLEN and the floating point rules don't 7823 // apply), then pass it using a pointer with the byval attribute. 7824 // * If a struct is less than 2*XLEN, then coerce to either a two-element 7825 // word-sized array or a 2*XLEN scalar (depending on alignment). 7826 // * The frontend can determine whether a struct is returned by reference or 7827 // not based on its size and fields. If it will be returned by reference, the 7828 // frontend must modify the prototype so a pointer with the sret annotation is 7829 // passed as the first argument. This is not necessary for large scalar 7830 // returns. 7831 // * Struct return values and varargs should be coerced to structs containing 7832 // register-size fields in the same situations they would be for fixed 7833 // arguments. 7834 7835 static const MCPhysReg ArgGPRs[] = { 7836 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 7837 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 7838 }; 7839 static const MCPhysReg ArgFPR16s[] = { 7840 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 7841 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 7842 }; 7843 static const MCPhysReg ArgFPR32s[] = { 7844 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 7845 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 7846 }; 7847 static const MCPhysReg ArgFPR64s[] = { 7848 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 7849 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 7850 }; 7851 // This is an interim calling convention and it may be changed in the future. 7852 static const MCPhysReg ArgVRs[] = { 7853 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 7854 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 7855 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 7856 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 7857 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 7858 RISCV::V20M2, RISCV::V22M2}; 7859 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 7860 RISCV::V20M4}; 7861 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 7862 7863 // Pass a 2*XLEN argument that has been split into two XLEN values through 7864 // registers or the stack as necessary. 7865 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 7866 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 7867 MVT ValVT2, MVT LocVT2, 7868 ISD::ArgFlagsTy ArgFlags2) { 7869 unsigned XLenInBytes = XLen / 8; 7870 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7871 // At least one half can be passed via register. 7872 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 7873 VA1.getLocVT(), CCValAssign::Full)); 7874 } else { 7875 // Both halves must be passed on the stack, with proper alignment. 7876 Align StackAlign = 7877 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 7878 State.addLoc( 7879 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 7880 State.AllocateStack(XLenInBytes, StackAlign), 7881 VA1.getLocVT(), CCValAssign::Full)); 7882 State.addLoc(CCValAssign::getMem( 7883 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7884 LocVT2, CCValAssign::Full)); 7885 return false; 7886 } 7887 7888 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7889 // The second half can also be passed via register. 7890 State.addLoc( 7891 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 7892 } else { 7893 // The second half is passed via the stack, without additional alignment. 7894 State.addLoc(CCValAssign::getMem( 7895 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7896 LocVT2, CCValAssign::Full)); 7897 } 7898 7899 return false; 7900 } 7901 7902 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 7903 Optional<unsigned> FirstMaskArgument, 7904 CCState &State, const RISCVTargetLowering &TLI) { 7905 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 7906 if (RC == &RISCV::VRRegClass) { 7907 // Assign the first mask argument to V0. 7908 // This is an interim calling convention and it may be changed in the 7909 // future. 7910 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 7911 return State.AllocateReg(RISCV::V0); 7912 return State.AllocateReg(ArgVRs); 7913 } 7914 if (RC == &RISCV::VRM2RegClass) 7915 return State.AllocateReg(ArgVRM2s); 7916 if (RC == &RISCV::VRM4RegClass) 7917 return State.AllocateReg(ArgVRM4s); 7918 if (RC == &RISCV::VRM8RegClass) 7919 return State.AllocateReg(ArgVRM8s); 7920 llvm_unreachable("Unhandled register class for ValueType"); 7921 } 7922 7923 // Implements the RISC-V calling convention. Returns true upon failure. 7924 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 7925 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 7926 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 7927 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 7928 Optional<unsigned> FirstMaskArgument) { 7929 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 7930 assert(XLen == 32 || XLen == 64); 7931 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 7932 7933 // Any return value split in to more than two values can't be returned 7934 // directly. Vectors are returned via the available vector registers. 7935 if (!LocVT.isVector() && IsRet && ValNo > 1) 7936 return true; 7937 7938 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 7939 // variadic argument, or if no F16/F32 argument registers are available. 7940 bool UseGPRForF16_F32 = true; 7941 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 7942 // variadic argument, or if no F64 argument registers are available. 7943 bool UseGPRForF64 = true; 7944 7945 switch (ABI) { 7946 default: 7947 llvm_unreachable("Unexpected ABI"); 7948 case RISCVABI::ABI_ILP32: 7949 case RISCVABI::ABI_LP64: 7950 break; 7951 case RISCVABI::ABI_ILP32F: 7952 case RISCVABI::ABI_LP64F: 7953 UseGPRForF16_F32 = !IsFixed; 7954 break; 7955 case RISCVABI::ABI_ILP32D: 7956 case RISCVABI::ABI_LP64D: 7957 UseGPRForF16_F32 = !IsFixed; 7958 UseGPRForF64 = !IsFixed; 7959 break; 7960 } 7961 7962 // FPR16, FPR32, and FPR64 alias each other. 7963 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 7964 UseGPRForF16_F32 = true; 7965 UseGPRForF64 = true; 7966 } 7967 7968 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 7969 // similar local variables rather than directly checking against the target 7970 // ABI. 7971 7972 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 7973 LocVT = XLenVT; 7974 LocInfo = CCValAssign::BCvt; 7975 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 7976 LocVT = MVT::i64; 7977 LocInfo = CCValAssign::BCvt; 7978 } 7979 7980 // If this is a variadic argument, the RISC-V calling convention requires 7981 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 7982 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 7983 // be used regardless of whether the original argument was split during 7984 // legalisation or not. The argument will not be passed by registers if the 7985 // original type is larger than 2*XLEN, so the register alignment rule does 7986 // not apply. 7987 unsigned TwoXLenInBytes = (2 * XLen) / 8; 7988 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 7989 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 7990 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 7991 // Skip 'odd' register if necessary. 7992 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 7993 State.AllocateReg(ArgGPRs); 7994 } 7995 7996 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 7997 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 7998 State.getPendingArgFlags(); 7999 8000 assert(PendingLocs.size() == PendingArgFlags.size() && 8001 "PendingLocs and PendingArgFlags out of sync"); 8002 8003 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8004 // registers are exhausted. 8005 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8006 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8007 "Can't lower f64 if it is split"); 8008 // Depending on available argument GPRS, f64 may be passed in a pair of 8009 // GPRs, split between a GPR and the stack, or passed completely on the 8010 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8011 // cases. 8012 Register Reg = State.AllocateReg(ArgGPRs); 8013 LocVT = MVT::i32; 8014 if (!Reg) { 8015 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8016 State.addLoc( 8017 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8018 return false; 8019 } 8020 if (!State.AllocateReg(ArgGPRs)) 8021 State.AllocateStack(4, Align(4)); 8022 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8023 return false; 8024 } 8025 8026 // Fixed-length vectors are located in the corresponding scalable-vector 8027 // container types. 8028 if (ValVT.isFixedLengthVector()) 8029 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8030 8031 // Split arguments might be passed indirectly, so keep track of the pending 8032 // values. Split vectors are passed via a mix of registers and indirectly, so 8033 // treat them as we would any other argument. 8034 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8035 LocVT = XLenVT; 8036 LocInfo = CCValAssign::Indirect; 8037 PendingLocs.push_back( 8038 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8039 PendingArgFlags.push_back(ArgFlags); 8040 if (!ArgFlags.isSplitEnd()) { 8041 return false; 8042 } 8043 } 8044 8045 // If the split argument only had two elements, it should be passed directly 8046 // in registers or on the stack. 8047 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8048 PendingLocs.size() <= 2) { 8049 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8050 // Apply the normal calling convention rules to the first half of the 8051 // split argument. 8052 CCValAssign VA = PendingLocs[0]; 8053 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8054 PendingLocs.clear(); 8055 PendingArgFlags.clear(); 8056 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8057 ArgFlags); 8058 } 8059 8060 // Allocate to a register if possible, or else a stack slot. 8061 Register Reg; 8062 unsigned StoreSizeBytes = XLen / 8; 8063 Align StackAlign = Align(XLen / 8); 8064 8065 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8066 Reg = State.AllocateReg(ArgFPR16s); 8067 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8068 Reg = State.AllocateReg(ArgFPR32s); 8069 else if (ValVT == MVT::f64 && !UseGPRForF64) 8070 Reg = State.AllocateReg(ArgFPR64s); 8071 else if (ValVT.isVector()) { 8072 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8073 if (!Reg) { 8074 // For return values, the vector must be passed fully via registers or 8075 // via the stack. 8076 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8077 // but we're using all of them. 8078 if (IsRet) 8079 return true; 8080 // Try using a GPR to pass the address 8081 if ((Reg = State.AllocateReg(ArgGPRs))) { 8082 LocVT = XLenVT; 8083 LocInfo = CCValAssign::Indirect; 8084 } else if (ValVT.isScalableVector()) { 8085 report_fatal_error("Unable to pass scalable vector types on the stack"); 8086 } else { 8087 // Pass fixed-length vectors on the stack. 8088 LocVT = ValVT; 8089 StoreSizeBytes = ValVT.getStoreSize(); 8090 // Align vectors to their element sizes, being careful for vXi1 8091 // vectors. 8092 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8093 } 8094 } 8095 } else { 8096 Reg = State.AllocateReg(ArgGPRs); 8097 } 8098 8099 unsigned StackOffset = 8100 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8101 8102 // If we reach this point and PendingLocs is non-empty, we must be at the 8103 // end of a split argument that must be passed indirectly. 8104 if (!PendingLocs.empty()) { 8105 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8106 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8107 8108 for (auto &It : PendingLocs) { 8109 if (Reg) 8110 It.convertToReg(Reg); 8111 else 8112 It.convertToMem(StackOffset); 8113 State.addLoc(It); 8114 } 8115 PendingLocs.clear(); 8116 PendingArgFlags.clear(); 8117 return false; 8118 } 8119 8120 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8121 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8122 "Expected an XLenVT or vector types at this stage"); 8123 8124 if (Reg) { 8125 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8126 return false; 8127 } 8128 8129 // When a floating-point value is passed on the stack, no bit-conversion is 8130 // needed. 8131 if (ValVT.isFloatingPoint()) { 8132 LocVT = ValVT; 8133 LocInfo = CCValAssign::Full; 8134 } 8135 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8136 return false; 8137 } 8138 8139 template <typename ArgTy> 8140 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8141 for (const auto &ArgIdx : enumerate(Args)) { 8142 MVT ArgVT = ArgIdx.value().VT; 8143 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8144 return ArgIdx.index(); 8145 } 8146 return None; 8147 } 8148 8149 void RISCVTargetLowering::analyzeInputArgs( 8150 MachineFunction &MF, CCState &CCInfo, 8151 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8152 RISCVCCAssignFn Fn) const { 8153 unsigned NumArgs = Ins.size(); 8154 FunctionType *FType = MF.getFunction().getFunctionType(); 8155 8156 Optional<unsigned> FirstMaskArgument; 8157 if (Subtarget.hasVInstructions()) 8158 FirstMaskArgument = preAssignMask(Ins); 8159 8160 for (unsigned i = 0; i != NumArgs; ++i) { 8161 MVT ArgVT = Ins[i].VT; 8162 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8163 8164 Type *ArgTy = nullptr; 8165 if (IsRet) 8166 ArgTy = FType->getReturnType(); 8167 else if (Ins[i].isOrigArg()) 8168 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8169 8170 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8171 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8172 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8173 FirstMaskArgument)) { 8174 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8175 << EVT(ArgVT).getEVTString() << '\n'); 8176 llvm_unreachable(nullptr); 8177 } 8178 } 8179 } 8180 8181 void RISCVTargetLowering::analyzeOutputArgs( 8182 MachineFunction &MF, CCState &CCInfo, 8183 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8184 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8185 unsigned NumArgs = Outs.size(); 8186 8187 Optional<unsigned> FirstMaskArgument; 8188 if (Subtarget.hasVInstructions()) 8189 FirstMaskArgument = preAssignMask(Outs); 8190 8191 for (unsigned i = 0; i != NumArgs; i++) { 8192 MVT ArgVT = Outs[i].VT; 8193 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8194 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8195 8196 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8197 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8198 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8199 FirstMaskArgument)) { 8200 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8201 << EVT(ArgVT).getEVTString() << "\n"); 8202 llvm_unreachable(nullptr); 8203 } 8204 } 8205 } 8206 8207 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8208 // values. 8209 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8210 const CCValAssign &VA, const SDLoc &DL, 8211 const RISCVSubtarget &Subtarget) { 8212 switch (VA.getLocInfo()) { 8213 default: 8214 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8215 case CCValAssign::Full: 8216 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8217 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8218 break; 8219 case CCValAssign::BCvt: 8220 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8221 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8222 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8223 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8224 else 8225 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8226 break; 8227 } 8228 return Val; 8229 } 8230 8231 // The caller is responsible for loading the full value if the argument is 8232 // passed with CCValAssign::Indirect. 8233 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8234 const CCValAssign &VA, const SDLoc &DL, 8235 const RISCVTargetLowering &TLI) { 8236 MachineFunction &MF = DAG.getMachineFunction(); 8237 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8238 EVT LocVT = VA.getLocVT(); 8239 SDValue Val; 8240 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8241 Register VReg = RegInfo.createVirtualRegister(RC); 8242 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8243 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8244 8245 if (VA.getLocInfo() == CCValAssign::Indirect) 8246 return Val; 8247 8248 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8249 } 8250 8251 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8252 const CCValAssign &VA, const SDLoc &DL, 8253 const RISCVSubtarget &Subtarget) { 8254 EVT LocVT = VA.getLocVT(); 8255 8256 switch (VA.getLocInfo()) { 8257 default: 8258 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8259 case CCValAssign::Full: 8260 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8261 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8262 break; 8263 case CCValAssign::BCvt: 8264 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8265 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8266 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8267 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8268 else 8269 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8270 break; 8271 } 8272 return Val; 8273 } 8274 8275 // The caller is responsible for loading the full value if the argument is 8276 // passed with CCValAssign::Indirect. 8277 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8278 const CCValAssign &VA, const SDLoc &DL) { 8279 MachineFunction &MF = DAG.getMachineFunction(); 8280 MachineFrameInfo &MFI = MF.getFrameInfo(); 8281 EVT LocVT = VA.getLocVT(); 8282 EVT ValVT = VA.getValVT(); 8283 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8284 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8285 /*Immutable=*/true); 8286 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8287 SDValue Val; 8288 8289 ISD::LoadExtType ExtType; 8290 switch (VA.getLocInfo()) { 8291 default: 8292 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8293 case CCValAssign::Full: 8294 case CCValAssign::Indirect: 8295 case CCValAssign::BCvt: 8296 ExtType = ISD::NON_EXTLOAD; 8297 break; 8298 } 8299 Val = DAG.getExtLoad( 8300 ExtType, DL, LocVT, Chain, FIN, 8301 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8302 return Val; 8303 } 8304 8305 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8306 const CCValAssign &VA, const SDLoc &DL) { 8307 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8308 "Unexpected VA"); 8309 MachineFunction &MF = DAG.getMachineFunction(); 8310 MachineFrameInfo &MFI = MF.getFrameInfo(); 8311 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8312 8313 if (VA.isMemLoc()) { 8314 // f64 is passed on the stack. 8315 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8316 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8317 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8318 MachinePointerInfo::getFixedStack(MF, FI)); 8319 } 8320 8321 assert(VA.isRegLoc() && "Expected register VA assignment"); 8322 8323 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8324 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8325 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8326 SDValue Hi; 8327 if (VA.getLocReg() == RISCV::X17) { 8328 // Second half of f64 is passed on the stack. 8329 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8330 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8331 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8332 MachinePointerInfo::getFixedStack(MF, FI)); 8333 } else { 8334 // Second half of f64 is passed in another GPR. 8335 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8336 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8337 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8338 } 8339 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8340 } 8341 8342 // FastCC has less than 1% performance improvement for some particular 8343 // benchmark. But theoretically, it may has benenfit for some cases. 8344 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8345 unsigned ValNo, MVT ValVT, MVT LocVT, 8346 CCValAssign::LocInfo LocInfo, 8347 ISD::ArgFlagsTy ArgFlags, CCState &State, 8348 bool IsFixed, bool IsRet, Type *OrigTy, 8349 const RISCVTargetLowering &TLI, 8350 Optional<unsigned> FirstMaskArgument) { 8351 8352 // X5 and X6 might be used for save-restore libcall. 8353 static const MCPhysReg GPRList[] = { 8354 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8355 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8356 RISCV::X29, RISCV::X30, RISCV::X31}; 8357 8358 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8359 if (unsigned Reg = State.AllocateReg(GPRList)) { 8360 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8361 return false; 8362 } 8363 } 8364 8365 if (LocVT == MVT::f16) { 8366 static const MCPhysReg FPR16List[] = { 8367 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8368 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8369 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8370 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8371 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8372 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8373 return false; 8374 } 8375 } 8376 8377 if (LocVT == MVT::f32) { 8378 static const MCPhysReg FPR32List[] = { 8379 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8380 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8381 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8382 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8383 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8384 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8385 return false; 8386 } 8387 } 8388 8389 if (LocVT == MVT::f64) { 8390 static const MCPhysReg FPR64List[] = { 8391 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8392 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8393 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8394 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8395 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8396 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8397 return false; 8398 } 8399 } 8400 8401 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8402 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8403 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8404 return false; 8405 } 8406 8407 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8408 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8409 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8410 return false; 8411 } 8412 8413 if (LocVT.isVector()) { 8414 if (unsigned Reg = 8415 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8416 // Fixed-length vectors are located in the corresponding scalable-vector 8417 // container types. 8418 if (ValVT.isFixedLengthVector()) 8419 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8420 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8421 } else { 8422 // Try and pass the address via a "fast" GPR. 8423 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8424 LocInfo = CCValAssign::Indirect; 8425 LocVT = TLI.getSubtarget().getXLenVT(); 8426 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8427 } else if (ValVT.isFixedLengthVector()) { 8428 auto StackAlign = 8429 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8430 unsigned StackOffset = 8431 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8432 State.addLoc( 8433 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8434 } else { 8435 // Can't pass scalable vectors on the stack. 8436 return true; 8437 } 8438 } 8439 8440 return false; 8441 } 8442 8443 return true; // CC didn't match. 8444 } 8445 8446 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8447 CCValAssign::LocInfo LocInfo, 8448 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8449 8450 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8451 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8452 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8453 static const MCPhysReg GPRList[] = { 8454 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8455 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8456 if (unsigned Reg = State.AllocateReg(GPRList)) { 8457 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8458 return false; 8459 } 8460 } 8461 8462 if (LocVT == MVT::f32) { 8463 // Pass in STG registers: F1, ..., F6 8464 // fs0 ... fs5 8465 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8466 RISCV::F18_F, RISCV::F19_F, 8467 RISCV::F20_F, RISCV::F21_F}; 8468 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8469 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8470 return false; 8471 } 8472 } 8473 8474 if (LocVT == MVT::f64) { 8475 // Pass in STG registers: D1, ..., D6 8476 // fs6 ... fs11 8477 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8478 RISCV::F24_D, RISCV::F25_D, 8479 RISCV::F26_D, RISCV::F27_D}; 8480 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8481 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8482 return false; 8483 } 8484 } 8485 8486 report_fatal_error("No registers left in GHC calling convention"); 8487 return true; 8488 } 8489 8490 // Transform physical registers into virtual registers. 8491 SDValue RISCVTargetLowering::LowerFormalArguments( 8492 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8493 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8494 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8495 8496 MachineFunction &MF = DAG.getMachineFunction(); 8497 8498 switch (CallConv) { 8499 default: 8500 report_fatal_error("Unsupported calling convention"); 8501 case CallingConv::C: 8502 case CallingConv::Fast: 8503 break; 8504 case CallingConv::GHC: 8505 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8506 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8507 report_fatal_error( 8508 "GHC calling convention requires the F and D instruction set extensions"); 8509 } 8510 8511 const Function &Func = MF.getFunction(); 8512 if (Func.hasFnAttribute("interrupt")) { 8513 if (!Func.arg_empty()) 8514 report_fatal_error( 8515 "Functions with the interrupt attribute cannot have arguments!"); 8516 8517 StringRef Kind = 8518 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8519 8520 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8521 report_fatal_error( 8522 "Function interrupt attribute argument not supported!"); 8523 } 8524 8525 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8526 MVT XLenVT = Subtarget.getXLenVT(); 8527 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8528 // Used with vargs to acumulate store chains. 8529 std::vector<SDValue> OutChains; 8530 8531 // Assign locations to all of the incoming arguments. 8532 SmallVector<CCValAssign, 16> ArgLocs; 8533 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8534 8535 if (CallConv == CallingConv::GHC) 8536 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8537 else 8538 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8539 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8540 : CC_RISCV); 8541 8542 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8543 CCValAssign &VA = ArgLocs[i]; 8544 SDValue ArgValue; 8545 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8546 // case. 8547 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8548 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8549 else if (VA.isRegLoc()) 8550 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8551 else 8552 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8553 8554 if (VA.getLocInfo() == CCValAssign::Indirect) { 8555 // If the original argument was split and passed by reference (e.g. i128 8556 // on RV32), we need to load all parts of it here (using the same 8557 // address). Vectors may be partly split to registers and partly to the 8558 // stack, in which case the base address is partly offset and subsequent 8559 // stores are relative to that. 8560 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8561 MachinePointerInfo())); 8562 unsigned ArgIndex = Ins[i].OrigArgIndex; 8563 unsigned ArgPartOffset = Ins[i].PartOffset; 8564 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8565 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8566 CCValAssign &PartVA = ArgLocs[i + 1]; 8567 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8568 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8569 if (PartVA.getValVT().isScalableVector()) 8570 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8571 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8572 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8573 MachinePointerInfo())); 8574 ++i; 8575 } 8576 continue; 8577 } 8578 InVals.push_back(ArgValue); 8579 } 8580 8581 if (IsVarArg) { 8582 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8583 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8584 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8585 MachineFrameInfo &MFI = MF.getFrameInfo(); 8586 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8587 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8588 8589 // Offset of the first variable argument from stack pointer, and size of 8590 // the vararg save area. For now, the varargs save area is either zero or 8591 // large enough to hold a0-a7. 8592 int VaArgOffset, VarArgsSaveSize; 8593 8594 // If all registers are allocated, then all varargs must be passed on the 8595 // stack and we don't need to save any argregs. 8596 if (ArgRegs.size() == Idx) { 8597 VaArgOffset = CCInfo.getNextStackOffset(); 8598 VarArgsSaveSize = 0; 8599 } else { 8600 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8601 VaArgOffset = -VarArgsSaveSize; 8602 } 8603 8604 // Record the frame index of the first variable argument 8605 // which is a value necessary to VASTART. 8606 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8607 RVFI->setVarArgsFrameIndex(FI); 8608 8609 // If saving an odd number of registers then create an extra stack slot to 8610 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8611 // offsets to even-numbered registered remain 2*XLEN-aligned. 8612 if (Idx % 2) { 8613 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8614 VarArgsSaveSize += XLenInBytes; 8615 } 8616 8617 // Copy the integer registers that may have been used for passing varargs 8618 // to the vararg save area. 8619 for (unsigned I = Idx; I < ArgRegs.size(); 8620 ++I, VaArgOffset += XLenInBytes) { 8621 const Register Reg = RegInfo.createVirtualRegister(RC); 8622 RegInfo.addLiveIn(ArgRegs[I], Reg); 8623 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8624 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8625 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8626 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8627 MachinePointerInfo::getFixedStack(MF, FI)); 8628 cast<StoreSDNode>(Store.getNode()) 8629 ->getMemOperand() 8630 ->setValue((Value *)nullptr); 8631 OutChains.push_back(Store); 8632 } 8633 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8634 } 8635 8636 // All stores are grouped in one node to allow the matching between 8637 // the size of Ins and InVals. This only happens for vararg functions. 8638 if (!OutChains.empty()) { 8639 OutChains.push_back(Chain); 8640 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8641 } 8642 8643 return Chain; 8644 } 8645 8646 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8647 /// for tail call optimization. 8648 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8649 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8650 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8651 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8652 8653 auto &Callee = CLI.Callee; 8654 auto CalleeCC = CLI.CallConv; 8655 auto &Outs = CLI.Outs; 8656 auto &Caller = MF.getFunction(); 8657 auto CallerCC = Caller.getCallingConv(); 8658 8659 // Exception-handling functions need a special set of instructions to 8660 // indicate a return to the hardware. Tail-calling another function would 8661 // probably break this. 8662 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8663 // should be expanded as new function attributes are introduced. 8664 if (Caller.hasFnAttribute("interrupt")) 8665 return false; 8666 8667 // Do not tail call opt if the stack is used to pass parameters. 8668 if (CCInfo.getNextStackOffset() != 0) 8669 return false; 8670 8671 // Do not tail call opt if any parameters need to be passed indirectly. 8672 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 8673 // passed indirectly. So the address of the value will be passed in a 8674 // register, or if not available, then the address is put on the stack. In 8675 // order to pass indirectly, space on the stack often needs to be allocated 8676 // in order to store the value. In this case the CCInfo.getNextStackOffset() 8677 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 8678 // are passed CCValAssign::Indirect. 8679 for (auto &VA : ArgLocs) 8680 if (VA.getLocInfo() == CCValAssign::Indirect) 8681 return false; 8682 8683 // Do not tail call opt if either caller or callee uses struct return 8684 // semantics. 8685 auto IsCallerStructRet = Caller.hasStructRetAttr(); 8686 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 8687 if (IsCallerStructRet || IsCalleeStructRet) 8688 return false; 8689 8690 // Externally-defined functions with weak linkage should not be 8691 // tail-called. The behaviour of branch instructions in this situation (as 8692 // used for tail calls) is implementation-defined, so we cannot rely on the 8693 // linker replacing the tail call with a return. 8694 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 8695 const GlobalValue *GV = G->getGlobal(); 8696 if (GV->hasExternalWeakLinkage()) 8697 return false; 8698 } 8699 8700 // The callee has to preserve all registers the caller needs to preserve. 8701 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8702 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 8703 if (CalleeCC != CallerCC) { 8704 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 8705 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 8706 return false; 8707 } 8708 8709 // Byval parameters hand the function a pointer directly into the stack area 8710 // we want to reuse during a tail call. Working around this *is* possible 8711 // but less efficient and uglier in LowerCall. 8712 for (auto &Arg : Outs) 8713 if (Arg.Flags.isByVal()) 8714 return false; 8715 8716 return true; 8717 } 8718 8719 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 8720 return DAG.getDataLayout().getPrefTypeAlign( 8721 VT.getTypeForEVT(*DAG.getContext())); 8722 } 8723 8724 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 8725 // and output parameter nodes. 8726 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 8727 SmallVectorImpl<SDValue> &InVals) const { 8728 SelectionDAG &DAG = CLI.DAG; 8729 SDLoc &DL = CLI.DL; 8730 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 8731 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 8732 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 8733 SDValue Chain = CLI.Chain; 8734 SDValue Callee = CLI.Callee; 8735 bool &IsTailCall = CLI.IsTailCall; 8736 CallingConv::ID CallConv = CLI.CallConv; 8737 bool IsVarArg = CLI.IsVarArg; 8738 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8739 MVT XLenVT = Subtarget.getXLenVT(); 8740 8741 MachineFunction &MF = DAG.getMachineFunction(); 8742 8743 // Analyze the operands of the call, assigning locations to each operand. 8744 SmallVector<CCValAssign, 16> ArgLocs; 8745 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8746 8747 if (CallConv == CallingConv::GHC) 8748 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 8749 else 8750 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 8751 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8752 : CC_RISCV); 8753 8754 // Check if it's really possible to do a tail call. 8755 if (IsTailCall) 8756 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 8757 8758 if (IsTailCall) 8759 ++NumTailCalls; 8760 else if (CLI.CB && CLI.CB->isMustTailCall()) 8761 report_fatal_error("failed to perform tail call elimination on a call " 8762 "site marked musttail"); 8763 8764 // Get a count of how many bytes are to be pushed on the stack. 8765 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 8766 8767 // Create local copies for byval args 8768 SmallVector<SDValue, 8> ByValArgs; 8769 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8770 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8771 if (!Flags.isByVal()) 8772 continue; 8773 8774 SDValue Arg = OutVals[i]; 8775 unsigned Size = Flags.getByValSize(); 8776 Align Alignment = Flags.getNonZeroByValAlign(); 8777 8778 int FI = 8779 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 8780 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8781 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 8782 8783 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 8784 /*IsVolatile=*/false, 8785 /*AlwaysInline=*/false, IsTailCall, 8786 MachinePointerInfo(), MachinePointerInfo()); 8787 ByValArgs.push_back(FIPtr); 8788 } 8789 8790 if (!IsTailCall) 8791 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 8792 8793 // Copy argument values to their designated locations. 8794 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 8795 SmallVector<SDValue, 8> MemOpChains; 8796 SDValue StackPtr; 8797 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 8798 CCValAssign &VA = ArgLocs[i]; 8799 SDValue ArgValue = OutVals[i]; 8800 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8801 8802 // Handle passing f64 on RV32D with a soft float ABI as a special case. 8803 bool IsF64OnRV32DSoftABI = 8804 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 8805 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 8806 SDValue SplitF64 = DAG.getNode( 8807 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 8808 SDValue Lo = SplitF64.getValue(0); 8809 SDValue Hi = SplitF64.getValue(1); 8810 8811 Register RegLo = VA.getLocReg(); 8812 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 8813 8814 if (RegLo == RISCV::X17) { 8815 // Second half of f64 is passed on the stack. 8816 // Work out the address of the stack slot. 8817 if (!StackPtr.getNode()) 8818 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8819 // Emit the store. 8820 MemOpChains.push_back( 8821 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 8822 } else { 8823 // Second half of f64 is passed in another GPR. 8824 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8825 Register RegHigh = RegLo + 1; 8826 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 8827 } 8828 continue; 8829 } 8830 8831 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 8832 // as any other MemLoc. 8833 8834 // Promote the value if needed. 8835 // For now, only handle fully promoted and indirect arguments. 8836 if (VA.getLocInfo() == CCValAssign::Indirect) { 8837 // Store the argument in a stack slot and pass its address. 8838 Align StackAlign = 8839 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 8840 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 8841 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 8842 // If the original argument was split (e.g. i128), we need 8843 // to store the required parts of it here (and pass just one address). 8844 // Vectors may be partly split to registers and partly to the stack, in 8845 // which case the base address is partly offset and subsequent stores are 8846 // relative to that. 8847 unsigned ArgIndex = Outs[i].OrigArgIndex; 8848 unsigned ArgPartOffset = Outs[i].PartOffset; 8849 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8850 // Calculate the total size to store. We don't have access to what we're 8851 // actually storing other than performing the loop and collecting the 8852 // info. 8853 SmallVector<std::pair<SDValue, SDValue>> Parts; 8854 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 8855 SDValue PartValue = OutVals[i + 1]; 8856 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 8857 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8858 EVT PartVT = PartValue.getValueType(); 8859 if (PartVT.isScalableVector()) 8860 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8861 StoredSize += PartVT.getStoreSize(); 8862 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 8863 Parts.push_back(std::make_pair(PartValue, Offset)); 8864 ++i; 8865 } 8866 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 8867 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 8868 MemOpChains.push_back( 8869 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 8870 MachinePointerInfo::getFixedStack(MF, FI))); 8871 for (const auto &Part : Parts) { 8872 SDValue PartValue = Part.first; 8873 SDValue PartOffset = Part.second; 8874 SDValue Address = 8875 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 8876 MemOpChains.push_back( 8877 DAG.getStore(Chain, DL, PartValue, Address, 8878 MachinePointerInfo::getFixedStack(MF, FI))); 8879 } 8880 ArgValue = SpillSlot; 8881 } else { 8882 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 8883 } 8884 8885 // Use local copy if it is a byval arg. 8886 if (Flags.isByVal()) 8887 ArgValue = ByValArgs[j++]; 8888 8889 if (VA.isRegLoc()) { 8890 // Queue up the argument copies and emit them at the end. 8891 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 8892 } else { 8893 assert(VA.isMemLoc() && "Argument not register or memory"); 8894 assert(!IsTailCall && "Tail call not allowed if stack is used " 8895 "for passing parameters"); 8896 8897 // Work out the address of the stack slot. 8898 if (!StackPtr.getNode()) 8899 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8900 SDValue Address = 8901 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 8902 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 8903 8904 // Emit the store. 8905 MemOpChains.push_back( 8906 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 8907 } 8908 } 8909 8910 // Join the stores, which are independent of one another. 8911 if (!MemOpChains.empty()) 8912 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 8913 8914 SDValue Glue; 8915 8916 // Build a sequence of copy-to-reg nodes, chained and glued together. 8917 for (auto &Reg : RegsToPass) { 8918 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 8919 Glue = Chain.getValue(1); 8920 } 8921 8922 // Validate that none of the argument registers have been marked as 8923 // reserved, if so report an error. Do the same for the return address if this 8924 // is not a tailcall. 8925 validateCCReservedRegs(RegsToPass, MF); 8926 if (!IsTailCall && 8927 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 8928 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8929 MF.getFunction(), 8930 "Return address register required, but has been reserved."}); 8931 8932 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 8933 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 8934 // split it and then direct call can be matched by PseudoCALL. 8935 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 8936 const GlobalValue *GV = S->getGlobal(); 8937 8938 unsigned OpFlags = RISCVII::MO_CALL; 8939 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 8940 OpFlags = RISCVII::MO_PLT; 8941 8942 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 8943 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 8944 unsigned OpFlags = RISCVII::MO_CALL; 8945 8946 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 8947 nullptr)) 8948 OpFlags = RISCVII::MO_PLT; 8949 8950 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 8951 } 8952 8953 // The first call operand is the chain and the second is the target address. 8954 SmallVector<SDValue, 8> Ops; 8955 Ops.push_back(Chain); 8956 Ops.push_back(Callee); 8957 8958 // Add argument registers to the end of the list so that they are 8959 // known live into the call. 8960 for (auto &Reg : RegsToPass) 8961 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 8962 8963 if (!IsTailCall) { 8964 // Add a register mask operand representing the call-preserved registers. 8965 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8966 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 8967 assert(Mask && "Missing call preserved mask for calling convention"); 8968 Ops.push_back(DAG.getRegisterMask(Mask)); 8969 } 8970 8971 // Glue the call to the argument copies, if any. 8972 if (Glue.getNode()) 8973 Ops.push_back(Glue); 8974 8975 // Emit the call. 8976 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8977 8978 if (IsTailCall) { 8979 MF.getFrameInfo().setHasTailCall(); 8980 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 8981 } 8982 8983 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 8984 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 8985 Glue = Chain.getValue(1); 8986 8987 // Mark the end of the call, which is glued to the call itself. 8988 Chain = DAG.getCALLSEQ_END(Chain, 8989 DAG.getConstant(NumBytes, DL, PtrVT, true), 8990 DAG.getConstant(0, DL, PtrVT, true), 8991 Glue, DL); 8992 Glue = Chain.getValue(1); 8993 8994 // Assign locations to each value returned by this call. 8995 SmallVector<CCValAssign, 16> RVLocs; 8996 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 8997 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 8998 8999 // Copy all of the result registers out of their specified physreg. 9000 for (auto &VA : RVLocs) { 9001 // Copy the value out 9002 SDValue RetValue = 9003 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9004 // Glue the RetValue to the end of the call sequence 9005 Chain = RetValue.getValue(1); 9006 Glue = RetValue.getValue(2); 9007 9008 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9009 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9010 SDValue RetValue2 = 9011 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9012 Chain = RetValue2.getValue(1); 9013 Glue = RetValue2.getValue(2); 9014 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9015 RetValue2); 9016 } 9017 9018 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9019 9020 InVals.push_back(RetValue); 9021 } 9022 9023 return Chain; 9024 } 9025 9026 bool RISCVTargetLowering::CanLowerReturn( 9027 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9028 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9029 SmallVector<CCValAssign, 16> RVLocs; 9030 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9031 9032 Optional<unsigned> FirstMaskArgument; 9033 if (Subtarget.hasVInstructions()) 9034 FirstMaskArgument = preAssignMask(Outs); 9035 9036 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9037 MVT VT = Outs[i].VT; 9038 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9039 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9040 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9041 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9042 *this, FirstMaskArgument)) 9043 return false; 9044 } 9045 return true; 9046 } 9047 9048 SDValue 9049 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9050 bool IsVarArg, 9051 const SmallVectorImpl<ISD::OutputArg> &Outs, 9052 const SmallVectorImpl<SDValue> &OutVals, 9053 const SDLoc &DL, SelectionDAG &DAG) const { 9054 const MachineFunction &MF = DAG.getMachineFunction(); 9055 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9056 9057 // Stores the assignment of the return value to a location. 9058 SmallVector<CCValAssign, 16> RVLocs; 9059 9060 // Info about the registers and stack slot. 9061 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9062 *DAG.getContext()); 9063 9064 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9065 nullptr, CC_RISCV); 9066 9067 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9068 report_fatal_error("GHC functions return void only"); 9069 9070 SDValue Glue; 9071 SmallVector<SDValue, 4> RetOps(1, Chain); 9072 9073 // Copy the result values into the output registers. 9074 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9075 SDValue Val = OutVals[i]; 9076 CCValAssign &VA = RVLocs[i]; 9077 assert(VA.isRegLoc() && "Can only return in registers!"); 9078 9079 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9080 // Handle returning f64 on RV32D with a soft float ABI. 9081 assert(VA.isRegLoc() && "Expected return via registers"); 9082 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9083 DAG.getVTList(MVT::i32, MVT::i32), Val); 9084 SDValue Lo = SplitF64.getValue(0); 9085 SDValue Hi = SplitF64.getValue(1); 9086 Register RegLo = VA.getLocReg(); 9087 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9088 Register RegHi = RegLo + 1; 9089 9090 if (STI.isRegisterReservedByUser(RegLo) || 9091 STI.isRegisterReservedByUser(RegHi)) 9092 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9093 MF.getFunction(), 9094 "Return value register required, but has been reserved."}); 9095 9096 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9097 Glue = Chain.getValue(1); 9098 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9099 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9100 Glue = Chain.getValue(1); 9101 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9102 } else { 9103 // Handle a 'normal' return. 9104 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9105 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9106 9107 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9108 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9109 MF.getFunction(), 9110 "Return value register required, but has been reserved."}); 9111 9112 // Guarantee that all emitted copies are stuck together. 9113 Glue = Chain.getValue(1); 9114 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9115 } 9116 } 9117 9118 RetOps[0] = Chain; // Update chain. 9119 9120 // Add the glue node if we have it. 9121 if (Glue.getNode()) { 9122 RetOps.push_back(Glue); 9123 } 9124 9125 unsigned RetOpc = RISCVISD::RET_FLAG; 9126 // Interrupt service routines use different return instructions. 9127 const Function &Func = DAG.getMachineFunction().getFunction(); 9128 if (Func.hasFnAttribute("interrupt")) { 9129 if (!Func.getReturnType()->isVoidTy()) 9130 report_fatal_error( 9131 "Functions with the interrupt attribute must have void return type!"); 9132 9133 MachineFunction &MF = DAG.getMachineFunction(); 9134 StringRef Kind = 9135 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9136 9137 if (Kind == "user") 9138 RetOpc = RISCVISD::URET_FLAG; 9139 else if (Kind == "supervisor") 9140 RetOpc = RISCVISD::SRET_FLAG; 9141 else 9142 RetOpc = RISCVISD::MRET_FLAG; 9143 } 9144 9145 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9146 } 9147 9148 void RISCVTargetLowering::validateCCReservedRegs( 9149 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9150 MachineFunction &MF) const { 9151 const Function &F = MF.getFunction(); 9152 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9153 9154 if (llvm::any_of(Regs, [&STI](auto Reg) { 9155 return STI.isRegisterReservedByUser(Reg.first); 9156 })) 9157 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9158 F, "Argument register required, but has been reserved."}); 9159 } 9160 9161 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9162 return CI->isTailCall(); 9163 } 9164 9165 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9166 #define NODE_NAME_CASE(NODE) \ 9167 case RISCVISD::NODE: \ 9168 return "RISCVISD::" #NODE; 9169 // clang-format off 9170 switch ((RISCVISD::NodeType)Opcode) { 9171 case RISCVISD::FIRST_NUMBER: 9172 break; 9173 NODE_NAME_CASE(RET_FLAG) 9174 NODE_NAME_CASE(URET_FLAG) 9175 NODE_NAME_CASE(SRET_FLAG) 9176 NODE_NAME_CASE(MRET_FLAG) 9177 NODE_NAME_CASE(CALL) 9178 NODE_NAME_CASE(SELECT_CC) 9179 NODE_NAME_CASE(BR_CC) 9180 NODE_NAME_CASE(BuildPairF64) 9181 NODE_NAME_CASE(SplitF64) 9182 NODE_NAME_CASE(TAIL) 9183 NODE_NAME_CASE(MULHSU) 9184 NODE_NAME_CASE(SLLW) 9185 NODE_NAME_CASE(SRAW) 9186 NODE_NAME_CASE(SRLW) 9187 NODE_NAME_CASE(DIVW) 9188 NODE_NAME_CASE(DIVUW) 9189 NODE_NAME_CASE(REMUW) 9190 NODE_NAME_CASE(ROLW) 9191 NODE_NAME_CASE(RORW) 9192 NODE_NAME_CASE(CLZW) 9193 NODE_NAME_CASE(CTZW) 9194 NODE_NAME_CASE(FSLW) 9195 NODE_NAME_CASE(FSRW) 9196 NODE_NAME_CASE(FSL) 9197 NODE_NAME_CASE(FSR) 9198 NODE_NAME_CASE(FMV_H_X) 9199 NODE_NAME_CASE(FMV_X_ANYEXTH) 9200 NODE_NAME_CASE(FMV_W_X_RV64) 9201 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9202 NODE_NAME_CASE(FCVT_X_RTZ) 9203 NODE_NAME_CASE(FCVT_XU_RTZ) 9204 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9205 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9206 NODE_NAME_CASE(READ_CYCLE_WIDE) 9207 NODE_NAME_CASE(GREV) 9208 NODE_NAME_CASE(GREVW) 9209 NODE_NAME_CASE(GORC) 9210 NODE_NAME_CASE(GORCW) 9211 NODE_NAME_CASE(SHFL) 9212 NODE_NAME_CASE(SHFLW) 9213 NODE_NAME_CASE(UNSHFL) 9214 NODE_NAME_CASE(UNSHFLW) 9215 NODE_NAME_CASE(BCOMPRESS) 9216 NODE_NAME_CASE(BCOMPRESSW) 9217 NODE_NAME_CASE(BDECOMPRESS) 9218 NODE_NAME_CASE(BDECOMPRESSW) 9219 NODE_NAME_CASE(VMV_V_X_VL) 9220 NODE_NAME_CASE(VFMV_V_F_VL) 9221 NODE_NAME_CASE(VMV_X_S) 9222 NODE_NAME_CASE(VMV_S_X_VL) 9223 NODE_NAME_CASE(VFMV_S_F_VL) 9224 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9225 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9226 NODE_NAME_CASE(READ_VLENB) 9227 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9228 NODE_NAME_CASE(VSLIDEUP_VL) 9229 NODE_NAME_CASE(VSLIDE1UP_VL) 9230 NODE_NAME_CASE(VSLIDEDOWN_VL) 9231 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9232 NODE_NAME_CASE(VID_VL) 9233 NODE_NAME_CASE(VFNCVT_ROD_VL) 9234 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9235 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9236 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9237 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9238 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9239 NODE_NAME_CASE(VECREDUCE_AND_VL) 9240 NODE_NAME_CASE(VECREDUCE_OR_VL) 9241 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9242 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9243 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9244 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9245 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9246 NODE_NAME_CASE(ADD_VL) 9247 NODE_NAME_CASE(AND_VL) 9248 NODE_NAME_CASE(MUL_VL) 9249 NODE_NAME_CASE(OR_VL) 9250 NODE_NAME_CASE(SDIV_VL) 9251 NODE_NAME_CASE(SHL_VL) 9252 NODE_NAME_CASE(SREM_VL) 9253 NODE_NAME_CASE(SRA_VL) 9254 NODE_NAME_CASE(SRL_VL) 9255 NODE_NAME_CASE(SUB_VL) 9256 NODE_NAME_CASE(UDIV_VL) 9257 NODE_NAME_CASE(UREM_VL) 9258 NODE_NAME_CASE(XOR_VL) 9259 NODE_NAME_CASE(SADDSAT_VL) 9260 NODE_NAME_CASE(UADDSAT_VL) 9261 NODE_NAME_CASE(SSUBSAT_VL) 9262 NODE_NAME_CASE(USUBSAT_VL) 9263 NODE_NAME_CASE(FADD_VL) 9264 NODE_NAME_CASE(FSUB_VL) 9265 NODE_NAME_CASE(FMUL_VL) 9266 NODE_NAME_CASE(FDIV_VL) 9267 NODE_NAME_CASE(FNEG_VL) 9268 NODE_NAME_CASE(FABS_VL) 9269 NODE_NAME_CASE(FSQRT_VL) 9270 NODE_NAME_CASE(FMA_VL) 9271 NODE_NAME_CASE(FCOPYSIGN_VL) 9272 NODE_NAME_CASE(SMIN_VL) 9273 NODE_NAME_CASE(SMAX_VL) 9274 NODE_NAME_CASE(UMIN_VL) 9275 NODE_NAME_CASE(UMAX_VL) 9276 NODE_NAME_CASE(FMINNUM_VL) 9277 NODE_NAME_CASE(FMAXNUM_VL) 9278 NODE_NAME_CASE(MULHS_VL) 9279 NODE_NAME_CASE(MULHU_VL) 9280 NODE_NAME_CASE(FP_TO_SINT_VL) 9281 NODE_NAME_CASE(FP_TO_UINT_VL) 9282 NODE_NAME_CASE(SINT_TO_FP_VL) 9283 NODE_NAME_CASE(UINT_TO_FP_VL) 9284 NODE_NAME_CASE(FP_EXTEND_VL) 9285 NODE_NAME_CASE(FP_ROUND_VL) 9286 NODE_NAME_CASE(VWMUL_VL) 9287 NODE_NAME_CASE(VWMULU_VL) 9288 NODE_NAME_CASE(SETCC_VL) 9289 NODE_NAME_CASE(VSELECT_VL) 9290 NODE_NAME_CASE(VMAND_VL) 9291 NODE_NAME_CASE(VMOR_VL) 9292 NODE_NAME_CASE(VMXOR_VL) 9293 NODE_NAME_CASE(VMCLR_VL) 9294 NODE_NAME_CASE(VMSET_VL) 9295 NODE_NAME_CASE(VRGATHER_VX_VL) 9296 NODE_NAME_CASE(VRGATHER_VV_VL) 9297 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9298 NODE_NAME_CASE(VSEXT_VL) 9299 NODE_NAME_CASE(VZEXT_VL) 9300 NODE_NAME_CASE(VCPOP_VL) 9301 NODE_NAME_CASE(VLE_VL) 9302 NODE_NAME_CASE(VSE_VL) 9303 NODE_NAME_CASE(READ_CSR) 9304 NODE_NAME_CASE(WRITE_CSR) 9305 NODE_NAME_CASE(SWAP_CSR) 9306 } 9307 // clang-format on 9308 return nullptr; 9309 #undef NODE_NAME_CASE 9310 } 9311 9312 /// getConstraintType - Given a constraint letter, return the type of 9313 /// constraint it is for this target. 9314 RISCVTargetLowering::ConstraintType 9315 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9316 if (Constraint.size() == 1) { 9317 switch (Constraint[0]) { 9318 default: 9319 break; 9320 case 'f': 9321 return C_RegisterClass; 9322 case 'I': 9323 case 'J': 9324 case 'K': 9325 return C_Immediate; 9326 case 'A': 9327 return C_Memory; 9328 case 'S': // A symbolic address 9329 return C_Other; 9330 } 9331 } else { 9332 if (Constraint == "vr" || Constraint == "vm") 9333 return C_RegisterClass; 9334 } 9335 return TargetLowering::getConstraintType(Constraint); 9336 } 9337 9338 std::pair<unsigned, const TargetRegisterClass *> 9339 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9340 StringRef Constraint, 9341 MVT VT) const { 9342 // First, see if this is a constraint that directly corresponds to a 9343 // RISCV register class. 9344 if (Constraint.size() == 1) { 9345 switch (Constraint[0]) { 9346 case 'r': 9347 return std::make_pair(0U, &RISCV::GPRRegClass); 9348 case 'f': 9349 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9350 return std::make_pair(0U, &RISCV::FPR16RegClass); 9351 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9352 return std::make_pair(0U, &RISCV::FPR32RegClass); 9353 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9354 return std::make_pair(0U, &RISCV::FPR64RegClass); 9355 break; 9356 default: 9357 break; 9358 } 9359 } else { 9360 if (Constraint == "vr") { 9361 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9362 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9363 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9364 return std::make_pair(0U, RC); 9365 } 9366 } else if (Constraint == "vm") { 9367 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9368 return std::make_pair(0U, &RISCV::VMRegClass); 9369 } 9370 } 9371 9372 // Clang will correctly decode the usage of register name aliases into their 9373 // official names. However, other frontends like `rustc` do not. This allows 9374 // users of these frontends to use the ABI names for registers in LLVM-style 9375 // register constraints. 9376 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9377 .Case("{zero}", RISCV::X0) 9378 .Case("{ra}", RISCV::X1) 9379 .Case("{sp}", RISCV::X2) 9380 .Case("{gp}", RISCV::X3) 9381 .Case("{tp}", RISCV::X4) 9382 .Case("{t0}", RISCV::X5) 9383 .Case("{t1}", RISCV::X6) 9384 .Case("{t2}", RISCV::X7) 9385 .Cases("{s0}", "{fp}", RISCV::X8) 9386 .Case("{s1}", RISCV::X9) 9387 .Case("{a0}", RISCV::X10) 9388 .Case("{a1}", RISCV::X11) 9389 .Case("{a2}", RISCV::X12) 9390 .Case("{a3}", RISCV::X13) 9391 .Case("{a4}", RISCV::X14) 9392 .Case("{a5}", RISCV::X15) 9393 .Case("{a6}", RISCV::X16) 9394 .Case("{a7}", RISCV::X17) 9395 .Case("{s2}", RISCV::X18) 9396 .Case("{s3}", RISCV::X19) 9397 .Case("{s4}", RISCV::X20) 9398 .Case("{s5}", RISCV::X21) 9399 .Case("{s6}", RISCV::X22) 9400 .Case("{s7}", RISCV::X23) 9401 .Case("{s8}", RISCV::X24) 9402 .Case("{s9}", RISCV::X25) 9403 .Case("{s10}", RISCV::X26) 9404 .Case("{s11}", RISCV::X27) 9405 .Case("{t3}", RISCV::X28) 9406 .Case("{t4}", RISCV::X29) 9407 .Case("{t5}", RISCV::X30) 9408 .Case("{t6}", RISCV::X31) 9409 .Default(RISCV::NoRegister); 9410 if (XRegFromAlias != RISCV::NoRegister) 9411 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9412 9413 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9414 // TableGen record rather than the AsmName to choose registers for InlineAsm 9415 // constraints, plus we want to match those names to the widest floating point 9416 // register type available, manually select floating point registers here. 9417 // 9418 // The second case is the ABI name of the register, so that frontends can also 9419 // use the ABI names in register constraint lists. 9420 if (Subtarget.hasStdExtF()) { 9421 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9422 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9423 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9424 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9425 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9426 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9427 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9428 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9429 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9430 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9431 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9432 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9433 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9434 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9435 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9436 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9437 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9438 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9439 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9440 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9441 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9442 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9443 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9444 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9445 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9446 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9447 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9448 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9449 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9450 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9451 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9452 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9453 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9454 .Default(RISCV::NoRegister); 9455 if (FReg != RISCV::NoRegister) { 9456 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9457 if (Subtarget.hasStdExtD()) { 9458 unsigned RegNo = FReg - RISCV::F0_F; 9459 unsigned DReg = RISCV::F0_D + RegNo; 9460 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9461 } 9462 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9463 } 9464 } 9465 9466 if (Subtarget.hasVInstructions()) { 9467 Register VReg = StringSwitch<Register>(Constraint.lower()) 9468 .Case("{v0}", RISCV::V0) 9469 .Case("{v1}", RISCV::V1) 9470 .Case("{v2}", RISCV::V2) 9471 .Case("{v3}", RISCV::V3) 9472 .Case("{v4}", RISCV::V4) 9473 .Case("{v5}", RISCV::V5) 9474 .Case("{v6}", RISCV::V6) 9475 .Case("{v7}", RISCV::V7) 9476 .Case("{v8}", RISCV::V8) 9477 .Case("{v9}", RISCV::V9) 9478 .Case("{v10}", RISCV::V10) 9479 .Case("{v11}", RISCV::V11) 9480 .Case("{v12}", RISCV::V12) 9481 .Case("{v13}", RISCV::V13) 9482 .Case("{v14}", RISCV::V14) 9483 .Case("{v15}", RISCV::V15) 9484 .Case("{v16}", RISCV::V16) 9485 .Case("{v17}", RISCV::V17) 9486 .Case("{v18}", RISCV::V18) 9487 .Case("{v19}", RISCV::V19) 9488 .Case("{v20}", RISCV::V20) 9489 .Case("{v21}", RISCV::V21) 9490 .Case("{v22}", RISCV::V22) 9491 .Case("{v23}", RISCV::V23) 9492 .Case("{v24}", RISCV::V24) 9493 .Case("{v25}", RISCV::V25) 9494 .Case("{v26}", RISCV::V26) 9495 .Case("{v27}", RISCV::V27) 9496 .Case("{v28}", RISCV::V28) 9497 .Case("{v29}", RISCV::V29) 9498 .Case("{v30}", RISCV::V30) 9499 .Case("{v31}", RISCV::V31) 9500 .Default(RISCV::NoRegister); 9501 if (VReg != RISCV::NoRegister) { 9502 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9503 return std::make_pair(VReg, &RISCV::VMRegClass); 9504 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9505 return std::make_pair(VReg, &RISCV::VRRegClass); 9506 for (const auto *RC : 9507 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9508 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9509 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9510 return std::make_pair(VReg, RC); 9511 } 9512 } 9513 } 9514 } 9515 9516 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9517 } 9518 9519 unsigned 9520 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9521 // Currently only support length 1 constraints. 9522 if (ConstraintCode.size() == 1) { 9523 switch (ConstraintCode[0]) { 9524 case 'A': 9525 return InlineAsm::Constraint_A; 9526 default: 9527 break; 9528 } 9529 } 9530 9531 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9532 } 9533 9534 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9535 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9536 SelectionDAG &DAG) const { 9537 // Currently only support length 1 constraints. 9538 if (Constraint.length() == 1) { 9539 switch (Constraint[0]) { 9540 case 'I': 9541 // Validate & create a 12-bit signed immediate operand. 9542 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9543 uint64_t CVal = C->getSExtValue(); 9544 if (isInt<12>(CVal)) 9545 Ops.push_back( 9546 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9547 } 9548 return; 9549 case 'J': 9550 // Validate & create an integer zero operand. 9551 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9552 if (C->getZExtValue() == 0) 9553 Ops.push_back( 9554 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9555 return; 9556 case 'K': 9557 // Validate & create a 5-bit unsigned immediate operand. 9558 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9559 uint64_t CVal = C->getZExtValue(); 9560 if (isUInt<5>(CVal)) 9561 Ops.push_back( 9562 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9563 } 9564 return; 9565 case 'S': 9566 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9567 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9568 GA->getValueType(0))); 9569 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9570 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9571 BA->getValueType(0))); 9572 } 9573 return; 9574 default: 9575 break; 9576 } 9577 } 9578 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9579 } 9580 9581 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9582 Instruction *Inst, 9583 AtomicOrdering Ord) const { 9584 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9585 return Builder.CreateFence(Ord); 9586 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9587 return Builder.CreateFence(AtomicOrdering::Release); 9588 return nullptr; 9589 } 9590 9591 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9592 Instruction *Inst, 9593 AtomicOrdering Ord) const { 9594 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9595 return Builder.CreateFence(AtomicOrdering::Acquire); 9596 return nullptr; 9597 } 9598 9599 TargetLowering::AtomicExpansionKind 9600 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9601 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9602 // point operations can't be used in an lr/sc sequence without breaking the 9603 // forward-progress guarantee. 9604 if (AI->isFloatingPointOperation()) 9605 return AtomicExpansionKind::CmpXChg; 9606 9607 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9608 if (Size == 8 || Size == 16) 9609 return AtomicExpansionKind::MaskedIntrinsic; 9610 return AtomicExpansionKind::None; 9611 } 9612 9613 static Intrinsic::ID 9614 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9615 if (XLen == 32) { 9616 switch (BinOp) { 9617 default: 9618 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9619 case AtomicRMWInst::Xchg: 9620 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9621 case AtomicRMWInst::Add: 9622 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9623 case AtomicRMWInst::Sub: 9624 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9625 case AtomicRMWInst::Nand: 9626 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9627 case AtomicRMWInst::Max: 9628 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9629 case AtomicRMWInst::Min: 9630 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9631 case AtomicRMWInst::UMax: 9632 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9633 case AtomicRMWInst::UMin: 9634 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9635 } 9636 } 9637 9638 if (XLen == 64) { 9639 switch (BinOp) { 9640 default: 9641 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9642 case AtomicRMWInst::Xchg: 9643 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9644 case AtomicRMWInst::Add: 9645 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9646 case AtomicRMWInst::Sub: 9647 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9648 case AtomicRMWInst::Nand: 9649 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9650 case AtomicRMWInst::Max: 9651 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9652 case AtomicRMWInst::Min: 9653 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9654 case AtomicRMWInst::UMax: 9655 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9656 case AtomicRMWInst::UMin: 9657 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9658 } 9659 } 9660 9661 llvm_unreachable("Unexpected XLen\n"); 9662 } 9663 9664 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 9665 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 9666 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 9667 unsigned XLen = Subtarget.getXLen(); 9668 Value *Ordering = 9669 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 9670 Type *Tys[] = {AlignedAddr->getType()}; 9671 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 9672 AI->getModule(), 9673 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 9674 9675 if (XLen == 64) { 9676 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 9677 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9678 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 9679 } 9680 9681 Value *Result; 9682 9683 // Must pass the shift amount needed to sign extend the loaded value prior 9684 // to performing a signed comparison for min/max. ShiftAmt is the number of 9685 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 9686 // is the number of bits to left+right shift the value in order to 9687 // sign-extend. 9688 if (AI->getOperation() == AtomicRMWInst::Min || 9689 AI->getOperation() == AtomicRMWInst::Max) { 9690 const DataLayout &DL = AI->getModule()->getDataLayout(); 9691 unsigned ValWidth = 9692 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 9693 Value *SextShamt = 9694 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 9695 Result = Builder.CreateCall(LrwOpScwLoop, 9696 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 9697 } else { 9698 Result = 9699 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 9700 } 9701 9702 if (XLen == 64) 9703 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9704 return Result; 9705 } 9706 9707 TargetLowering::AtomicExpansionKind 9708 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 9709 AtomicCmpXchgInst *CI) const { 9710 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 9711 if (Size == 8 || Size == 16) 9712 return AtomicExpansionKind::MaskedIntrinsic; 9713 return AtomicExpansionKind::None; 9714 } 9715 9716 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 9717 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 9718 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 9719 unsigned XLen = Subtarget.getXLen(); 9720 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 9721 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 9722 if (XLen == 64) { 9723 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 9724 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 9725 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9726 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 9727 } 9728 Type *Tys[] = {AlignedAddr->getType()}; 9729 Function *MaskedCmpXchg = 9730 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 9731 Value *Result = Builder.CreateCall( 9732 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 9733 if (XLen == 64) 9734 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9735 return Result; 9736 } 9737 9738 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 9739 return false; 9740 } 9741 9742 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 9743 EVT VT) const { 9744 VT = VT.getScalarType(); 9745 9746 if (!VT.isSimple()) 9747 return false; 9748 9749 switch (VT.getSimpleVT().SimpleTy) { 9750 case MVT::f16: 9751 return Subtarget.hasStdExtZfh(); 9752 case MVT::f32: 9753 return Subtarget.hasStdExtF(); 9754 case MVT::f64: 9755 return Subtarget.hasStdExtD(); 9756 default: 9757 break; 9758 } 9759 9760 return false; 9761 } 9762 9763 Register RISCVTargetLowering::getExceptionPointerRegister( 9764 const Constant *PersonalityFn) const { 9765 return RISCV::X10; 9766 } 9767 9768 Register RISCVTargetLowering::getExceptionSelectorRegister( 9769 const Constant *PersonalityFn) const { 9770 return RISCV::X11; 9771 } 9772 9773 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 9774 // Return false to suppress the unnecessary extensions if the LibCall 9775 // arguments or return value is f32 type for LP64 ABI. 9776 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 9777 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 9778 return false; 9779 9780 return true; 9781 } 9782 9783 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 9784 if (Subtarget.is64Bit() && Type == MVT::i32) 9785 return true; 9786 9787 return IsSigned; 9788 } 9789 9790 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 9791 SDValue C) const { 9792 // Check integral scalar types. 9793 if (VT.isScalarInteger()) { 9794 // Omit the optimization if the sub target has the M extension and the data 9795 // size exceeds XLen. 9796 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 9797 return false; 9798 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 9799 // Break the MUL to a SLLI and an ADD/SUB. 9800 const APInt &Imm = ConstNode->getAPIntValue(); 9801 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 9802 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 9803 return true; 9804 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 9805 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 9806 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 9807 (Imm - 8).isPowerOf2())) 9808 return true; 9809 // Omit the following optimization if the sub target has the M extension 9810 // and the data size >= XLen. 9811 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 9812 return false; 9813 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 9814 // a pair of LUI/ADDI. 9815 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 9816 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 9817 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 9818 (1 - ImmS).isPowerOf2()) 9819 return true; 9820 } 9821 } 9822 } 9823 9824 return false; 9825 } 9826 9827 bool RISCVTargetLowering::isMulAddWithConstProfitable( 9828 const SDValue &AddNode, const SDValue &ConstNode) const { 9829 // Let the DAGCombiner decide for vectors. 9830 EVT VT = AddNode.getValueType(); 9831 if (VT.isVector()) 9832 return true; 9833 9834 // Let the DAGCombiner decide for larger types. 9835 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 9836 return true; 9837 9838 // It is worse if c1 is simm12 while c1*c2 is not. 9839 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 9840 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 9841 const APInt &C1 = C1Node->getAPIntValue(); 9842 const APInt &C2 = C2Node->getAPIntValue(); 9843 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 9844 return false; 9845 9846 // Default to true and let the DAGCombiner decide. 9847 return true; 9848 } 9849 9850 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 9851 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 9852 bool *Fast) const { 9853 if (!VT.isVector()) 9854 return false; 9855 9856 EVT ElemVT = VT.getVectorElementType(); 9857 if (Alignment >= ElemVT.getStoreSize()) { 9858 if (Fast) 9859 *Fast = true; 9860 return true; 9861 } 9862 9863 return false; 9864 } 9865 9866 bool RISCVTargetLowering::splitValueIntoRegisterParts( 9867 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 9868 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 9869 bool IsABIRegCopy = CC.hasValue(); 9870 EVT ValueVT = Val.getValueType(); 9871 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9872 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 9873 // and cast to f32. 9874 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 9875 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 9876 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 9877 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 9878 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 9879 Parts[0] = Val; 9880 return true; 9881 } 9882 9883 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9884 LLVMContext &Context = *DAG.getContext(); 9885 EVT ValueEltVT = ValueVT.getVectorElementType(); 9886 EVT PartEltVT = PartVT.getVectorElementType(); 9887 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9888 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9889 if (PartVTBitSize % ValueVTBitSize == 0) { 9890 // If the element types are different, bitcast to the same element type of 9891 // PartVT first. 9892 if (ValueEltVT != PartEltVT) { 9893 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9894 assert(Count != 0 && "The number of element should not be zero."); 9895 EVT SameEltTypeVT = 9896 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9897 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 9898 } 9899 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 9900 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9901 Parts[0] = Val; 9902 return true; 9903 } 9904 } 9905 return false; 9906 } 9907 9908 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 9909 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 9910 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 9911 bool IsABIRegCopy = CC.hasValue(); 9912 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9913 SDValue Val = Parts[0]; 9914 9915 // Cast the f32 to i32, truncate to i16, and cast back to f16. 9916 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 9917 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 9918 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 9919 return Val; 9920 } 9921 9922 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9923 LLVMContext &Context = *DAG.getContext(); 9924 SDValue Val = Parts[0]; 9925 EVT ValueEltVT = ValueVT.getVectorElementType(); 9926 EVT PartEltVT = PartVT.getVectorElementType(); 9927 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9928 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9929 if (PartVTBitSize % ValueVTBitSize == 0) { 9930 EVT SameEltTypeVT = ValueVT; 9931 // If the element types are different, convert it to the same element type 9932 // of PartVT. 9933 if (ValueEltVT != PartEltVT) { 9934 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9935 assert(Count != 0 && "The number of element should not be zero."); 9936 SameEltTypeVT = 9937 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9938 } 9939 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 9940 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9941 if (ValueEltVT != PartEltVT) 9942 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 9943 return Val; 9944 } 9945 } 9946 return SDValue(); 9947 } 9948 9949 #define GET_REGISTER_MATCHER 9950 #include "RISCVGenAsmMatcher.inc" 9951 9952 Register 9953 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 9954 const MachineFunction &MF) const { 9955 Register Reg = MatchRegisterAltName(RegName); 9956 if (Reg == RISCV::NoRegister) 9957 Reg = MatchRegisterName(RegName); 9958 if (Reg == RISCV::NoRegister) 9959 report_fatal_error( 9960 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 9961 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 9962 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 9963 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 9964 StringRef(RegName) + "\".")); 9965 return Reg; 9966 } 9967 9968 namespace llvm { 9969 namespace RISCVVIntrinsicsTable { 9970 9971 #define GET_RISCVVIntrinsicsTable_IMPL 9972 #include "RISCVGenSearchableTables.inc" 9973 9974 } // namespace RISCVVIntrinsicsTable 9975 9976 } // namespace llvm 9977