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.hasStdExtV()) { 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 addRegClassForRVV(VT); 133 134 if (Subtarget.hasStdExtZfh()) 135 for (MVT VT : F16VecVTs) 136 addRegClassForRVV(VT); 137 138 if (Subtarget.hasStdExtF()) 139 for (MVT VT : F32VecVTs) 140 addRegClassForRVV(VT); 141 142 if (Subtarget.hasStdExtD()) 143 for (MVT VT : F64VecVTs) 144 addRegClassForRVV(VT); 145 146 if (Subtarget.useRVVForFixedLengthVectors()) { 147 auto addRegClassForFixedVectors = [this](MVT VT) { 148 MVT ContainerVT = getContainerForFixedLengthVector(VT); 149 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 150 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 151 addRegisterClass(VT, TRI.getRegClass(RCID)); 152 }; 153 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 154 if (useRVVForFixedLengthVectorVT(VT)) 155 addRegClassForFixedVectors(VT); 156 157 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 158 if (useRVVForFixedLengthVectorVT(VT)) 159 addRegClassForFixedVectors(VT); 160 } 161 } 162 163 // Compute derived properties from the register classes. 164 computeRegisterProperties(STI.getRegisterInfo()); 165 166 setStackPointerRegisterToSaveRestore(RISCV::X2); 167 168 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 169 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 170 171 // TODO: add all necessary setOperationAction calls. 172 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 173 174 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 175 setOperationAction(ISD::BR_CC, XLenVT, Expand); 176 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 177 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 178 179 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 180 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 181 182 setOperationAction(ISD::VASTART, MVT::Other, Custom); 183 setOperationAction(ISD::VAARG, MVT::Other, Expand); 184 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 185 setOperationAction(ISD::VAEND, MVT::Other, Expand); 186 187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 188 if (!Subtarget.hasStdExtZbb()) { 189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 191 } 192 193 if (Subtarget.is64Bit()) { 194 setOperationAction(ISD::ADD, MVT::i32, Custom); 195 setOperationAction(ISD::SUB, MVT::i32, Custom); 196 setOperationAction(ISD::SHL, MVT::i32, Custom); 197 setOperationAction(ISD::SRA, MVT::i32, Custom); 198 setOperationAction(ISD::SRL, MVT::i32, Custom); 199 200 setOperationAction(ISD::UADDO, MVT::i32, Custom); 201 setOperationAction(ISD::USUBO, MVT::i32, Custom); 202 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 203 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 204 } else { 205 setLibcallName(RTLIB::SHL_I128, nullptr); 206 setLibcallName(RTLIB::SRL_I128, nullptr); 207 setLibcallName(RTLIB::SRA_I128, nullptr); 208 setLibcallName(RTLIB::MUL_I128, nullptr); 209 setLibcallName(RTLIB::MULO_I64, nullptr); 210 } 211 212 if (!Subtarget.hasStdExtM()) { 213 setOperationAction(ISD::MUL, XLenVT, Expand); 214 setOperationAction(ISD::MULHS, XLenVT, Expand); 215 setOperationAction(ISD::MULHU, XLenVT, Expand); 216 setOperationAction(ISD::SDIV, XLenVT, Expand); 217 setOperationAction(ISD::UDIV, XLenVT, Expand); 218 setOperationAction(ISD::SREM, XLenVT, Expand); 219 setOperationAction(ISD::UREM, XLenVT, Expand); 220 } else { 221 if (Subtarget.is64Bit()) { 222 setOperationAction(ISD::MUL, MVT::i32, Custom); 223 setOperationAction(ISD::MUL, MVT::i128, Custom); 224 225 setOperationAction(ISD::SDIV, MVT::i8, Custom); 226 setOperationAction(ISD::UDIV, MVT::i8, Custom); 227 setOperationAction(ISD::UREM, MVT::i8, Custom); 228 setOperationAction(ISD::SDIV, MVT::i16, Custom); 229 setOperationAction(ISD::UDIV, MVT::i16, Custom); 230 setOperationAction(ISD::UREM, MVT::i16, Custom); 231 setOperationAction(ISD::SDIV, MVT::i32, Custom); 232 setOperationAction(ISD::UDIV, MVT::i32, Custom); 233 setOperationAction(ISD::UREM, MVT::i32, Custom); 234 } else { 235 setOperationAction(ISD::MUL, MVT::i64, Custom); 236 } 237 } 238 239 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 240 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 241 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 242 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 243 244 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 245 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 246 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 247 248 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 249 if (Subtarget.is64Bit()) { 250 setOperationAction(ISD::ROTL, MVT::i32, Custom); 251 setOperationAction(ISD::ROTR, MVT::i32, Custom); 252 } 253 } else { 254 setOperationAction(ISD::ROTL, XLenVT, Expand); 255 setOperationAction(ISD::ROTR, XLenVT, Expand); 256 } 257 258 if (Subtarget.hasStdExtZbp()) { 259 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 260 // more combining. 261 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 262 setOperationAction(ISD::BSWAP, XLenVT, Custom); 263 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 264 // BSWAP i8 doesn't exist. 265 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 266 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 267 268 if (Subtarget.is64Bit()) { 269 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 270 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 271 } 272 } else { 273 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 274 // pattern match it directly in isel. 275 setOperationAction(ISD::BSWAP, XLenVT, 276 Subtarget.hasStdExtZbb() ? Legal : Expand); 277 } 278 279 if (Subtarget.hasStdExtZbb()) { 280 setOperationAction(ISD::SMIN, XLenVT, Legal); 281 setOperationAction(ISD::SMAX, XLenVT, Legal); 282 setOperationAction(ISD::UMIN, XLenVT, Legal); 283 setOperationAction(ISD::UMAX, XLenVT, Legal); 284 285 if (Subtarget.is64Bit()) { 286 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 287 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 288 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 289 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 290 } 291 } else { 292 setOperationAction(ISD::CTTZ, XLenVT, Expand); 293 setOperationAction(ISD::CTLZ, XLenVT, Expand); 294 setOperationAction(ISD::CTPOP, XLenVT, Expand); 295 } 296 297 if (Subtarget.hasStdExtZbt()) { 298 setOperationAction(ISD::FSHL, XLenVT, Custom); 299 setOperationAction(ISD::FSHR, XLenVT, Custom); 300 setOperationAction(ISD::SELECT, XLenVT, Legal); 301 302 if (Subtarget.is64Bit()) { 303 setOperationAction(ISD::FSHL, MVT::i32, Custom); 304 setOperationAction(ISD::FSHR, MVT::i32, Custom); 305 } 306 } else { 307 setOperationAction(ISD::SELECT, XLenVT, Custom); 308 } 309 310 static const ISD::CondCode FPCCToExpand[] = { 311 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 312 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 313 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 314 315 static const ISD::NodeType FPOpToExpand[] = { 316 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 317 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 318 319 if (Subtarget.hasStdExtZfh()) 320 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 321 322 if (Subtarget.hasStdExtZfh()) { 323 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 324 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 325 setOperationAction(ISD::LRINT, MVT::f16, Legal); 326 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 327 setOperationAction(ISD::LROUND, MVT::f16, Legal); 328 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 329 for (auto CC : FPCCToExpand) 330 setCondCodeAction(CC, MVT::f16, Expand); 331 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 332 setOperationAction(ISD::SELECT, MVT::f16, Custom); 333 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 334 for (auto Op : FPOpToExpand) 335 setOperationAction(Op, MVT::f16, Expand); 336 } 337 338 if (Subtarget.hasStdExtF()) { 339 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 340 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 341 setOperationAction(ISD::LRINT, MVT::f32, Legal); 342 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 343 setOperationAction(ISD::LROUND, MVT::f32, Legal); 344 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 345 for (auto CC : FPCCToExpand) 346 setCondCodeAction(CC, MVT::f32, Expand); 347 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 348 setOperationAction(ISD::SELECT, MVT::f32, Custom); 349 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 350 for (auto Op : FPOpToExpand) 351 setOperationAction(Op, MVT::f32, Expand); 352 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 353 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 354 } 355 356 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 357 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 358 359 if (Subtarget.hasStdExtD()) { 360 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 361 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 362 setOperationAction(ISD::LRINT, MVT::f64, Legal); 363 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 364 setOperationAction(ISD::LROUND, MVT::f64, Legal); 365 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 366 for (auto CC : FPCCToExpand) 367 setCondCodeAction(CC, MVT::f64, Expand); 368 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 369 setOperationAction(ISD::SELECT, MVT::f64, Custom); 370 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 371 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 372 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 373 for (auto Op : FPOpToExpand) 374 setOperationAction(Op, MVT::f64, Expand); 375 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 376 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 377 } 378 379 if (Subtarget.is64Bit()) { 380 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 381 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 382 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 383 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 384 } 385 386 if (Subtarget.hasStdExtF()) { 387 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 388 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 389 390 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 391 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 392 } 393 394 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 395 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 396 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 397 setOperationAction(ISD::JumpTable, XLenVT, Custom); 398 399 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 400 401 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 402 // Unfortunately this can't be determined just from the ISA naming string. 403 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 404 Subtarget.is64Bit() ? Legal : Custom); 405 406 setOperationAction(ISD::TRAP, MVT::Other, Legal); 407 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 408 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 409 if (Subtarget.is64Bit()) 410 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 411 412 if (Subtarget.hasStdExtA()) { 413 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 414 setMinCmpXchgSizeInBits(32); 415 } else { 416 setMaxAtomicSizeInBitsSupported(0); 417 } 418 419 setBooleanContents(ZeroOrOneBooleanContent); 420 421 if (Subtarget.hasStdExtV()) { 422 setBooleanVectorContents(ZeroOrOneBooleanContent); 423 424 setOperationAction(ISD::VSCALE, XLenVT, Custom); 425 426 // RVV intrinsics may have illegal operands. 427 // We also need to custom legalize vmv.x.s. 428 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 429 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 430 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 431 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 432 if (Subtarget.is64Bit()) { 433 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 434 } else { 435 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 436 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 437 } 438 439 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 440 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 441 442 static const unsigned IntegerVPOps[] = { 443 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 444 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 445 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 446 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 447 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 448 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 449 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}; 450 451 static const unsigned FloatingPointVPOps[] = { 452 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 453 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 454 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX}; 455 456 if (!Subtarget.is64Bit()) { 457 // We must custom-lower certain vXi64 operations on RV32 due to the vector 458 // element type being illegal. 459 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 461 462 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 463 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 464 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 465 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 466 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 467 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 468 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 469 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 470 471 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 472 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 473 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 474 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 475 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 476 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 477 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 478 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 479 } 480 481 for (MVT VT : BoolVecVTs) { 482 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 483 484 // Mask VTs are custom-expanded into a series of standard nodes 485 setOperationAction(ISD::TRUNCATE, VT, Custom); 486 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 487 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 488 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 489 490 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 491 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 492 493 setOperationAction(ISD::SELECT, VT, Custom); 494 setOperationAction(ISD::SELECT_CC, VT, Expand); 495 setOperationAction(ISD::VSELECT, VT, Expand); 496 497 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 498 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 499 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 500 501 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 502 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 503 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 504 505 // RVV has native int->float & float->int conversions where the 506 // element type sizes are within one power-of-two of each other. Any 507 // wider distances between type sizes have to be lowered as sequences 508 // which progressively narrow the gap in stages. 509 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 510 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 511 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 512 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 513 514 // Expand all extending loads to types larger than this, and truncating 515 // stores from types larger than this. 516 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 517 setTruncStoreAction(OtherVT, VT, Expand); 518 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 519 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 520 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 521 } 522 } 523 524 for (MVT VT : IntVecVTs) { 525 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 526 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 527 528 setOperationAction(ISD::SMIN, VT, Legal); 529 setOperationAction(ISD::SMAX, VT, Legal); 530 setOperationAction(ISD::UMIN, VT, Legal); 531 setOperationAction(ISD::UMAX, VT, Legal); 532 533 setOperationAction(ISD::ROTL, VT, Expand); 534 setOperationAction(ISD::ROTR, VT, Expand); 535 536 setOperationAction(ISD::CTTZ, VT, Expand); 537 setOperationAction(ISD::CTLZ, VT, Expand); 538 setOperationAction(ISD::CTPOP, VT, Expand); 539 540 // Custom-lower extensions and truncations from/to mask types. 541 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 542 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 543 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 544 545 // RVV has native int->float & float->int conversions where the 546 // element type sizes are within one power-of-two of each other. Any 547 // wider distances between type sizes have to be lowered as sequences 548 // which progressively narrow the gap in stages. 549 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 550 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 551 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 552 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 553 554 setOperationAction(ISD::SADDSAT, VT, Legal); 555 setOperationAction(ISD::UADDSAT, VT, Legal); 556 setOperationAction(ISD::SSUBSAT, VT, Legal); 557 setOperationAction(ISD::USUBSAT, VT, Legal); 558 559 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 560 // nodes which truncate by one power of two at a time. 561 setOperationAction(ISD::TRUNCATE, VT, Custom); 562 563 // Custom-lower insert/extract operations to simplify patterns. 564 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 565 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 566 567 // Custom-lower reduction operations to set up the corresponding custom 568 // nodes' operands. 569 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 570 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 571 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 572 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 573 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 574 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 575 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 576 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 577 578 for (unsigned VPOpc : IntegerVPOps) 579 setOperationAction(VPOpc, VT, Custom); 580 581 setOperationAction(ISD::LOAD, VT, Custom); 582 setOperationAction(ISD::STORE, VT, Custom); 583 584 setOperationAction(ISD::MLOAD, VT, Custom); 585 setOperationAction(ISD::MSTORE, VT, Custom); 586 setOperationAction(ISD::MGATHER, VT, Custom); 587 setOperationAction(ISD::MSCATTER, VT, Custom); 588 589 setOperationAction(ISD::VP_LOAD, VT, Custom); 590 setOperationAction(ISD::VP_STORE, VT, Custom); 591 setOperationAction(ISD::VP_GATHER, VT, Custom); 592 setOperationAction(ISD::VP_SCATTER, VT, Custom); 593 594 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 595 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 596 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 597 598 setOperationAction(ISD::SELECT, VT, Custom); 599 setOperationAction(ISD::SELECT_CC, VT, Expand); 600 601 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 602 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 603 604 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 605 setTruncStoreAction(VT, OtherVT, Expand); 606 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 607 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 608 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 609 } 610 } 611 612 // Expand various CCs to best match the RVV ISA, which natively supports UNE 613 // but no other unordered comparisons, and supports all ordered comparisons 614 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 615 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 616 // and we pattern-match those back to the "original", swapping operands once 617 // more. This way we catch both operations and both "vf" and "fv" forms with 618 // fewer patterns. 619 static const ISD::CondCode VFPCCToExpand[] = { 620 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 621 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 622 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 623 }; 624 625 // Sets common operation actions on RVV floating-point vector types. 626 const auto SetCommonVFPActions = [&](MVT VT) { 627 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 628 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 629 // sizes are within one power-of-two of each other. Therefore conversions 630 // between vXf16 and vXf64 must be lowered as sequences which convert via 631 // vXf32. 632 setOperationAction(ISD::FP_ROUND, VT, Custom); 633 setOperationAction(ISD::FP_EXTEND, VT, Custom); 634 // Custom-lower insert/extract operations to simplify patterns. 635 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 636 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 637 // Expand various condition codes (explained above). 638 for (auto CC : VFPCCToExpand) 639 setCondCodeAction(CC, VT, Expand); 640 641 setOperationAction(ISD::FMINNUM, VT, Legal); 642 setOperationAction(ISD::FMAXNUM, VT, Legal); 643 644 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 645 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 646 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 647 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 648 649 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 650 651 setOperationAction(ISD::LOAD, VT, Custom); 652 setOperationAction(ISD::STORE, VT, Custom); 653 654 setOperationAction(ISD::MLOAD, VT, Custom); 655 setOperationAction(ISD::MSTORE, VT, Custom); 656 setOperationAction(ISD::MGATHER, VT, Custom); 657 setOperationAction(ISD::MSCATTER, VT, Custom); 658 659 setOperationAction(ISD::VP_LOAD, VT, Custom); 660 setOperationAction(ISD::VP_STORE, VT, Custom); 661 setOperationAction(ISD::VP_GATHER, VT, Custom); 662 setOperationAction(ISD::VP_SCATTER, VT, Custom); 663 664 setOperationAction(ISD::SELECT, VT, Custom); 665 setOperationAction(ISD::SELECT_CC, VT, Expand); 666 667 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 668 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 669 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 670 671 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 672 673 for (unsigned VPOpc : FloatingPointVPOps) 674 setOperationAction(VPOpc, VT, Custom); 675 }; 676 677 // Sets common extload/truncstore actions on RVV floating-point vector 678 // types. 679 const auto SetCommonVFPExtLoadTruncStoreActions = 680 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 681 for (auto SmallVT : SmallerVTs) { 682 setTruncStoreAction(VT, SmallVT, Expand); 683 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 684 } 685 }; 686 687 if (Subtarget.hasStdExtZfh()) 688 for (MVT VT : F16VecVTs) 689 SetCommonVFPActions(VT); 690 691 for (MVT VT : F32VecVTs) { 692 if (Subtarget.hasStdExtF()) 693 SetCommonVFPActions(VT); 694 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 695 } 696 697 for (MVT VT : F64VecVTs) { 698 if (Subtarget.hasStdExtD()) 699 SetCommonVFPActions(VT); 700 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 701 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 702 } 703 704 if (Subtarget.useRVVForFixedLengthVectors()) { 705 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 706 if (!useRVVForFixedLengthVectorVT(VT)) 707 continue; 708 709 // By default everything must be expanded. 710 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 711 setOperationAction(Op, VT, Expand); 712 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 713 setTruncStoreAction(VT, OtherVT, Expand); 714 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 715 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 716 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 717 } 718 719 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 720 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 721 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 722 723 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 724 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 725 726 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 728 729 setOperationAction(ISD::LOAD, VT, Custom); 730 setOperationAction(ISD::STORE, VT, Custom); 731 732 setOperationAction(ISD::SETCC, VT, Custom); 733 734 setOperationAction(ISD::SELECT, VT, Custom); 735 736 setOperationAction(ISD::TRUNCATE, VT, Custom); 737 738 setOperationAction(ISD::BITCAST, VT, Custom); 739 740 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 741 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 742 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 743 744 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 745 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 746 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 747 748 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 749 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 750 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 751 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 752 753 // Operations below are different for between masks and other vectors. 754 if (VT.getVectorElementType() == MVT::i1) { 755 setOperationAction(ISD::AND, VT, Custom); 756 setOperationAction(ISD::OR, VT, Custom); 757 setOperationAction(ISD::XOR, VT, Custom); 758 continue; 759 } 760 761 // Use SPLAT_VECTOR to prevent type legalization from destroying the 762 // splats when type legalizing i64 scalar on RV32. 763 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 764 // improvements first. 765 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 766 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 767 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 768 } 769 770 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 771 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 772 773 setOperationAction(ISD::MLOAD, VT, Custom); 774 setOperationAction(ISD::MSTORE, VT, Custom); 775 setOperationAction(ISD::MGATHER, VT, Custom); 776 setOperationAction(ISD::MSCATTER, VT, Custom); 777 778 setOperationAction(ISD::VP_LOAD, VT, Custom); 779 setOperationAction(ISD::VP_STORE, VT, Custom); 780 setOperationAction(ISD::VP_GATHER, VT, Custom); 781 setOperationAction(ISD::VP_SCATTER, VT, Custom); 782 783 setOperationAction(ISD::ADD, VT, Custom); 784 setOperationAction(ISD::MUL, VT, Custom); 785 setOperationAction(ISD::SUB, VT, Custom); 786 setOperationAction(ISD::AND, VT, Custom); 787 setOperationAction(ISD::OR, VT, Custom); 788 setOperationAction(ISD::XOR, VT, Custom); 789 setOperationAction(ISD::SDIV, VT, Custom); 790 setOperationAction(ISD::SREM, VT, Custom); 791 setOperationAction(ISD::UDIV, VT, Custom); 792 setOperationAction(ISD::UREM, VT, Custom); 793 setOperationAction(ISD::SHL, VT, Custom); 794 setOperationAction(ISD::SRA, VT, Custom); 795 setOperationAction(ISD::SRL, VT, Custom); 796 797 setOperationAction(ISD::SMIN, VT, Custom); 798 setOperationAction(ISD::SMAX, VT, Custom); 799 setOperationAction(ISD::UMIN, VT, Custom); 800 setOperationAction(ISD::UMAX, VT, Custom); 801 setOperationAction(ISD::ABS, VT, Custom); 802 803 setOperationAction(ISD::MULHS, VT, Custom); 804 setOperationAction(ISD::MULHU, VT, Custom); 805 806 setOperationAction(ISD::SADDSAT, VT, Custom); 807 setOperationAction(ISD::UADDSAT, VT, Custom); 808 setOperationAction(ISD::SSUBSAT, VT, Custom); 809 setOperationAction(ISD::USUBSAT, VT, Custom); 810 811 setOperationAction(ISD::VSELECT, VT, Custom); 812 setOperationAction(ISD::SELECT_CC, VT, Expand); 813 814 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 815 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 816 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 817 818 // Custom-lower reduction operations to set up the corresponding custom 819 // nodes' operands. 820 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 821 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 822 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 823 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 824 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 825 826 for (unsigned VPOpc : IntegerVPOps) 827 setOperationAction(VPOpc, VT, Custom); 828 } 829 830 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 831 if (!useRVVForFixedLengthVectorVT(VT)) 832 continue; 833 834 // By default everything must be expanded. 835 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 836 setOperationAction(Op, VT, Expand); 837 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 838 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 839 setTruncStoreAction(VT, OtherVT, Expand); 840 } 841 842 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 843 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 844 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 845 846 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 847 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 848 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 849 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 850 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 851 852 setOperationAction(ISD::LOAD, VT, Custom); 853 setOperationAction(ISD::STORE, VT, Custom); 854 setOperationAction(ISD::MLOAD, VT, Custom); 855 setOperationAction(ISD::MSTORE, VT, Custom); 856 setOperationAction(ISD::MGATHER, VT, Custom); 857 setOperationAction(ISD::MSCATTER, VT, Custom); 858 859 setOperationAction(ISD::VP_LOAD, VT, Custom); 860 setOperationAction(ISD::VP_STORE, VT, Custom); 861 setOperationAction(ISD::VP_GATHER, VT, Custom); 862 setOperationAction(ISD::VP_SCATTER, VT, Custom); 863 864 setOperationAction(ISD::FADD, VT, Custom); 865 setOperationAction(ISD::FSUB, VT, Custom); 866 setOperationAction(ISD::FMUL, VT, Custom); 867 setOperationAction(ISD::FDIV, VT, Custom); 868 setOperationAction(ISD::FNEG, VT, Custom); 869 setOperationAction(ISD::FABS, VT, Custom); 870 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 871 setOperationAction(ISD::FSQRT, VT, Custom); 872 setOperationAction(ISD::FMA, VT, Custom); 873 setOperationAction(ISD::FMINNUM, VT, Custom); 874 setOperationAction(ISD::FMAXNUM, VT, Custom); 875 876 setOperationAction(ISD::FP_ROUND, VT, Custom); 877 setOperationAction(ISD::FP_EXTEND, VT, Custom); 878 879 for (auto CC : VFPCCToExpand) 880 setCondCodeAction(CC, VT, Expand); 881 882 setOperationAction(ISD::VSELECT, VT, Custom); 883 setOperationAction(ISD::SELECT, VT, Custom); 884 setOperationAction(ISD::SELECT_CC, VT, Expand); 885 886 setOperationAction(ISD::BITCAST, VT, Custom); 887 888 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 889 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 890 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 891 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 892 893 for (unsigned VPOpc : FloatingPointVPOps) 894 setOperationAction(VPOpc, VT, Custom); 895 } 896 897 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 898 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 899 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 900 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 901 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 902 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 903 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 904 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 905 } 906 } 907 908 // Function alignments. 909 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 910 setMinFunctionAlignment(FunctionAlignment); 911 setPrefFunctionAlignment(FunctionAlignment); 912 913 setMinimumJumpTableEntries(5); 914 915 // Jumps are expensive, compared to logic 916 setJumpIsExpensive(); 917 918 // We can use any register for comparisons 919 setHasMultipleConditionRegisters(); 920 921 setTargetDAGCombine(ISD::ADD); 922 setTargetDAGCombine(ISD::SUB); 923 setTargetDAGCombine(ISD::AND); 924 setTargetDAGCombine(ISD::OR); 925 setTargetDAGCombine(ISD::XOR); 926 setTargetDAGCombine(ISD::ANY_EXTEND); 927 setTargetDAGCombine(ISD::ZERO_EXTEND); 928 if (Subtarget.hasStdExtV()) { 929 setTargetDAGCombine(ISD::FCOPYSIGN); 930 setTargetDAGCombine(ISD::MGATHER); 931 setTargetDAGCombine(ISD::MSCATTER); 932 setTargetDAGCombine(ISD::VP_GATHER); 933 setTargetDAGCombine(ISD::VP_SCATTER); 934 setTargetDAGCombine(ISD::SRA); 935 setTargetDAGCombine(ISD::SRL); 936 setTargetDAGCombine(ISD::SHL); 937 setTargetDAGCombine(ISD::STORE); 938 } 939 } 940 941 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 942 LLVMContext &Context, 943 EVT VT) const { 944 if (!VT.isVector()) 945 return getPointerTy(DL); 946 if (Subtarget.hasStdExtV() && 947 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 948 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 949 return VT.changeVectorElementTypeToInteger(); 950 } 951 952 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 953 return Subtarget.getXLenVT(); 954 } 955 956 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 957 const CallInst &I, 958 MachineFunction &MF, 959 unsigned Intrinsic) const { 960 auto &DL = I.getModule()->getDataLayout(); 961 switch (Intrinsic) { 962 default: 963 return false; 964 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 965 case Intrinsic::riscv_masked_atomicrmw_add_i32: 966 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 967 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 968 case Intrinsic::riscv_masked_atomicrmw_max_i32: 969 case Intrinsic::riscv_masked_atomicrmw_min_i32: 970 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 971 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 972 case Intrinsic::riscv_masked_cmpxchg_i32: { 973 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 974 Info.opc = ISD::INTRINSIC_W_CHAIN; 975 Info.memVT = MVT::getVT(PtrTy->getElementType()); 976 Info.ptrVal = I.getArgOperand(0); 977 Info.offset = 0; 978 Info.align = Align(4); 979 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 980 MachineMemOperand::MOVolatile; 981 return true; 982 } 983 case Intrinsic::riscv_masked_strided_load: 984 Info.opc = ISD::INTRINSIC_W_CHAIN; 985 Info.ptrVal = I.getArgOperand(1); 986 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 987 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 988 Info.size = MemoryLocation::UnknownSize; 989 Info.flags |= MachineMemOperand::MOLoad; 990 return true; 991 case Intrinsic::riscv_masked_strided_store: 992 Info.opc = ISD::INTRINSIC_VOID; 993 Info.ptrVal = I.getArgOperand(1); 994 Info.memVT = 995 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 996 Info.align = Align( 997 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 998 8); 999 Info.size = MemoryLocation::UnknownSize; 1000 Info.flags |= MachineMemOperand::MOStore; 1001 return true; 1002 } 1003 } 1004 1005 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1006 const AddrMode &AM, Type *Ty, 1007 unsigned AS, 1008 Instruction *I) const { 1009 // No global is ever allowed as a base. 1010 if (AM.BaseGV) 1011 return false; 1012 1013 // Require a 12-bit signed offset. 1014 if (!isInt<12>(AM.BaseOffs)) 1015 return false; 1016 1017 switch (AM.Scale) { 1018 case 0: // "r+i" or just "i", depending on HasBaseReg. 1019 break; 1020 case 1: 1021 if (!AM.HasBaseReg) // allow "r+i". 1022 break; 1023 return false; // disallow "r+r" or "r+r+i". 1024 default: 1025 return false; 1026 } 1027 1028 return true; 1029 } 1030 1031 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1032 return isInt<12>(Imm); 1033 } 1034 1035 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1036 return isInt<12>(Imm); 1037 } 1038 1039 // On RV32, 64-bit integers are split into their high and low parts and held 1040 // in two different registers, so the trunc is free since the low register can 1041 // just be used. 1042 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1043 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1044 return false; 1045 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1046 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1047 return (SrcBits == 64 && DestBits == 32); 1048 } 1049 1050 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1051 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1052 !SrcVT.isInteger() || !DstVT.isInteger()) 1053 return false; 1054 unsigned SrcBits = SrcVT.getSizeInBits(); 1055 unsigned DestBits = DstVT.getSizeInBits(); 1056 return (SrcBits == 64 && DestBits == 32); 1057 } 1058 1059 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1060 // Zexts are free if they can be combined with a load. 1061 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1062 EVT MemVT = LD->getMemoryVT(); 1063 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1064 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1065 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1066 LD->getExtensionType() == ISD::ZEXTLOAD)) 1067 return true; 1068 } 1069 1070 return TargetLowering::isZExtFree(Val, VT2); 1071 } 1072 1073 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1074 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1075 } 1076 1077 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1078 return Subtarget.hasStdExtZbb(); 1079 } 1080 1081 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1082 return Subtarget.hasStdExtZbb(); 1083 } 1084 1085 /// Check if sinking \p I's operands to I's basic block is profitable, because 1086 /// the operands can be folded into a target instruction, e.g. 1087 /// splats of scalars can fold into vector instructions. 1088 bool RISCVTargetLowering::shouldSinkOperands( 1089 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1090 using namespace llvm::PatternMatch; 1091 1092 if (!I->getType()->isVectorTy() || !Subtarget.hasStdExtV()) 1093 return false; 1094 1095 auto IsSinker = [&](Instruction *I, int Operand) { 1096 switch (I->getOpcode()) { 1097 case Instruction::Add: 1098 case Instruction::Sub: 1099 case Instruction::Mul: 1100 case Instruction::And: 1101 case Instruction::Or: 1102 case Instruction::Xor: 1103 case Instruction::FAdd: 1104 case Instruction::FSub: 1105 case Instruction::FMul: 1106 case Instruction::FDiv: 1107 return true; 1108 case Instruction::Shl: 1109 case Instruction::LShr: 1110 case Instruction::AShr: 1111 return Operand == 1; 1112 case Instruction::Call: 1113 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1114 switch (II->getIntrinsicID()) { 1115 case Intrinsic::fma: 1116 return Operand == 0 || Operand == 1; 1117 default: 1118 return false; 1119 } 1120 } 1121 return false; 1122 default: 1123 return false; 1124 } 1125 }; 1126 1127 for (auto OpIdx : enumerate(I->operands())) { 1128 if (!IsSinker(I, OpIdx.index())) 1129 continue; 1130 1131 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1132 // Make sure we are not already sinking this operand 1133 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1134 continue; 1135 1136 // We are looking for a splat that can be sunk. 1137 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1138 m_Undef(), m_ZeroMask()))) 1139 continue; 1140 1141 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1142 // and vector registers 1143 for (Use &U : Op->uses()) { 1144 Instruction *Insn = cast<Instruction>(U.getUser()); 1145 if (!IsSinker(Insn, U.getOperandNo())) 1146 return false; 1147 } 1148 1149 Ops.push_back(&Op->getOperandUse(0)); 1150 Ops.push_back(&OpIdx.value()); 1151 } 1152 return true; 1153 } 1154 1155 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1156 bool ForCodeSize) const { 1157 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1158 return false; 1159 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1160 return false; 1161 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1162 return false; 1163 if (Imm.isNegZero()) 1164 return false; 1165 return Imm.isZero(); 1166 } 1167 1168 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1169 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1170 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1171 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1172 } 1173 1174 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1175 CallingConv::ID CC, 1176 EVT VT) const { 1177 // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still 1178 // end up using a GPR but that will be decided based on ABI. 1179 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1180 return MVT::f32; 1181 1182 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1183 } 1184 1185 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1186 CallingConv::ID CC, 1187 EVT VT) const { 1188 // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still 1189 // end up using a GPR but that will be decided based on ABI. 1190 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1191 return 1; 1192 1193 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1194 } 1195 1196 // Changes the condition code and swaps operands if necessary, so the SetCC 1197 // operation matches one of the comparisons supported directly by branches 1198 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1199 // with 1/-1. 1200 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1201 ISD::CondCode &CC, SelectionDAG &DAG) { 1202 // Convert X > -1 to X >= 0. 1203 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1204 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1205 CC = ISD::SETGE; 1206 return; 1207 } 1208 // Convert X < 1 to 0 >= X. 1209 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1210 RHS = LHS; 1211 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1212 CC = ISD::SETGE; 1213 return; 1214 } 1215 1216 switch (CC) { 1217 default: 1218 break; 1219 case ISD::SETGT: 1220 case ISD::SETLE: 1221 case ISD::SETUGT: 1222 case ISD::SETULE: 1223 CC = ISD::getSetCCSwappedOperands(CC); 1224 std::swap(LHS, RHS); 1225 break; 1226 } 1227 } 1228 1229 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1230 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1231 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1232 if (VT.getVectorElementType() == MVT::i1) 1233 KnownSize *= 8; 1234 1235 switch (KnownSize) { 1236 default: 1237 llvm_unreachable("Invalid LMUL."); 1238 case 8: 1239 return RISCVII::VLMUL::LMUL_F8; 1240 case 16: 1241 return RISCVII::VLMUL::LMUL_F4; 1242 case 32: 1243 return RISCVII::VLMUL::LMUL_F2; 1244 case 64: 1245 return RISCVII::VLMUL::LMUL_1; 1246 case 128: 1247 return RISCVII::VLMUL::LMUL_2; 1248 case 256: 1249 return RISCVII::VLMUL::LMUL_4; 1250 case 512: 1251 return RISCVII::VLMUL::LMUL_8; 1252 } 1253 } 1254 1255 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1256 switch (LMul) { 1257 default: 1258 llvm_unreachable("Invalid LMUL."); 1259 case RISCVII::VLMUL::LMUL_F8: 1260 case RISCVII::VLMUL::LMUL_F4: 1261 case RISCVII::VLMUL::LMUL_F2: 1262 case RISCVII::VLMUL::LMUL_1: 1263 return RISCV::VRRegClassID; 1264 case RISCVII::VLMUL::LMUL_2: 1265 return RISCV::VRM2RegClassID; 1266 case RISCVII::VLMUL::LMUL_4: 1267 return RISCV::VRM4RegClassID; 1268 case RISCVII::VLMUL::LMUL_8: 1269 return RISCV::VRM8RegClassID; 1270 } 1271 } 1272 1273 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1274 RISCVII::VLMUL LMUL = getLMUL(VT); 1275 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1276 LMUL == RISCVII::VLMUL::LMUL_F4 || 1277 LMUL == RISCVII::VLMUL::LMUL_F2 || 1278 LMUL == RISCVII::VLMUL::LMUL_1) { 1279 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1280 "Unexpected subreg numbering"); 1281 return RISCV::sub_vrm1_0 + Index; 1282 } 1283 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1284 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1285 "Unexpected subreg numbering"); 1286 return RISCV::sub_vrm2_0 + Index; 1287 } 1288 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1289 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1290 "Unexpected subreg numbering"); 1291 return RISCV::sub_vrm4_0 + Index; 1292 } 1293 llvm_unreachable("Invalid vector type."); 1294 } 1295 1296 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1297 if (VT.getVectorElementType() == MVT::i1) 1298 return RISCV::VRRegClassID; 1299 return getRegClassIDForLMUL(getLMUL(VT)); 1300 } 1301 1302 // Attempt to decompose a subvector insert/extract between VecVT and 1303 // SubVecVT via subregister indices. Returns the subregister index that 1304 // can perform the subvector insert/extract with the given element index, as 1305 // well as the index corresponding to any leftover subvectors that must be 1306 // further inserted/extracted within the register class for SubVecVT. 1307 std::pair<unsigned, unsigned> 1308 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1309 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1310 const RISCVRegisterInfo *TRI) { 1311 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1312 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1313 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1314 "Register classes not ordered"); 1315 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1316 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1317 // Try to compose a subregister index that takes us from the incoming 1318 // LMUL>1 register class down to the outgoing one. At each step we half 1319 // the LMUL: 1320 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1321 // Note that this is not guaranteed to find a subregister index, such as 1322 // when we are extracting from one VR type to another. 1323 unsigned SubRegIdx = RISCV::NoSubRegister; 1324 for (const unsigned RCID : 1325 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1326 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1327 VecVT = VecVT.getHalfNumVectorElementsVT(); 1328 bool IsHi = 1329 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1330 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1331 getSubregIndexByMVT(VecVT, IsHi)); 1332 if (IsHi) 1333 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1334 } 1335 return {SubRegIdx, InsertExtractIdx}; 1336 } 1337 1338 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1339 // stores for those types. 1340 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1341 return !Subtarget.useRVVForFixedLengthVectors() || 1342 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1343 } 1344 1345 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1346 if (ScalarTy->isPointerTy()) 1347 return true; 1348 1349 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1350 ScalarTy->isIntegerTy(32) || ScalarTy->isIntegerTy(64)) 1351 return true; 1352 1353 if (ScalarTy->isHalfTy()) 1354 return Subtarget.hasStdExtZfh(); 1355 if (ScalarTy->isFloatTy()) 1356 return Subtarget.hasStdExtF(); 1357 if (ScalarTy->isDoubleTy()) 1358 return Subtarget.hasStdExtD(); 1359 1360 return false; 1361 } 1362 1363 static bool useRVVForFixedLengthVectorVT(MVT VT, 1364 const RISCVSubtarget &Subtarget) { 1365 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1366 if (!Subtarget.useRVVForFixedLengthVectors()) 1367 return false; 1368 1369 // We only support a set of vector types with a consistent maximum fixed size 1370 // across all supported vector element types to avoid legalization issues. 1371 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1372 // fixed-length vector type we support is 1024 bytes. 1373 if (VT.getFixedSizeInBits() > 1024 * 8) 1374 return false; 1375 1376 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1377 1378 MVT EltVT = VT.getVectorElementType(); 1379 1380 // Don't use RVV for vectors we cannot scalarize if required. 1381 switch (EltVT.SimpleTy) { 1382 // i1 is supported but has different rules. 1383 default: 1384 return false; 1385 case MVT::i1: 1386 // Masks can only use a single register. 1387 if (VT.getVectorNumElements() > MinVLen) 1388 return false; 1389 MinVLen /= 8; 1390 break; 1391 case MVT::i8: 1392 case MVT::i16: 1393 case MVT::i32: 1394 case MVT::i64: 1395 break; 1396 case MVT::f16: 1397 if (!Subtarget.hasStdExtZfh()) 1398 return false; 1399 break; 1400 case MVT::f32: 1401 if (!Subtarget.hasStdExtF()) 1402 return false; 1403 break; 1404 case MVT::f64: 1405 if (!Subtarget.hasStdExtD()) 1406 return false; 1407 break; 1408 } 1409 1410 // Reject elements larger than ELEN. 1411 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1412 return false; 1413 1414 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1415 // Don't use RVV for types that don't fit. 1416 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1417 return false; 1418 1419 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1420 // the base fixed length RVV support in place. 1421 if (!VT.isPow2VectorType()) 1422 return false; 1423 1424 return true; 1425 } 1426 1427 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1428 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1429 } 1430 1431 // Return the largest legal scalable vector type that matches VT's element type. 1432 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1433 const RISCVSubtarget &Subtarget) { 1434 // This may be called before legal types are setup. 1435 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1436 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1437 "Expected legal fixed length vector!"); 1438 1439 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1440 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1441 1442 MVT EltVT = VT.getVectorElementType(); 1443 switch (EltVT.SimpleTy) { 1444 default: 1445 llvm_unreachable("unexpected element type for RVV container"); 1446 case MVT::i1: 1447 case MVT::i8: 1448 case MVT::i16: 1449 case MVT::i32: 1450 case MVT::i64: 1451 case MVT::f16: 1452 case MVT::f32: 1453 case MVT::f64: { 1454 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1455 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1456 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1457 unsigned NumElts = 1458 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1459 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1460 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1461 return MVT::getScalableVectorVT(EltVT, NumElts); 1462 } 1463 } 1464 } 1465 1466 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1467 const RISCVSubtarget &Subtarget) { 1468 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1469 Subtarget); 1470 } 1471 1472 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1473 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1474 } 1475 1476 // Grow V to consume an entire RVV register. 1477 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1478 const RISCVSubtarget &Subtarget) { 1479 assert(VT.isScalableVector() && 1480 "Expected to convert into a scalable vector!"); 1481 assert(V.getValueType().isFixedLengthVector() && 1482 "Expected a fixed length vector operand!"); 1483 SDLoc DL(V); 1484 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1485 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1486 } 1487 1488 // Shrink V so it's just big enough to maintain a VT's worth of data. 1489 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1490 const RISCVSubtarget &Subtarget) { 1491 assert(VT.isFixedLengthVector() && 1492 "Expected to convert into a fixed length vector!"); 1493 assert(V.getValueType().isScalableVector() && 1494 "Expected a scalable vector operand!"); 1495 SDLoc DL(V); 1496 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1497 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1498 } 1499 1500 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1501 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1502 // the vector type that it is contained in. 1503 static std::pair<SDValue, SDValue> 1504 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1505 const RISCVSubtarget &Subtarget) { 1506 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1507 MVT XLenVT = Subtarget.getXLenVT(); 1508 SDValue VL = VecVT.isFixedLengthVector() 1509 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1510 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1511 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1512 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1513 return {Mask, VL}; 1514 } 1515 1516 // As above but assuming the given type is a scalable vector type. 1517 static std::pair<SDValue, SDValue> 1518 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1519 const RISCVSubtarget &Subtarget) { 1520 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1521 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1522 } 1523 1524 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1525 // of either is (currently) supported. This can get us into an infinite loop 1526 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1527 // as a ..., etc. 1528 // Until either (or both) of these can reliably lower any node, reporting that 1529 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1530 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1531 // which is not desirable. 1532 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1533 EVT VT, unsigned DefinedValues) const { 1534 return false; 1535 } 1536 1537 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1538 // Only splats are currently supported. 1539 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1540 return true; 1541 1542 return false; 1543 } 1544 1545 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1546 // RISCV FP-to-int conversions saturate to the destination register size, but 1547 // don't produce 0 for nan. We can use a conversion instruction and fix the 1548 // nan case with a compare and a select. 1549 SDValue Src = Op.getOperand(0); 1550 1551 EVT DstVT = Op.getValueType(); 1552 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1553 1554 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1555 unsigned Opc; 1556 if (SatVT == DstVT) 1557 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1558 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1559 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1560 else 1561 return SDValue(); 1562 // FIXME: Support other SatVTs by clamping before or after the conversion. 1563 1564 SDLoc DL(Op); 1565 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1566 1567 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1568 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1569 } 1570 1571 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1572 const RISCVSubtarget &Subtarget) { 1573 MVT VT = Op.getSimpleValueType(); 1574 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1575 1576 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1577 1578 SDLoc DL(Op); 1579 SDValue Mask, VL; 1580 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1581 1582 unsigned Opc = 1583 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1584 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1585 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1586 } 1587 1588 struct VIDSequence { 1589 int64_t StepNumerator; 1590 unsigned StepDenominator; 1591 int64_t Addend; 1592 }; 1593 1594 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1595 // to the (non-zero) step S and start value X. This can be then lowered as the 1596 // RVV sequence (VID * S) + X, for example. 1597 // The step S is represented as an integer numerator divided by a positive 1598 // denominator. Note that the implementation currently only identifies 1599 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1600 // cannot detect 2/3, for example. 1601 // Note that this method will also match potentially unappealing index 1602 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1603 // determine whether this is worth generating code for. 1604 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1605 unsigned NumElts = Op.getNumOperands(); 1606 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1607 if (!Op.getValueType().isInteger()) 1608 return None; 1609 1610 Optional<unsigned> SeqStepDenom; 1611 Optional<int64_t> SeqStepNum, SeqAddend; 1612 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1613 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1614 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1615 // Assume undef elements match the sequence; we just have to be careful 1616 // when interpolating across them. 1617 if (Op.getOperand(Idx).isUndef()) 1618 continue; 1619 // The BUILD_VECTOR must be all constants. 1620 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1621 return None; 1622 1623 uint64_t Val = Op.getConstantOperandVal(Idx) & 1624 maskTrailingOnes<uint64_t>(EltSizeInBits); 1625 1626 if (PrevElt) { 1627 // Calculate the step since the last non-undef element, and ensure 1628 // it's consistent across the entire sequence. 1629 unsigned IdxDiff = Idx - PrevElt->second; 1630 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1631 1632 // A zero-value value difference means that we're somewhere in the middle 1633 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1634 // step change before evaluating the sequence. 1635 if (ValDiff != 0) { 1636 int64_t Remainder = ValDiff % IdxDiff; 1637 // Normalize the step if it's greater than 1. 1638 if (Remainder != ValDiff) { 1639 // The difference must cleanly divide the element span. 1640 if (Remainder != 0) 1641 return None; 1642 ValDiff /= IdxDiff; 1643 IdxDiff = 1; 1644 } 1645 1646 if (!SeqStepNum) 1647 SeqStepNum = ValDiff; 1648 else if (ValDiff != SeqStepNum) 1649 return None; 1650 1651 if (!SeqStepDenom) 1652 SeqStepDenom = IdxDiff; 1653 else if (IdxDiff != *SeqStepDenom) 1654 return None; 1655 } 1656 } 1657 1658 // Record and/or check any addend. 1659 if (SeqStepNum && SeqStepDenom) { 1660 uint64_t ExpectedVal = 1661 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1662 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1663 if (!SeqAddend) 1664 SeqAddend = Addend; 1665 else if (SeqAddend != Addend) 1666 return None; 1667 } 1668 1669 // Record this non-undef element for later. 1670 if (!PrevElt || PrevElt->first != Val) 1671 PrevElt = std::make_pair(Val, Idx); 1672 } 1673 // We need to have logged both a step and an addend for this to count as 1674 // a legal index sequence. 1675 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1676 return None; 1677 1678 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1679 } 1680 1681 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1682 const RISCVSubtarget &Subtarget) { 1683 MVT VT = Op.getSimpleValueType(); 1684 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1685 1686 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1687 1688 SDLoc DL(Op); 1689 SDValue Mask, VL; 1690 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1691 1692 MVT XLenVT = Subtarget.getXLenVT(); 1693 unsigned NumElts = Op.getNumOperands(); 1694 1695 if (VT.getVectorElementType() == MVT::i1) { 1696 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1697 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1698 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1699 } 1700 1701 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1702 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1703 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1704 } 1705 1706 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1707 // scalar integer chunks whose bit-width depends on the number of mask 1708 // bits and XLEN. 1709 // First, determine the most appropriate scalar integer type to use. This 1710 // is at most XLenVT, but may be shrunk to a smaller vector element type 1711 // according to the size of the final vector - use i8 chunks rather than 1712 // XLenVT if we're producing a v8i1. This results in more consistent 1713 // codegen across RV32 and RV64. 1714 unsigned NumViaIntegerBits = 1715 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1716 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1717 // If we have to use more than one INSERT_VECTOR_ELT then this 1718 // optimization is likely to increase code size; avoid peforming it in 1719 // such a case. We can use a load from a constant pool in this case. 1720 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1721 return SDValue(); 1722 // Now we can create our integer vector type. Note that it may be larger 1723 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1724 MVT IntegerViaVecVT = 1725 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1726 divideCeil(NumElts, NumViaIntegerBits)); 1727 1728 uint64_t Bits = 0; 1729 unsigned BitPos = 0, IntegerEltIdx = 0; 1730 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1731 1732 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1733 // Once we accumulate enough bits to fill our scalar type, insert into 1734 // our vector and clear our accumulated data. 1735 if (I != 0 && I % NumViaIntegerBits == 0) { 1736 if (NumViaIntegerBits <= 32) 1737 Bits = SignExtend64(Bits, 32); 1738 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1739 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1740 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1741 Bits = 0; 1742 BitPos = 0; 1743 IntegerEltIdx++; 1744 } 1745 SDValue V = Op.getOperand(I); 1746 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1747 Bits |= ((uint64_t)BitValue << BitPos); 1748 } 1749 1750 // Insert the (remaining) scalar value into position in our integer 1751 // vector type. 1752 if (NumViaIntegerBits <= 32) 1753 Bits = SignExtend64(Bits, 32); 1754 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1755 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1756 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1757 1758 if (NumElts < NumViaIntegerBits) { 1759 // If we're producing a smaller vector than our minimum legal integer 1760 // type, bitcast to the equivalent (known-legal) mask type, and extract 1761 // our final mask. 1762 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1763 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1764 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1765 DAG.getConstant(0, DL, XLenVT)); 1766 } else { 1767 // Else we must have produced an integer type with the same size as the 1768 // mask type; bitcast for the final result. 1769 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1770 Vec = DAG.getBitcast(VT, Vec); 1771 } 1772 1773 return Vec; 1774 } 1775 1776 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1777 // vector type, we have a legal equivalently-sized i8 type, so we can use 1778 // that. 1779 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1780 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1781 1782 SDValue WideVec; 1783 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1784 // For a splat, perform a scalar truncate before creating the wider 1785 // vector. 1786 assert(Splat.getValueType() == XLenVT && 1787 "Unexpected type for i1 splat value"); 1788 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1789 DAG.getConstant(1, DL, XLenVT)); 1790 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1791 } else { 1792 SmallVector<SDValue, 8> Ops(Op->op_values()); 1793 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1794 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1795 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1796 } 1797 1798 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1799 } 1800 1801 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1802 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1803 : RISCVISD::VMV_V_X_VL; 1804 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1805 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1806 } 1807 1808 // Try and match index sequences, which we can lower to the vid instruction 1809 // with optional modifications. An all-undef vector is matched by 1810 // getSplatValue, above. 1811 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1812 int64_t StepNumerator = SimpleVID->StepNumerator; 1813 unsigned StepDenominator = SimpleVID->StepDenominator; 1814 int64_t Addend = SimpleVID->Addend; 1815 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 1816 // threshold since it's the immediate value many RVV instructions accept. 1817 if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) && 1818 isInt<5>(Addend)) { 1819 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1820 // Convert right out of the scalable type so we can use standard ISD 1821 // nodes for the rest of the computation. If we used scalable types with 1822 // these, we'd lose the fixed-length vector info and generate worse 1823 // vsetvli code. 1824 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 1825 assert(StepNumerator != 0 && "Invalid step"); 1826 bool Negate = false; 1827 if (StepNumerator != 1) { 1828 int64_t SplatStepVal = StepNumerator; 1829 unsigned Opcode = ISD::MUL; 1830 if (isPowerOf2_64(std::abs(StepNumerator))) { 1831 Negate = StepNumerator < 0; 1832 Opcode = ISD::SHL; 1833 SplatStepVal = Log2_64(std::abs(StepNumerator)); 1834 } 1835 SDValue SplatStep = DAG.getSplatVector( 1836 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 1837 VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep); 1838 } 1839 if (StepDenominator != 1) { 1840 SDValue SplatStep = DAG.getSplatVector( 1841 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 1842 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 1843 } 1844 if (Addend != 0 || Negate) { 1845 SDValue SplatAddend = 1846 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 1847 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 1848 } 1849 return VID; 1850 } 1851 } 1852 1853 // Attempt to detect "hidden" splats, which only reveal themselves as splats 1854 // when re-interpreted as a vector with a larger element type. For example, 1855 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 1856 // could be instead splat as 1857 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 1858 // TODO: This optimization could also work on non-constant splats, but it 1859 // would require bit-manipulation instructions to construct the splat value. 1860 SmallVector<SDValue> Sequence; 1861 unsigned EltBitSize = VT.getScalarSizeInBits(); 1862 const auto *BV = cast<BuildVectorSDNode>(Op); 1863 if (VT.isInteger() && EltBitSize < 64 && 1864 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1865 BV->getRepeatedSequence(Sequence) && 1866 (Sequence.size() * EltBitSize) <= 64) { 1867 unsigned SeqLen = Sequence.size(); 1868 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 1869 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 1870 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 1871 ViaIntVT == MVT::i64) && 1872 "Unexpected sequence type"); 1873 1874 unsigned EltIdx = 0; 1875 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 1876 uint64_t SplatValue = 0; 1877 // Construct the amalgamated value which can be splatted as this larger 1878 // vector type. 1879 for (const auto &SeqV : Sequence) { 1880 if (!SeqV.isUndef()) 1881 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 1882 << (EltIdx * EltBitSize)); 1883 EltIdx++; 1884 } 1885 1886 // On RV64, sign-extend from 32 to 64 bits where possible in order to 1887 // achieve better constant materializion. 1888 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 1889 SplatValue = SignExtend64(SplatValue, 32); 1890 1891 // Since we can't introduce illegal i64 types at this stage, we can only 1892 // perform an i64 splat on RV32 if it is its own sign-extended value. That 1893 // way we can use RVV instructions to splat. 1894 assert((ViaIntVT.bitsLE(XLenVT) || 1895 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 1896 "Unexpected bitcast sequence"); 1897 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 1898 SDValue ViaVL = 1899 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 1900 MVT ViaContainerVT = 1901 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 1902 SDValue Splat = 1903 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 1904 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 1905 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 1906 return DAG.getBitcast(VT, Splat); 1907 } 1908 } 1909 1910 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1911 // which constitute a large proportion of the elements. In such cases we can 1912 // splat a vector with the dominant element and make up the shortfall with 1913 // INSERT_VECTOR_ELTs. 1914 // Note that this includes vectors of 2 elements by association. The 1915 // upper-most element is the "dominant" one, allowing us to use a splat to 1916 // "insert" the upper element, and an insert of the lower element at position 1917 // 0, which improves codegen. 1918 SDValue DominantValue; 1919 unsigned MostCommonCount = 0; 1920 DenseMap<SDValue, unsigned> ValueCounts; 1921 unsigned NumUndefElts = 1922 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1923 1924 // Track the number of scalar loads we know we'd be inserting, estimated as 1925 // any non-zero floating-point constant. Other kinds of element are either 1926 // already in registers or are materialized on demand. The threshold at which 1927 // a vector load is more desirable than several scalar materializion and 1928 // vector-insertion instructions is not known. 1929 unsigned NumScalarLoads = 0; 1930 1931 for (SDValue V : Op->op_values()) { 1932 if (V.isUndef()) 1933 continue; 1934 1935 ValueCounts.insert(std::make_pair(V, 0)); 1936 unsigned &Count = ValueCounts[V]; 1937 1938 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 1939 NumScalarLoads += !CFP->isExactlyValue(+0.0); 1940 1941 // Is this value dominant? In case of a tie, prefer the highest element as 1942 // it's cheaper to insert near the beginning of a vector than it is at the 1943 // end. 1944 if (++Count >= MostCommonCount) { 1945 DominantValue = V; 1946 MostCommonCount = Count; 1947 } 1948 } 1949 1950 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 1951 unsigned NumDefElts = NumElts - NumUndefElts; 1952 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 1953 1954 // Don't perform this optimization when optimizing for size, since 1955 // materializing elements and inserting them tends to cause code bloat. 1956 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 1957 ((MostCommonCount > DominantValueCountThreshold) || 1958 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 1959 // Start by splatting the most common element. 1960 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 1961 1962 DenseSet<SDValue> Processed{DominantValue}; 1963 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 1964 for (const auto &OpIdx : enumerate(Op->ops())) { 1965 const SDValue &V = OpIdx.value(); 1966 if (V.isUndef() || !Processed.insert(V).second) 1967 continue; 1968 if (ValueCounts[V] == 1) { 1969 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 1970 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 1971 } else { 1972 // Blend in all instances of this value using a VSELECT, using a 1973 // mask where each bit signals whether that element is the one 1974 // we're after. 1975 SmallVector<SDValue> Ops; 1976 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 1977 return DAG.getConstant(V == V1, DL, XLenVT); 1978 }); 1979 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 1980 DAG.getBuildVector(SelMaskTy, DL, Ops), 1981 DAG.getSplatBuildVector(VT, DL, V), Vec); 1982 } 1983 } 1984 1985 return Vec; 1986 } 1987 1988 return SDValue(); 1989 } 1990 1991 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 1992 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 1993 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 1994 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 1995 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 1996 // If Hi constant is all the same sign bit as Lo, lower this as a custom 1997 // node in order to try and match RVV vector/scalar instructions. 1998 if ((LoC >> 31) == HiC) 1999 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2000 } 2001 2002 // Fall back to a stack store and stride x0 vector load. 2003 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2004 } 2005 2006 // Called by type legalization to handle splat of i64 on RV32. 2007 // FIXME: We can optimize this when the type has sign or zero bits in one 2008 // of the halves. 2009 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2010 SDValue VL, SelectionDAG &DAG) { 2011 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2012 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2013 DAG.getConstant(0, DL, MVT::i32)); 2014 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2015 DAG.getConstant(1, DL, MVT::i32)); 2016 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2017 } 2018 2019 // This function lowers a splat of a scalar operand Splat with the vector 2020 // length VL. It ensures the final sequence is type legal, which is useful when 2021 // lowering a splat after type legalization. 2022 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2023 SelectionDAG &DAG, 2024 const RISCVSubtarget &Subtarget) { 2025 if (VT.isFloatingPoint()) 2026 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2027 2028 MVT XLenVT = Subtarget.getXLenVT(); 2029 2030 // Simplest case is that the operand needs to be promoted to XLenVT. 2031 if (Scalar.getValueType().bitsLE(XLenVT)) { 2032 // If the operand is a constant, sign extend to increase our chances 2033 // of being able to use a .vi instruction. ANY_EXTEND would become a 2034 // a zero extend and the simm5 check in isel would fail. 2035 // FIXME: Should we ignore the upper bits in isel instead? 2036 unsigned ExtOpc = 2037 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2038 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2039 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2040 } 2041 2042 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2043 "Unexpected scalar for splat lowering!"); 2044 2045 // Otherwise use the more complicated splatting algorithm. 2046 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2047 } 2048 2049 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2050 const RISCVSubtarget &Subtarget) { 2051 SDValue V1 = Op.getOperand(0); 2052 SDValue V2 = Op.getOperand(1); 2053 SDLoc DL(Op); 2054 MVT XLenVT = Subtarget.getXLenVT(); 2055 MVT VT = Op.getSimpleValueType(); 2056 unsigned NumElts = VT.getVectorNumElements(); 2057 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2058 2059 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2060 2061 SDValue TrueMask, VL; 2062 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2063 2064 if (SVN->isSplat()) { 2065 const int Lane = SVN->getSplatIndex(); 2066 if (Lane >= 0) { 2067 MVT SVT = VT.getVectorElementType(); 2068 2069 // Turn splatted vector load into a strided load with an X0 stride. 2070 SDValue V = V1; 2071 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2072 // with undef. 2073 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2074 int Offset = Lane; 2075 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2076 int OpElements = 2077 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2078 V = V.getOperand(Offset / OpElements); 2079 Offset %= OpElements; 2080 } 2081 2082 // We need to ensure the load isn't atomic or volatile. 2083 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2084 auto *Ld = cast<LoadSDNode>(V); 2085 Offset *= SVT.getStoreSize(); 2086 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2087 TypeSize::Fixed(Offset), DL); 2088 2089 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2090 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2091 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2092 SDValue IntID = 2093 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2094 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2095 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2096 SDValue NewLoad = DAG.getMemIntrinsicNode( 2097 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2098 DAG.getMachineFunction().getMachineMemOperand( 2099 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2100 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2101 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2102 } 2103 2104 // Otherwise use a scalar load and splat. This will give the best 2105 // opportunity to fold a splat into the operation. ISel can turn it into 2106 // the x0 strided load if we aren't able to fold away the select. 2107 if (SVT.isFloatingPoint()) 2108 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2109 Ld->getPointerInfo().getWithOffset(Offset), 2110 Ld->getOriginalAlign(), 2111 Ld->getMemOperand()->getFlags()); 2112 else 2113 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2114 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2115 Ld->getOriginalAlign(), 2116 Ld->getMemOperand()->getFlags()); 2117 DAG.makeEquivalentMemoryOrdering(Ld, V); 2118 2119 unsigned Opc = 2120 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2121 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2122 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2123 } 2124 2125 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2126 assert(Lane < (int)NumElts && "Unexpected lane!"); 2127 SDValue Gather = 2128 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2129 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2130 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2131 } 2132 } 2133 2134 // Detect shuffles which can be re-expressed as vector selects; these are 2135 // shuffles in which each element in the destination is taken from an element 2136 // at the corresponding index in either source vectors. 2137 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2138 int MaskIndex = MaskIdx.value(); 2139 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2140 }); 2141 2142 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2143 2144 SmallVector<SDValue> MaskVals; 2145 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2146 // merged with a second vrgather. 2147 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2148 2149 // By default we preserve the original operand order, and use a mask to 2150 // select LHS as true and RHS as false. However, since RVV vector selects may 2151 // feature splats but only on the LHS, we may choose to invert our mask and 2152 // instead select between RHS and LHS. 2153 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2154 bool InvertMask = IsSelect == SwapOps; 2155 2156 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2157 // half. 2158 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2159 2160 // Now construct the mask that will be used by the vselect or blended 2161 // vrgather operation. For vrgathers, construct the appropriate indices into 2162 // each vector. 2163 for (int MaskIndex : SVN->getMask()) { 2164 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2165 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2166 if (!IsSelect) { 2167 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2168 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2169 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2170 : DAG.getUNDEF(XLenVT)); 2171 GatherIndicesRHS.push_back( 2172 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2173 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2174 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2175 ++LHSIndexCounts[MaskIndex]; 2176 if (!IsLHSOrUndefIndex) 2177 ++RHSIndexCounts[MaskIndex - NumElts]; 2178 } 2179 } 2180 2181 if (SwapOps) { 2182 std::swap(V1, V2); 2183 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2184 } 2185 2186 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2187 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2188 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2189 2190 if (IsSelect) 2191 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2192 2193 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2194 // On such a large vector we're unable to use i8 as the index type. 2195 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2196 // may involve vector splitting if we're already at LMUL=8, or our 2197 // user-supplied maximum fixed-length LMUL. 2198 return SDValue(); 2199 } 2200 2201 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2202 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2203 MVT IndexVT = VT.changeTypeToInteger(); 2204 // Since we can't introduce illegal index types at this stage, use i16 and 2205 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2206 // than XLenVT. 2207 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2208 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2209 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2210 } 2211 2212 MVT IndexContainerVT = 2213 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2214 2215 SDValue Gather; 2216 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2217 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2218 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2219 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2220 } else { 2221 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2222 // If only one index is used, we can use a "splat" vrgather. 2223 // TODO: We can splat the most-common index and fix-up any stragglers, if 2224 // that's beneficial. 2225 if (LHSIndexCounts.size() == 1) { 2226 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2227 Gather = 2228 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2229 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2230 } else { 2231 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2232 LHSIndices = 2233 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2234 2235 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2236 TrueMask, VL); 2237 } 2238 } 2239 2240 // If a second vector operand is used by this shuffle, blend it in with an 2241 // additional vrgather. 2242 if (!V2.isUndef()) { 2243 V2 = convertToScalableVector(ContainerVT, V2, 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 (RHSIndexCounts.size() == 1) { 2248 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2249 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2250 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2251 } else { 2252 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2253 RHSIndices = 2254 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2255 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2256 VL); 2257 } 2258 2259 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2260 SelectMask = 2261 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2262 2263 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2264 Gather, VL); 2265 } 2266 2267 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2268 } 2269 2270 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2271 SDLoc DL, SelectionDAG &DAG, 2272 const RISCVSubtarget &Subtarget) { 2273 if (VT.isScalableVector()) 2274 return DAG.getFPExtendOrRound(Op, DL, VT); 2275 assert(VT.isFixedLengthVector() && 2276 "Unexpected value type for RVV FP extend/round lowering"); 2277 SDValue Mask, VL; 2278 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2279 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2280 ? RISCVISD::FP_EXTEND_VL 2281 : RISCVISD::FP_ROUND_VL; 2282 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2283 } 2284 2285 // While RVV has alignment restrictions, we should always be able to load as a 2286 // legal equivalently-sized byte-typed vector instead. This method is 2287 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2288 // the load is already correctly-aligned, it returns SDValue(). 2289 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2290 SelectionDAG &DAG) const { 2291 auto *Load = cast<LoadSDNode>(Op); 2292 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2293 2294 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2295 Load->getMemoryVT(), 2296 *Load->getMemOperand())) 2297 return SDValue(); 2298 2299 SDLoc DL(Op); 2300 MVT VT = Op.getSimpleValueType(); 2301 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2302 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2303 "Unexpected unaligned RVV load type"); 2304 MVT NewVT = 2305 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2306 assert(NewVT.isValid() && 2307 "Expecting equally-sized RVV vector types to be legal"); 2308 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2309 Load->getPointerInfo(), Load->getOriginalAlign(), 2310 Load->getMemOperand()->getFlags()); 2311 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2312 } 2313 2314 // While RVV has alignment restrictions, we should always be able to store as a 2315 // legal equivalently-sized byte-typed vector instead. This method is 2316 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2317 // returns SDValue() if the store is already correctly aligned. 2318 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2319 SelectionDAG &DAG) const { 2320 auto *Store = cast<StoreSDNode>(Op); 2321 assert(Store && Store->getValue().getValueType().isVector() && 2322 "Expected vector store"); 2323 2324 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2325 Store->getMemoryVT(), 2326 *Store->getMemOperand())) 2327 return SDValue(); 2328 2329 SDLoc DL(Op); 2330 SDValue StoredVal = Store->getValue(); 2331 MVT VT = StoredVal.getSimpleValueType(); 2332 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2333 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2334 "Unexpected unaligned RVV store type"); 2335 MVT NewVT = 2336 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2337 assert(NewVT.isValid() && 2338 "Expecting equally-sized RVV vector types to be legal"); 2339 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2340 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2341 Store->getPointerInfo(), Store->getOriginalAlign(), 2342 Store->getMemOperand()->getFlags()); 2343 } 2344 2345 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2346 SelectionDAG &DAG) const { 2347 switch (Op.getOpcode()) { 2348 default: 2349 report_fatal_error("unimplemented operand"); 2350 case ISD::GlobalAddress: 2351 return lowerGlobalAddress(Op, DAG); 2352 case ISD::BlockAddress: 2353 return lowerBlockAddress(Op, DAG); 2354 case ISD::ConstantPool: 2355 return lowerConstantPool(Op, DAG); 2356 case ISD::JumpTable: 2357 return lowerJumpTable(Op, DAG); 2358 case ISD::GlobalTLSAddress: 2359 return lowerGlobalTLSAddress(Op, DAG); 2360 case ISD::SELECT: 2361 return lowerSELECT(Op, DAG); 2362 case ISD::BRCOND: 2363 return lowerBRCOND(Op, DAG); 2364 case ISD::VASTART: 2365 return lowerVASTART(Op, DAG); 2366 case ISD::FRAMEADDR: 2367 return lowerFRAMEADDR(Op, DAG); 2368 case ISD::RETURNADDR: 2369 return lowerRETURNADDR(Op, DAG); 2370 case ISD::SHL_PARTS: 2371 return lowerShiftLeftParts(Op, DAG); 2372 case ISD::SRA_PARTS: 2373 return lowerShiftRightParts(Op, DAG, true); 2374 case ISD::SRL_PARTS: 2375 return lowerShiftRightParts(Op, DAG, false); 2376 case ISD::BITCAST: { 2377 SDLoc DL(Op); 2378 EVT VT = Op.getValueType(); 2379 SDValue Op0 = Op.getOperand(0); 2380 EVT Op0VT = Op0.getValueType(); 2381 MVT XLenVT = Subtarget.getXLenVT(); 2382 if (VT.isFixedLengthVector()) { 2383 // We can handle fixed length vector bitcasts with a simple replacement 2384 // in isel. 2385 if (Op0VT.isFixedLengthVector()) 2386 return Op; 2387 // When bitcasting from scalar to fixed-length vector, insert the scalar 2388 // into a one-element vector of the result type, and perform a vector 2389 // bitcast. 2390 if (!Op0VT.isVector()) { 2391 auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2392 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2393 DAG.getUNDEF(BVT), Op0, 2394 DAG.getConstant(0, DL, XLenVT))); 2395 } 2396 return SDValue(); 2397 } 2398 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2399 // thus: bitcast the vector to a one-element vector type whose element type 2400 // is the same as the result type, and extract the first element. 2401 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2402 LLVMContext &Context = *DAG.getContext(); 2403 SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0); 2404 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2405 DAG.getConstant(0, DL, XLenVT)); 2406 } 2407 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2408 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2409 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2410 return FPConv; 2411 } 2412 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2413 Subtarget.hasStdExtF()) { 2414 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2415 SDValue FPConv = 2416 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2417 return FPConv; 2418 } 2419 return SDValue(); 2420 } 2421 case ISD::INTRINSIC_WO_CHAIN: 2422 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2423 case ISD::INTRINSIC_W_CHAIN: 2424 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2425 case ISD::INTRINSIC_VOID: 2426 return LowerINTRINSIC_VOID(Op, DAG); 2427 case ISD::BSWAP: 2428 case ISD::BITREVERSE: { 2429 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2430 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2431 MVT VT = Op.getSimpleValueType(); 2432 SDLoc DL(Op); 2433 // Start with the maximum immediate value which is the bitwidth - 1. 2434 unsigned Imm = VT.getSizeInBits() - 1; 2435 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2436 if (Op.getOpcode() == ISD::BSWAP) 2437 Imm &= ~0x7U; 2438 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2439 DAG.getConstant(Imm, DL, VT)); 2440 } 2441 case ISD::FSHL: 2442 case ISD::FSHR: { 2443 MVT VT = Op.getSimpleValueType(); 2444 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2445 SDLoc DL(Op); 2446 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2447 return Op; 2448 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2449 // use log(XLen) bits. Mask the shift amount accordingly. 2450 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2451 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2452 DAG.getConstant(ShAmtWidth, DL, VT)); 2453 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2454 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2455 } 2456 case ISD::TRUNCATE: { 2457 SDLoc DL(Op); 2458 MVT VT = Op.getSimpleValueType(); 2459 // Only custom-lower vector truncates 2460 if (!VT.isVector()) 2461 return Op; 2462 2463 // Truncates to mask types are handled differently 2464 if (VT.getVectorElementType() == MVT::i1) 2465 return lowerVectorMaskTrunc(Op, DAG); 2466 2467 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2468 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2469 // truncate by one power of two at a time. 2470 MVT DstEltVT = VT.getVectorElementType(); 2471 2472 SDValue Src = Op.getOperand(0); 2473 MVT SrcVT = Src.getSimpleValueType(); 2474 MVT SrcEltVT = SrcVT.getVectorElementType(); 2475 2476 assert(DstEltVT.bitsLT(SrcEltVT) && 2477 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2478 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2479 "Unexpected vector truncate lowering"); 2480 2481 MVT ContainerVT = SrcVT; 2482 if (SrcVT.isFixedLengthVector()) { 2483 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2484 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2485 } 2486 2487 SDValue Result = Src; 2488 SDValue Mask, VL; 2489 std::tie(Mask, VL) = 2490 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2491 LLVMContext &Context = *DAG.getContext(); 2492 const ElementCount Count = ContainerVT.getVectorElementCount(); 2493 do { 2494 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2495 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2496 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2497 Mask, VL); 2498 } while (SrcEltVT != DstEltVT); 2499 2500 if (SrcVT.isFixedLengthVector()) 2501 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2502 2503 return Result; 2504 } 2505 case ISD::ANY_EXTEND: 2506 case ISD::ZERO_EXTEND: 2507 if (Op.getOperand(0).getValueType().isVector() && 2508 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2509 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2510 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2511 case ISD::SIGN_EXTEND: 2512 if (Op.getOperand(0).getValueType().isVector() && 2513 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2514 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2515 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2516 case ISD::SPLAT_VECTOR_PARTS: 2517 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2518 case ISD::INSERT_VECTOR_ELT: 2519 return lowerINSERT_VECTOR_ELT(Op, DAG); 2520 case ISD::EXTRACT_VECTOR_ELT: 2521 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2522 case ISD::VSCALE: { 2523 MVT VT = Op.getSimpleValueType(); 2524 SDLoc DL(Op); 2525 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2526 // We define our scalable vector types for lmul=1 to use a 64 bit known 2527 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2528 // vscale as VLENB / 8. 2529 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2530 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2531 // We assume VLENB is a multiple of 8. We manually choose the best shift 2532 // here because SimplifyDemandedBits isn't always able to simplify it. 2533 uint64_t Val = Op.getConstantOperandVal(0); 2534 if (isPowerOf2_64(Val)) { 2535 uint64_t Log2 = Log2_64(Val); 2536 if (Log2 < 3) 2537 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2538 DAG.getConstant(3 - Log2, DL, VT)); 2539 if (Log2 > 3) 2540 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2541 DAG.getConstant(Log2 - 3, DL, VT)); 2542 return VLENB; 2543 } 2544 // If the multiplier is a multiple of 8, scale it down to avoid needing 2545 // to shift the VLENB value. 2546 if ((Val % 8) == 0) 2547 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2548 DAG.getConstant(Val / 8, DL, VT)); 2549 } 2550 2551 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2552 DAG.getConstant(3, DL, VT)); 2553 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2554 } 2555 case ISD::FP_EXTEND: { 2556 // RVV can only do fp_extend to types double the size as the source. We 2557 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2558 // via f32. 2559 SDLoc DL(Op); 2560 MVT VT = Op.getSimpleValueType(); 2561 SDValue Src = Op.getOperand(0); 2562 MVT SrcVT = Src.getSimpleValueType(); 2563 2564 // Prepare any fixed-length vector operands. 2565 MVT ContainerVT = VT; 2566 if (SrcVT.isFixedLengthVector()) { 2567 ContainerVT = getContainerForFixedLengthVector(VT); 2568 MVT SrcContainerVT = 2569 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2570 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2571 } 2572 2573 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2574 SrcVT.getVectorElementType() != MVT::f16) { 2575 // For scalable vectors, we only need to close the gap between 2576 // vXf16->vXf64. 2577 if (!VT.isFixedLengthVector()) 2578 return Op; 2579 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2580 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2581 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2582 } 2583 2584 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2585 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2586 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2587 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2588 2589 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2590 DL, DAG, Subtarget); 2591 if (VT.isFixedLengthVector()) 2592 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2593 return Extend; 2594 } 2595 case ISD::FP_ROUND: { 2596 // RVV can only do fp_round to types half the size as the source. We 2597 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2598 // conversion instruction. 2599 SDLoc DL(Op); 2600 MVT VT = Op.getSimpleValueType(); 2601 SDValue Src = Op.getOperand(0); 2602 MVT SrcVT = Src.getSimpleValueType(); 2603 2604 // Prepare any fixed-length vector operands. 2605 MVT ContainerVT = VT; 2606 if (VT.isFixedLengthVector()) { 2607 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2608 ContainerVT = 2609 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2610 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2611 } 2612 2613 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2614 SrcVT.getVectorElementType() != MVT::f64) { 2615 // For scalable vectors, we only need to close the gap between 2616 // vXf64<->vXf16. 2617 if (!VT.isFixedLengthVector()) 2618 return Op; 2619 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2620 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2621 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2622 } 2623 2624 SDValue Mask, VL; 2625 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2626 2627 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2628 SDValue IntermediateRound = 2629 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2630 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2631 DL, DAG, Subtarget); 2632 2633 if (VT.isFixedLengthVector()) 2634 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2635 return Round; 2636 } 2637 case ISD::FP_TO_SINT: 2638 case ISD::FP_TO_UINT: 2639 case ISD::SINT_TO_FP: 2640 case ISD::UINT_TO_FP: { 2641 // RVV can only do fp<->int conversions to types half/double the size as 2642 // the source. We custom-lower any conversions that do two hops into 2643 // sequences. 2644 MVT VT = Op.getSimpleValueType(); 2645 if (!VT.isVector()) 2646 return Op; 2647 SDLoc DL(Op); 2648 SDValue Src = Op.getOperand(0); 2649 MVT EltVT = VT.getVectorElementType(); 2650 MVT SrcVT = Src.getSimpleValueType(); 2651 MVT SrcEltVT = SrcVT.getVectorElementType(); 2652 unsigned EltSize = EltVT.getSizeInBits(); 2653 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2654 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2655 "Unexpected vector element types"); 2656 2657 bool IsInt2FP = SrcEltVT.isInteger(); 2658 // Widening conversions 2659 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2660 if (IsInt2FP) { 2661 // Do a regular integer sign/zero extension then convert to float. 2662 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2663 VT.getVectorElementCount()); 2664 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2665 ? ISD::ZERO_EXTEND 2666 : ISD::SIGN_EXTEND; 2667 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2668 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2669 } 2670 // FP2Int 2671 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2672 // Do one doubling fp_extend then complete the operation by converting 2673 // to int. 2674 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2675 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2676 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2677 } 2678 2679 // Narrowing conversions 2680 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2681 if (IsInt2FP) { 2682 // One narrowing int_to_fp, then an fp_round. 2683 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2684 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2685 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2686 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2687 } 2688 // FP2Int 2689 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2690 // representable by the integer, the result is poison. 2691 MVT IVecVT = 2692 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2693 VT.getVectorElementCount()); 2694 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2695 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2696 } 2697 2698 // Scalable vectors can exit here. Patterns will handle equally-sized 2699 // conversions halving/doubling ones. 2700 if (!VT.isFixedLengthVector()) 2701 return Op; 2702 2703 // For fixed-length vectors we lower to a custom "VL" node. 2704 unsigned RVVOpc = 0; 2705 switch (Op.getOpcode()) { 2706 default: 2707 llvm_unreachable("Impossible opcode"); 2708 case ISD::FP_TO_SINT: 2709 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2710 break; 2711 case ISD::FP_TO_UINT: 2712 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2713 break; 2714 case ISD::SINT_TO_FP: 2715 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2716 break; 2717 case ISD::UINT_TO_FP: 2718 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2719 break; 2720 } 2721 2722 MVT ContainerVT, SrcContainerVT; 2723 // Derive the reference container type from the larger vector type. 2724 if (SrcEltSize > EltSize) { 2725 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2726 ContainerVT = 2727 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2728 } else { 2729 ContainerVT = getContainerForFixedLengthVector(VT); 2730 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2731 } 2732 2733 SDValue Mask, VL; 2734 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2735 2736 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2737 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 2738 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2739 } 2740 case ISD::FP_TO_SINT_SAT: 2741 case ISD::FP_TO_UINT_SAT: 2742 return lowerFP_TO_INT_SAT(Op, DAG); 2743 case ISD::VECREDUCE_ADD: 2744 case ISD::VECREDUCE_UMAX: 2745 case ISD::VECREDUCE_SMAX: 2746 case ISD::VECREDUCE_UMIN: 2747 case ISD::VECREDUCE_SMIN: 2748 return lowerVECREDUCE(Op, DAG); 2749 case ISD::VECREDUCE_AND: 2750 case ISD::VECREDUCE_OR: 2751 case ISD::VECREDUCE_XOR: 2752 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2753 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 2754 return lowerVECREDUCE(Op, DAG); 2755 case ISD::VECREDUCE_FADD: 2756 case ISD::VECREDUCE_SEQ_FADD: 2757 case ISD::VECREDUCE_FMIN: 2758 case ISD::VECREDUCE_FMAX: 2759 return lowerFPVECREDUCE(Op, DAG); 2760 case ISD::VP_REDUCE_ADD: 2761 case ISD::VP_REDUCE_UMAX: 2762 case ISD::VP_REDUCE_SMAX: 2763 case ISD::VP_REDUCE_UMIN: 2764 case ISD::VP_REDUCE_SMIN: 2765 case ISD::VP_REDUCE_FADD: 2766 case ISD::VP_REDUCE_SEQ_FADD: 2767 case ISD::VP_REDUCE_FMIN: 2768 case ISD::VP_REDUCE_FMAX: 2769 return lowerVPREDUCE(Op, DAG); 2770 case ISD::VP_REDUCE_AND: 2771 case ISD::VP_REDUCE_OR: 2772 case ISD::VP_REDUCE_XOR: 2773 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 2774 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 2775 return lowerVPREDUCE(Op, DAG); 2776 case ISD::INSERT_SUBVECTOR: 2777 return lowerINSERT_SUBVECTOR(Op, DAG); 2778 case ISD::EXTRACT_SUBVECTOR: 2779 return lowerEXTRACT_SUBVECTOR(Op, DAG); 2780 case ISD::STEP_VECTOR: 2781 return lowerSTEP_VECTOR(Op, DAG); 2782 case ISD::VECTOR_REVERSE: 2783 return lowerVECTOR_REVERSE(Op, DAG); 2784 case ISD::BUILD_VECTOR: 2785 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 2786 case ISD::SPLAT_VECTOR: 2787 if (Op.getValueType().getVectorElementType() == MVT::i1) 2788 return lowerVectorMaskSplat(Op, DAG); 2789 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 2790 case ISD::VECTOR_SHUFFLE: 2791 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 2792 case ISD::CONCAT_VECTORS: { 2793 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 2794 // better than going through the stack, as the default expansion does. 2795 SDLoc DL(Op); 2796 MVT VT = Op.getSimpleValueType(); 2797 unsigned NumOpElts = 2798 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 2799 SDValue Vec = DAG.getUNDEF(VT); 2800 for (const auto &OpIdx : enumerate(Op->ops())) 2801 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 2802 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 2803 return Vec; 2804 } 2805 case ISD::LOAD: 2806 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 2807 return V; 2808 if (Op.getValueType().isFixedLengthVector()) 2809 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 2810 return Op; 2811 case ISD::STORE: 2812 if (auto V = expandUnalignedRVVStore(Op, DAG)) 2813 return V; 2814 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 2815 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 2816 return Op; 2817 case ISD::MLOAD: 2818 case ISD::VP_LOAD: 2819 return lowerMaskedLoad(Op, DAG); 2820 case ISD::MSTORE: 2821 case ISD::VP_STORE: 2822 return lowerMaskedStore(Op, DAG); 2823 case ISD::SETCC: 2824 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 2825 case ISD::ADD: 2826 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 2827 case ISD::SUB: 2828 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 2829 case ISD::MUL: 2830 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 2831 case ISD::MULHS: 2832 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 2833 case ISD::MULHU: 2834 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 2835 case ISD::AND: 2836 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 2837 RISCVISD::AND_VL); 2838 case ISD::OR: 2839 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 2840 RISCVISD::OR_VL); 2841 case ISD::XOR: 2842 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 2843 RISCVISD::XOR_VL); 2844 case ISD::SDIV: 2845 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 2846 case ISD::SREM: 2847 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 2848 case ISD::UDIV: 2849 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 2850 case ISD::UREM: 2851 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 2852 case ISD::SHL: 2853 case ISD::SRA: 2854 case ISD::SRL: 2855 if (Op.getSimpleValueType().isFixedLengthVector()) 2856 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 2857 // This can be called for an i32 shift amount that needs to be promoted. 2858 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 2859 "Unexpected custom legalisation"); 2860 return SDValue(); 2861 case ISD::SADDSAT: 2862 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 2863 case ISD::UADDSAT: 2864 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 2865 case ISD::SSUBSAT: 2866 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 2867 case ISD::USUBSAT: 2868 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 2869 case ISD::FADD: 2870 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 2871 case ISD::FSUB: 2872 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 2873 case ISD::FMUL: 2874 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 2875 case ISD::FDIV: 2876 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 2877 case ISD::FNEG: 2878 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 2879 case ISD::FABS: 2880 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 2881 case ISD::FSQRT: 2882 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 2883 case ISD::FMA: 2884 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 2885 case ISD::SMIN: 2886 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 2887 case ISD::SMAX: 2888 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 2889 case ISD::UMIN: 2890 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 2891 case ISD::UMAX: 2892 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 2893 case ISD::FMINNUM: 2894 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 2895 case ISD::FMAXNUM: 2896 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 2897 case ISD::ABS: 2898 return lowerABS(Op, DAG); 2899 case ISD::VSELECT: 2900 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 2901 case ISD::FCOPYSIGN: 2902 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 2903 case ISD::MGATHER: 2904 case ISD::VP_GATHER: 2905 return lowerMaskedGather(Op, DAG); 2906 case ISD::MSCATTER: 2907 case ISD::VP_SCATTER: 2908 return lowerMaskedScatter(Op, DAG); 2909 case ISD::FLT_ROUNDS_: 2910 return lowerGET_ROUNDING(Op, DAG); 2911 case ISD::SET_ROUNDING: 2912 return lowerSET_ROUNDING(Op, DAG); 2913 case ISD::VP_ADD: 2914 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 2915 case ISD::VP_SUB: 2916 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 2917 case ISD::VP_MUL: 2918 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 2919 case ISD::VP_SDIV: 2920 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 2921 case ISD::VP_UDIV: 2922 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 2923 case ISD::VP_SREM: 2924 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 2925 case ISD::VP_UREM: 2926 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 2927 case ISD::VP_AND: 2928 return lowerVPOp(Op, DAG, RISCVISD::AND_VL); 2929 case ISD::VP_OR: 2930 return lowerVPOp(Op, DAG, RISCVISD::OR_VL); 2931 case ISD::VP_XOR: 2932 return lowerVPOp(Op, DAG, RISCVISD::XOR_VL); 2933 case ISD::VP_ASHR: 2934 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 2935 case ISD::VP_LSHR: 2936 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 2937 case ISD::VP_SHL: 2938 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 2939 case ISD::VP_FADD: 2940 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 2941 case ISD::VP_FSUB: 2942 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 2943 case ISD::VP_FMUL: 2944 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 2945 case ISD::VP_FDIV: 2946 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 2947 } 2948 } 2949 2950 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 2951 SelectionDAG &DAG, unsigned Flags) { 2952 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 2953 } 2954 2955 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 2956 SelectionDAG &DAG, unsigned Flags) { 2957 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 2958 Flags); 2959 } 2960 2961 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 2962 SelectionDAG &DAG, unsigned Flags) { 2963 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 2964 N->getOffset(), Flags); 2965 } 2966 2967 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 2968 SelectionDAG &DAG, unsigned Flags) { 2969 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 2970 } 2971 2972 template <class NodeTy> 2973 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 2974 bool IsLocal) const { 2975 SDLoc DL(N); 2976 EVT Ty = getPointerTy(DAG.getDataLayout()); 2977 2978 if (isPositionIndependent()) { 2979 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 2980 if (IsLocal) 2981 // Use PC-relative addressing to access the symbol. This generates the 2982 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 2983 // %pcrel_lo(auipc)). 2984 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 2985 2986 // Use PC-relative addressing to access the GOT for this symbol, then load 2987 // the address from the GOT. This generates the pattern (PseudoLA sym), 2988 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 2989 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 2990 } 2991 2992 switch (getTargetMachine().getCodeModel()) { 2993 default: 2994 report_fatal_error("Unsupported code model for lowering"); 2995 case CodeModel::Small: { 2996 // Generate a sequence for accessing addresses within the first 2 GiB of 2997 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 2998 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 2999 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3000 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3001 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3002 } 3003 case CodeModel::Medium: { 3004 // Generate a sequence for accessing addresses within any 2GiB range within 3005 // the address space. This generates the pattern (PseudoLLA sym), which 3006 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3007 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3008 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3009 } 3010 } 3011 } 3012 3013 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3014 SelectionDAG &DAG) const { 3015 SDLoc DL(Op); 3016 EVT Ty = Op.getValueType(); 3017 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3018 int64_t Offset = N->getOffset(); 3019 MVT XLenVT = Subtarget.getXLenVT(); 3020 3021 const GlobalValue *GV = N->getGlobal(); 3022 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3023 SDValue Addr = getAddr(N, DAG, IsLocal); 3024 3025 // In order to maximise the opportunity for common subexpression elimination, 3026 // emit a separate ADD node for the global address offset instead of folding 3027 // it in the global address node. Later peephole optimisations may choose to 3028 // fold it back in when profitable. 3029 if (Offset != 0) 3030 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3031 DAG.getConstant(Offset, DL, XLenVT)); 3032 return Addr; 3033 } 3034 3035 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3036 SelectionDAG &DAG) const { 3037 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3038 3039 return getAddr(N, DAG); 3040 } 3041 3042 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3043 SelectionDAG &DAG) const { 3044 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3045 3046 return getAddr(N, DAG); 3047 } 3048 3049 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3050 SelectionDAG &DAG) const { 3051 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3052 3053 return getAddr(N, DAG); 3054 } 3055 3056 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3057 SelectionDAG &DAG, 3058 bool UseGOT) const { 3059 SDLoc DL(N); 3060 EVT Ty = getPointerTy(DAG.getDataLayout()); 3061 const GlobalValue *GV = N->getGlobal(); 3062 MVT XLenVT = Subtarget.getXLenVT(); 3063 3064 if (UseGOT) { 3065 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3066 // load the address from the GOT and add the thread pointer. This generates 3067 // the pattern (PseudoLA_TLS_IE sym), which expands to 3068 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3069 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3070 SDValue Load = 3071 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3072 3073 // Add the thread pointer. 3074 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3075 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3076 } 3077 3078 // Generate a sequence for accessing the address relative to the thread 3079 // pointer, with the appropriate adjustment for the thread pointer offset. 3080 // This generates the pattern 3081 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3082 SDValue AddrHi = 3083 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3084 SDValue AddrAdd = 3085 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3086 SDValue AddrLo = 3087 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3088 3089 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3090 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3091 SDValue MNAdd = SDValue( 3092 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3093 0); 3094 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3095 } 3096 3097 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3098 SelectionDAG &DAG) const { 3099 SDLoc DL(N); 3100 EVT Ty = getPointerTy(DAG.getDataLayout()); 3101 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3102 const GlobalValue *GV = N->getGlobal(); 3103 3104 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3105 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3106 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3107 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3108 SDValue Load = 3109 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3110 3111 // Prepare argument list to generate call. 3112 ArgListTy Args; 3113 ArgListEntry Entry; 3114 Entry.Node = Load; 3115 Entry.Ty = CallTy; 3116 Args.push_back(Entry); 3117 3118 // Setup call to __tls_get_addr. 3119 TargetLowering::CallLoweringInfo CLI(DAG); 3120 CLI.setDebugLoc(DL) 3121 .setChain(DAG.getEntryNode()) 3122 .setLibCallee(CallingConv::C, CallTy, 3123 DAG.getExternalSymbol("__tls_get_addr", Ty), 3124 std::move(Args)); 3125 3126 return LowerCallTo(CLI).first; 3127 } 3128 3129 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3130 SelectionDAG &DAG) const { 3131 SDLoc DL(Op); 3132 EVT Ty = Op.getValueType(); 3133 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3134 int64_t Offset = N->getOffset(); 3135 MVT XLenVT = Subtarget.getXLenVT(); 3136 3137 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3138 3139 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3140 CallingConv::GHC) 3141 report_fatal_error("In GHC calling convention TLS is not supported"); 3142 3143 SDValue Addr; 3144 switch (Model) { 3145 case TLSModel::LocalExec: 3146 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3147 break; 3148 case TLSModel::InitialExec: 3149 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3150 break; 3151 case TLSModel::LocalDynamic: 3152 case TLSModel::GeneralDynamic: 3153 Addr = getDynamicTLSAddr(N, DAG); 3154 break; 3155 } 3156 3157 // In order to maximise the opportunity for common subexpression elimination, 3158 // emit a separate ADD node for the global address offset instead of folding 3159 // it in the global address node. Later peephole optimisations may choose to 3160 // fold it back in when profitable. 3161 if (Offset != 0) 3162 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3163 DAG.getConstant(Offset, DL, XLenVT)); 3164 return Addr; 3165 } 3166 3167 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3168 SDValue CondV = Op.getOperand(0); 3169 SDValue TrueV = Op.getOperand(1); 3170 SDValue FalseV = Op.getOperand(2); 3171 SDLoc DL(Op); 3172 MVT VT = Op.getSimpleValueType(); 3173 MVT XLenVT = Subtarget.getXLenVT(); 3174 3175 // Lower vector SELECTs to VSELECTs by splatting the condition. 3176 if (VT.isVector()) { 3177 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3178 SDValue CondSplat = VT.isScalableVector() 3179 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3180 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3181 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3182 } 3183 3184 // If the result type is XLenVT and CondV is the output of a SETCC node 3185 // which also operated on XLenVT inputs, then merge the SETCC node into the 3186 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3187 // compare+branch instructions. i.e.: 3188 // (select (setcc lhs, rhs, cc), truev, falsev) 3189 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3190 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3191 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3192 SDValue LHS = CondV.getOperand(0); 3193 SDValue RHS = CondV.getOperand(1); 3194 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3195 ISD::CondCode CCVal = CC->get(); 3196 3197 // Special case for a select of 2 constants that have a diffence of 1. 3198 // Normally this is done by DAGCombine, but if the select is introduced by 3199 // type legalization or op legalization, we miss it. Restricting to SETLT 3200 // case for now because that is what signed saturating add/sub need. 3201 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3202 // but we would probably want to swap the true/false values if the condition 3203 // is SETGE/SETLE to avoid an XORI. 3204 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3205 CCVal == ISD::SETLT) { 3206 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3207 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3208 if (TrueVal - 1 == FalseVal) 3209 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3210 if (TrueVal + 1 == FalseVal) 3211 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3212 } 3213 3214 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3215 3216 SDValue TargetCC = DAG.getCondCode(CCVal); 3217 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3218 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3219 } 3220 3221 // Otherwise: 3222 // (select condv, truev, falsev) 3223 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3224 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3225 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3226 3227 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3228 3229 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3230 } 3231 3232 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3233 SDValue CondV = Op.getOperand(1); 3234 SDLoc DL(Op); 3235 MVT XLenVT = Subtarget.getXLenVT(); 3236 3237 if (CondV.getOpcode() == ISD::SETCC && 3238 CondV.getOperand(0).getValueType() == XLenVT) { 3239 SDValue LHS = CondV.getOperand(0); 3240 SDValue RHS = CondV.getOperand(1); 3241 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3242 3243 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3244 3245 SDValue TargetCC = DAG.getCondCode(CCVal); 3246 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3247 LHS, RHS, TargetCC, Op.getOperand(2)); 3248 } 3249 3250 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3251 CondV, DAG.getConstant(0, DL, XLenVT), 3252 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3253 } 3254 3255 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3256 MachineFunction &MF = DAG.getMachineFunction(); 3257 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3258 3259 SDLoc DL(Op); 3260 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3261 getPointerTy(MF.getDataLayout())); 3262 3263 // vastart just stores the address of the VarArgsFrameIndex slot into the 3264 // memory location argument. 3265 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3266 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3267 MachinePointerInfo(SV)); 3268 } 3269 3270 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3271 SelectionDAG &DAG) const { 3272 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3273 MachineFunction &MF = DAG.getMachineFunction(); 3274 MachineFrameInfo &MFI = MF.getFrameInfo(); 3275 MFI.setFrameAddressIsTaken(true); 3276 Register FrameReg = RI.getFrameRegister(MF); 3277 int XLenInBytes = Subtarget.getXLen() / 8; 3278 3279 EVT VT = Op.getValueType(); 3280 SDLoc DL(Op); 3281 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3282 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3283 while (Depth--) { 3284 int Offset = -(XLenInBytes * 2); 3285 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3286 DAG.getIntPtrConstant(Offset, DL)); 3287 FrameAddr = 3288 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3289 } 3290 return FrameAddr; 3291 } 3292 3293 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3294 SelectionDAG &DAG) const { 3295 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3296 MachineFunction &MF = DAG.getMachineFunction(); 3297 MachineFrameInfo &MFI = MF.getFrameInfo(); 3298 MFI.setReturnAddressIsTaken(true); 3299 MVT XLenVT = Subtarget.getXLenVT(); 3300 int XLenInBytes = Subtarget.getXLen() / 8; 3301 3302 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3303 return SDValue(); 3304 3305 EVT VT = Op.getValueType(); 3306 SDLoc DL(Op); 3307 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3308 if (Depth) { 3309 int Off = -XLenInBytes; 3310 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3311 SDValue Offset = DAG.getConstant(Off, DL, VT); 3312 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3313 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3314 MachinePointerInfo()); 3315 } 3316 3317 // Return the value of the return address register, marking it an implicit 3318 // live-in. 3319 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3320 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3321 } 3322 3323 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3324 SelectionDAG &DAG) const { 3325 SDLoc DL(Op); 3326 SDValue Lo = Op.getOperand(0); 3327 SDValue Hi = Op.getOperand(1); 3328 SDValue Shamt = Op.getOperand(2); 3329 EVT VT = Lo.getValueType(); 3330 3331 // if Shamt-XLEN < 0: // Shamt < XLEN 3332 // Lo = Lo << Shamt 3333 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3334 // else: 3335 // Lo = 0 3336 // Hi = Lo << (Shamt-XLEN) 3337 3338 SDValue Zero = DAG.getConstant(0, DL, VT); 3339 SDValue One = DAG.getConstant(1, DL, VT); 3340 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3341 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3342 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3343 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3344 3345 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3346 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3347 SDValue ShiftRightLo = 3348 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3349 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3350 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3351 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3352 3353 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3354 3355 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3356 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3357 3358 SDValue Parts[2] = {Lo, Hi}; 3359 return DAG.getMergeValues(Parts, DL); 3360 } 3361 3362 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3363 bool IsSRA) const { 3364 SDLoc DL(Op); 3365 SDValue Lo = Op.getOperand(0); 3366 SDValue Hi = Op.getOperand(1); 3367 SDValue Shamt = Op.getOperand(2); 3368 EVT VT = Lo.getValueType(); 3369 3370 // SRA expansion: 3371 // if Shamt-XLEN < 0: // Shamt < XLEN 3372 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3373 // Hi = Hi >>s Shamt 3374 // else: 3375 // Lo = Hi >>s (Shamt-XLEN); 3376 // Hi = Hi >>s (XLEN-1) 3377 // 3378 // SRL expansion: 3379 // if Shamt-XLEN < 0: // Shamt < XLEN 3380 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3381 // Hi = Hi >>u Shamt 3382 // else: 3383 // Lo = Hi >>u (Shamt-XLEN); 3384 // Hi = 0; 3385 3386 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3387 3388 SDValue Zero = DAG.getConstant(0, DL, VT); 3389 SDValue One = DAG.getConstant(1, DL, VT); 3390 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3391 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3392 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3393 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3394 3395 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3396 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3397 SDValue ShiftLeftHi = 3398 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3399 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3400 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3401 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3402 SDValue HiFalse = 3403 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3404 3405 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3406 3407 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3408 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3409 3410 SDValue Parts[2] = {Lo, Hi}; 3411 return DAG.getMergeValues(Parts, DL); 3412 } 3413 3414 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3415 // legal equivalently-sized i8 type, so we can use that as a go-between. 3416 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3417 SelectionDAG &DAG) const { 3418 SDLoc DL(Op); 3419 MVT VT = Op.getSimpleValueType(); 3420 SDValue SplatVal = Op.getOperand(0); 3421 // All-zeros or all-ones splats are handled specially. 3422 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3423 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3424 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3425 } 3426 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3427 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3428 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3429 } 3430 MVT XLenVT = Subtarget.getXLenVT(); 3431 assert(SplatVal.getValueType() == XLenVT && 3432 "Unexpected type for i1 splat value"); 3433 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3434 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3435 DAG.getConstant(1, DL, XLenVT)); 3436 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3437 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3438 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3439 } 3440 3441 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3442 // illegal (currently only vXi64 RV32). 3443 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3444 // them to SPLAT_VECTOR_I64 3445 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3446 SelectionDAG &DAG) const { 3447 SDLoc DL(Op); 3448 MVT VecVT = Op.getSimpleValueType(); 3449 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3450 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3451 3452 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3453 SDValue Lo = Op.getOperand(0); 3454 SDValue Hi = Op.getOperand(1); 3455 3456 if (VecVT.isFixedLengthVector()) { 3457 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3458 SDLoc DL(Op); 3459 SDValue Mask, VL; 3460 std::tie(Mask, VL) = 3461 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3462 3463 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3464 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3465 } 3466 3467 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3468 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3469 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3470 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3471 // node in order to try and match RVV vector/scalar instructions. 3472 if ((LoC >> 31) == HiC) 3473 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3474 } 3475 3476 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3477 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3478 isa<ConstantSDNode>(Hi.getOperand(1)) && 3479 Hi.getConstantOperandVal(1) == 31) 3480 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3481 3482 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3483 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3484 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3485 } 3486 3487 // Custom-lower extensions from mask vectors by using a vselect either with 1 3488 // for zero/any-extension or -1 for sign-extension: 3489 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3490 // Note that any-extension is lowered identically to zero-extension. 3491 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3492 int64_t ExtTrueVal) const { 3493 SDLoc DL(Op); 3494 MVT VecVT = Op.getSimpleValueType(); 3495 SDValue Src = Op.getOperand(0); 3496 // Only custom-lower extensions from mask types 3497 assert(Src.getValueType().isVector() && 3498 Src.getValueType().getVectorElementType() == MVT::i1); 3499 3500 MVT XLenVT = Subtarget.getXLenVT(); 3501 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3502 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3503 3504 if (VecVT.isScalableVector()) { 3505 // Be careful not to introduce illegal scalar types at this stage, and be 3506 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3507 // illegal and must be expanded. Since we know that the constants are 3508 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3509 bool IsRV32E64 = 3510 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3511 3512 if (!IsRV32E64) { 3513 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3514 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3515 } else { 3516 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3517 SplatTrueVal = 3518 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3519 } 3520 3521 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3522 } 3523 3524 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3525 MVT I1ContainerVT = 3526 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3527 3528 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3529 3530 SDValue Mask, VL; 3531 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3532 3533 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3534 SplatTrueVal = 3535 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3536 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3537 SplatTrueVal, SplatZero, VL); 3538 3539 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3540 } 3541 3542 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3543 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3544 MVT ExtVT = Op.getSimpleValueType(); 3545 // Only custom-lower extensions from fixed-length vector types. 3546 if (!ExtVT.isFixedLengthVector()) 3547 return Op; 3548 MVT VT = Op.getOperand(0).getSimpleValueType(); 3549 // Grab the canonical container type for the extended type. Infer the smaller 3550 // type from that to ensure the same number of vector elements, as we know 3551 // the LMUL will be sufficient to hold the smaller type. 3552 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3553 // Get the extended container type manually to ensure the same number of 3554 // vector elements between source and dest. 3555 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3556 ContainerExtVT.getVectorElementCount()); 3557 3558 SDValue Op1 = 3559 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3560 3561 SDLoc DL(Op); 3562 SDValue Mask, VL; 3563 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3564 3565 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3566 3567 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3568 } 3569 3570 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3571 // setcc operation: 3572 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3573 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3574 SelectionDAG &DAG) const { 3575 SDLoc DL(Op); 3576 EVT MaskVT = Op.getValueType(); 3577 // Only expect to custom-lower truncations to mask types 3578 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3579 "Unexpected type for vector mask lowering"); 3580 SDValue Src = Op.getOperand(0); 3581 MVT VecVT = Src.getSimpleValueType(); 3582 3583 // If this is a fixed vector, we need to convert it to a scalable vector. 3584 MVT ContainerVT = VecVT; 3585 if (VecVT.isFixedLengthVector()) { 3586 ContainerVT = getContainerForFixedLengthVector(VecVT); 3587 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3588 } 3589 3590 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3591 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3592 3593 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3594 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3595 3596 if (VecVT.isScalableVector()) { 3597 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3598 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3599 } 3600 3601 SDValue Mask, VL; 3602 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3603 3604 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3605 SDValue Trunc = 3606 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3607 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3608 DAG.getCondCode(ISD::SETNE), Mask, VL); 3609 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3610 } 3611 3612 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3613 // first position of a vector, and that vector is slid up to the insert index. 3614 // By limiting the active vector length to index+1 and merging with the 3615 // original vector (with an undisturbed tail policy for elements >= VL), we 3616 // achieve the desired result of leaving all elements untouched except the one 3617 // at VL-1, which is replaced with the desired value. 3618 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3619 SelectionDAG &DAG) const { 3620 SDLoc DL(Op); 3621 MVT VecVT = Op.getSimpleValueType(); 3622 SDValue Vec = Op.getOperand(0); 3623 SDValue Val = Op.getOperand(1); 3624 SDValue Idx = Op.getOperand(2); 3625 3626 if (VecVT.getVectorElementType() == MVT::i1) { 3627 // FIXME: For now we just promote to an i8 vector and insert into that, 3628 // but this is probably not optimal. 3629 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3630 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3631 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3632 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3633 } 3634 3635 MVT ContainerVT = VecVT; 3636 // If the operand is a fixed-length vector, convert to a scalable one. 3637 if (VecVT.isFixedLengthVector()) { 3638 ContainerVT = getContainerForFixedLengthVector(VecVT); 3639 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3640 } 3641 3642 MVT XLenVT = Subtarget.getXLenVT(); 3643 3644 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3645 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3646 // Even i64-element vectors on RV32 can be lowered without scalar 3647 // legalization if the most-significant 32 bits of the value are not affected 3648 // by the sign-extension of the lower 32 bits. 3649 // TODO: We could also catch sign extensions of a 32-bit value. 3650 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3651 const auto *CVal = cast<ConstantSDNode>(Val); 3652 if (isInt<32>(CVal->getSExtValue())) { 3653 IsLegalInsert = true; 3654 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3655 } 3656 } 3657 3658 SDValue Mask, VL; 3659 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3660 3661 SDValue ValInVec; 3662 3663 if (IsLegalInsert) { 3664 unsigned Opc = 3665 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3666 if (isNullConstant(Idx)) { 3667 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3668 if (!VecVT.isFixedLengthVector()) 3669 return Vec; 3670 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3671 } 3672 ValInVec = 3673 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3674 } else { 3675 // On RV32, i64-element vectors must be specially handled to place the 3676 // value at element 0, by using two vslide1up instructions in sequence on 3677 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3678 // this. 3679 SDValue One = DAG.getConstant(1, DL, XLenVT); 3680 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3681 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3682 MVT I32ContainerVT = 3683 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3684 SDValue I32Mask = 3685 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3686 // Limit the active VL to two. 3687 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3688 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3689 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3690 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3691 InsertI64VL); 3692 // First slide in the hi value, then the lo in underneath it. 3693 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3694 ValHi, I32Mask, InsertI64VL); 3695 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3696 ValLo, I32Mask, InsertI64VL); 3697 // Bitcast back to the right container type. 3698 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3699 } 3700 3701 // Now that the value is in a vector, slide it into position. 3702 SDValue InsertVL = 3703 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3704 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3705 ValInVec, Idx, Mask, InsertVL); 3706 if (!VecVT.isFixedLengthVector()) 3707 return Slideup; 3708 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3709 } 3710 3711 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3712 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3713 // types this is done using VMV_X_S to allow us to glean information about the 3714 // sign bits of the result. 3715 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3716 SelectionDAG &DAG) const { 3717 SDLoc DL(Op); 3718 SDValue Idx = Op.getOperand(1); 3719 SDValue Vec = Op.getOperand(0); 3720 EVT EltVT = Op.getValueType(); 3721 MVT VecVT = Vec.getSimpleValueType(); 3722 MVT XLenVT = Subtarget.getXLenVT(); 3723 3724 if (VecVT.getVectorElementType() == MVT::i1) { 3725 // FIXME: For now we just promote to an i8 vector and extract from that, 3726 // but this is probably not optimal. 3727 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3728 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3729 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 3730 } 3731 3732 // If this is a fixed vector, we need to convert it to a scalable vector. 3733 MVT ContainerVT = VecVT; 3734 if (VecVT.isFixedLengthVector()) { 3735 ContainerVT = getContainerForFixedLengthVector(VecVT); 3736 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3737 } 3738 3739 // If the index is 0, the vector is already in the right position. 3740 if (!isNullConstant(Idx)) { 3741 // Use a VL of 1 to avoid processing more elements than we need. 3742 SDValue VL = DAG.getConstant(1, DL, XLenVT); 3743 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3744 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3745 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3746 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 3747 } 3748 3749 if (!EltVT.isInteger()) { 3750 // Floating-point extracts are handled in TableGen. 3751 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 3752 DAG.getConstant(0, DL, XLenVT)); 3753 } 3754 3755 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 3756 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 3757 } 3758 3759 // Some RVV intrinsics may claim that they want an integer operand to be 3760 // promoted or expanded. 3761 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 3762 const RISCVSubtarget &Subtarget) { 3763 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3764 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 3765 "Unexpected opcode"); 3766 3767 if (!Subtarget.hasStdExtV()) 3768 return SDValue(); 3769 3770 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 3771 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 3772 SDLoc DL(Op); 3773 3774 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 3775 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 3776 if (!II || !II->SplatOperand) 3777 return SDValue(); 3778 3779 unsigned SplatOp = II->SplatOperand + HasChain; 3780 assert(SplatOp < Op.getNumOperands()); 3781 3782 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 3783 SDValue &ScalarOp = Operands[SplatOp]; 3784 MVT OpVT = ScalarOp.getSimpleValueType(); 3785 MVT XLenVT = Subtarget.getXLenVT(); 3786 3787 // If this isn't a scalar, or its type is XLenVT we're done. 3788 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 3789 return SDValue(); 3790 3791 // Simplest case is that the operand needs to be promoted to XLenVT. 3792 if (OpVT.bitsLT(XLenVT)) { 3793 // If the operand is a constant, sign extend to increase our chances 3794 // of being able to use a .vi instruction. ANY_EXTEND would become a 3795 // a zero extend and the simm5 check in isel would fail. 3796 // FIXME: Should we ignore the upper bits in isel instead? 3797 unsigned ExtOpc = 3798 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 3799 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 3800 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3801 } 3802 3803 // Use the previous operand to get the vXi64 VT. The result might be a mask 3804 // VT for compares. Using the previous operand assumes that the previous 3805 // operand will never have a smaller element size than a scalar operand and 3806 // that a widening operation never uses SEW=64. 3807 // NOTE: If this fails the below assert, we can probably just find the 3808 // element count from any operand or result and use it to construct the VT. 3809 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 3810 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 3811 3812 // The more complex case is when the scalar is larger than XLenVT. 3813 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 3814 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 3815 3816 // If this is a sign-extended 32-bit constant, we can truncate it and rely 3817 // on the instruction to sign-extend since SEW>XLEN. 3818 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 3819 if (isInt<32>(CVal->getSExtValue())) { 3820 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3821 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3822 } 3823 } 3824 3825 // We need to convert the scalar to a splat vector. 3826 // FIXME: Can we implicitly truncate the scalar if it is known to 3827 // be sign extended? 3828 // VL should be the last operand. 3829 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 3830 assert(VL.getValueType() == XLenVT); 3831 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 3832 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 3833 } 3834 3835 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3836 SelectionDAG &DAG) const { 3837 unsigned IntNo = Op.getConstantOperandVal(0); 3838 SDLoc DL(Op); 3839 MVT XLenVT = Subtarget.getXLenVT(); 3840 3841 switch (IntNo) { 3842 default: 3843 break; // Don't custom lower most intrinsics. 3844 case Intrinsic::thread_pointer: { 3845 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3846 return DAG.getRegister(RISCV::X4, PtrVT); 3847 } 3848 case Intrinsic::riscv_orc_b: 3849 // Lower to the GORCI encoding for orc.b. 3850 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 3851 DAG.getConstant(7, DL, XLenVT)); 3852 case Intrinsic::riscv_grev: 3853 case Intrinsic::riscv_gorc: { 3854 unsigned Opc = 3855 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 3856 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3857 } 3858 case Intrinsic::riscv_shfl: 3859 case Intrinsic::riscv_unshfl: { 3860 unsigned Opc = 3861 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 3862 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3863 } 3864 case Intrinsic::riscv_bcompress: 3865 case Intrinsic::riscv_bdecompress: { 3866 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 3867 : RISCVISD::BDECOMPRESS; 3868 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 3869 } 3870 case Intrinsic::riscv_vmv_x_s: 3871 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 3872 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 3873 Op.getOperand(1)); 3874 case Intrinsic::riscv_vmv_v_x: 3875 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 3876 Op.getSimpleValueType(), DL, DAG, Subtarget); 3877 case Intrinsic::riscv_vfmv_v_f: 3878 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 3879 Op.getOperand(1), Op.getOperand(2)); 3880 case Intrinsic::riscv_vmv_s_x: { 3881 SDValue Scalar = Op.getOperand(2); 3882 3883 if (Scalar.getValueType().bitsLE(XLenVT)) { 3884 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 3885 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 3886 Op.getOperand(1), Scalar, Op.getOperand(3)); 3887 } 3888 3889 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 3890 3891 // This is an i64 value that lives in two scalar registers. We have to 3892 // insert this in a convoluted way. First we build vXi64 splat containing 3893 // the/ two values that we assemble using some bit math. Next we'll use 3894 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 3895 // to merge element 0 from our splat into the source vector. 3896 // FIXME: This is probably not the best way to do this, but it is 3897 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 3898 // point. 3899 // sw lo, (a0) 3900 // sw hi, 4(a0) 3901 // vlse vX, (a0) 3902 // 3903 // vid.v vVid 3904 // vmseq.vx mMask, vVid, 0 3905 // vmerge.vvm vDest, vSrc, vVal, mMask 3906 MVT VT = Op.getSimpleValueType(); 3907 SDValue Vec = Op.getOperand(1); 3908 SDValue VL = Op.getOperand(3); 3909 3910 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 3911 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 3912 DAG.getConstant(0, DL, MVT::i32), VL); 3913 3914 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 3915 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3916 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 3917 SDValue SelectCond = 3918 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 3919 DAG.getCondCode(ISD::SETEQ), Mask, VL); 3920 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 3921 Vec, VL); 3922 } 3923 case Intrinsic::riscv_vslide1up: 3924 case Intrinsic::riscv_vslide1down: 3925 case Intrinsic::riscv_vslide1up_mask: 3926 case Intrinsic::riscv_vslide1down_mask: { 3927 // We need to special case these when the scalar is larger than XLen. 3928 unsigned NumOps = Op.getNumOperands(); 3929 bool IsMasked = NumOps == 7; 3930 unsigned OpOffset = IsMasked ? 1 : 0; 3931 SDValue Scalar = Op.getOperand(2 + OpOffset); 3932 if (Scalar.getValueType().bitsLE(XLenVT)) 3933 break; 3934 3935 // Splatting a sign extended constant is fine. 3936 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 3937 if (isInt<32>(CVal->getSExtValue())) 3938 break; 3939 3940 MVT VT = Op.getSimpleValueType(); 3941 assert(VT.getVectorElementType() == MVT::i64 && 3942 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 3943 3944 // Convert the vector source to the equivalent nxvXi32 vector. 3945 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 3946 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 3947 3948 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3949 DAG.getConstant(0, DL, XLenVT)); 3950 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 3951 DAG.getConstant(1, DL, XLenVT)); 3952 3953 // Double the VL since we halved SEW. 3954 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 3955 SDValue I32VL = 3956 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 3957 3958 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 3959 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 3960 3961 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 3962 // instructions. 3963 if (IntNo == Intrinsic::riscv_vslide1up || 3964 IntNo == Intrinsic::riscv_vslide1up_mask) { 3965 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 3966 I32Mask, I32VL); 3967 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 3968 I32Mask, I32VL); 3969 } else { 3970 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 3971 I32Mask, I32VL); 3972 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 3973 I32Mask, I32VL); 3974 } 3975 3976 // Convert back to nxvXi64. 3977 Vec = DAG.getBitcast(VT, Vec); 3978 3979 if (!IsMasked) 3980 return Vec; 3981 3982 // Apply mask after the operation. 3983 SDValue Mask = Op.getOperand(NumOps - 3); 3984 SDValue MaskedOff = Op.getOperand(1); 3985 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 3986 } 3987 } 3988 3989 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 3990 } 3991 3992 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 3993 SelectionDAG &DAG) const { 3994 unsigned IntNo = Op.getConstantOperandVal(1); 3995 switch (IntNo) { 3996 default: 3997 break; 3998 case Intrinsic::riscv_masked_strided_load: { 3999 SDLoc DL(Op); 4000 MVT XLenVT = Subtarget.getXLenVT(); 4001 4002 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4003 // the selection of the masked intrinsics doesn't do this for us. 4004 SDValue Mask = Op.getOperand(5); 4005 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4006 4007 MVT VT = Op->getSimpleValueType(0); 4008 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4009 4010 SDValue PassThru = Op.getOperand(2); 4011 if (!IsUnmasked) { 4012 MVT MaskVT = 4013 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4014 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4015 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4016 } 4017 4018 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4019 4020 SDValue IntID = DAG.getTargetConstant( 4021 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4022 XLenVT); 4023 4024 auto *Load = cast<MemIntrinsicSDNode>(Op); 4025 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4026 if (!IsUnmasked) 4027 Ops.push_back(PassThru); 4028 Ops.push_back(Op.getOperand(3)); // Ptr 4029 Ops.push_back(Op.getOperand(4)); // Stride 4030 if (!IsUnmasked) 4031 Ops.push_back(Mask); 4032 Ops.push_back(VL); 4033 if (!IsUnmasked) { 4034 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4035 Ops.push_back(Policy); 4036 } 4037 4038 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4039 SDValue Result = 4040 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4041 Load->getMemoryVT(), Load->getMemOperand()); 4042 SDValue Chain = Result.getValue(1); 4043 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4044 return DAG.getMergeValues({Result, Chain}, DL); 4045 } 4046 } 4047 4048 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4049 } 4050 4051 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4052 SelectionDAG &DAG) const { 4053 unsigned IntNo = Op.getConstantOperandVal(1); 4054 switch (IntNo) { 4055 default: 4056 break; 4057 case Intrinsic::riscv_masked_strided_store: { 4058 SDLoc DL(Op); 4059 MVT XLenVT = Subtarget.getXLenVT(); 4060 4061 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4062 // the selection of the masked intrinsics doesn't do this for us. 4063 SDValue Mask = Op.getOperand(5); 4064 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4065 4066 SDValue Val = Op.getOperand(2); 4067 MVT VT = Val.getSimpleValueType(); 4068 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4069 4070 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4071 if (!IsUnmasked) { 4072 MVT MaskVT = 4073 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4074 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4075 } 4076 4077 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4078 4079 SDValue IntID = DAG.getTargetConstant( 4080 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4081 XLenVT); 4082 4083 auto *Store = cast<MemIntrinsicSDNode>(Op); 4084 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4085 Ops.push_back(Val); 4086 Ops.push_back(Op.getOperand(3)); // Ptr 4087 Ops.push_back(Op.getOperand(4)); // Stride 4088 if (!IsUnmasked) 4089 Ops.push_back(Mask); 4090 Ops.push_back(VL); 4091 4092 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4093 Ops, Store->getMemoryVT(), 4094 Store->getMemOperand()); 4095 } 4096 } 4097 4098 return SDValue(); 4099 } 4100 4101 static MVT getLMUL1VT(MVT VT) { 4102 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4103 "Unexpected vector MVT"); 4104 return MVT::getScalableVectorVT( 4105 VT.getVectorElementType(), 4106 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4107 } 4108 4109 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4110 switch (ISDOpcode) { 4111 default: 4112 llvm_unreachable("Unhandled reduction"); 4113 case ISD::VECREDUCE_ADD: 4114 return RISCVISD::VECREDUCE_ADD_VL; 4115 case ISD::VECREDUCE_UMAX: 4116 return RISCVISD::VECREDUCE_UMAX_VL; 4117 case ISD::VECREDUCE_SMAX: 4118 return RISCVISD::VECREDUCE_SMAX_VL; 4119 case ISD::VECREDUCE_UMIN: 4120 return RISCVISD::VECREDUCE_UMIN_VL; 4121 case ISD::VECREDUCE_SMIN: 4122 return RISCVISD::VECREDUCE_SMIN_VL; 4123 case ISD::VECREDUCE_AND: 4124 return RISCVISD::VECREDUCE_AND_VL; 4125 case ISD::VECREDUCE_OR: 4126 return RISCVISD::VECREDUCE_OR_VL; 4127 case ISD::VECREDUCE_XOR: 4128 return RISCVISD::VECREDUCE_XOR_VL; 4129 } 4130 } 4131 4132 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4133 SelectionDAG &DAG, 4134 bool IsVP) const { 4135 SDLoc DL(Op); 4136 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4137 MVT VecVT = Vec.getSimpleValueType(); 4138 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4139 Op.getOpcode() == ISD::VECREDUCE_OR || 4140 Op.getOpcode() == ISD::VECREDUCE_XOR || 4141 Op.getOpcode() == ISD::VP_REDUCE_AND || 4142 Op.getOpcode() == ISD::VP_REDUCE_OR || 4143 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4144 "Unexpected reduction lowering"); 4145 4146 MVT XLenVT = Subtarget.getXLenVT(); 4147 assert(Op.getValueType() == XLenVT && 4148 "Expected reduction output to be legalized to XLenVT"); 4149 4150 MVT ContainerVT = VecVT; 4151 if (VecVT.isFixedLengthVector()) { 4152 ContainerVT = getContainerForFixedLengthVector(VecVT); 4153 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4154 } 4155 4156 SDValue Mask, VL; 4157 if (IsVP) { 4158 Mask = Op.getOperand(2); 4159 VL = Op.getOperand(3); 4160 } else { 4161 std::tie(Mask, VL) = 4162 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4163 } 4164 4165 unsigned BaseOpc; 4166 ISD::CondCode CC; 4167 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4168 4169 switch (Op.getOpcode()) { 4170 default: 4171 llvm_unreachable("Unhandled reduction"); 4172 case ISD::VECREDUCE_AND: 4173 case ISD::VP_REDUCE_AND: { 4174 // vpopc ~x == 0 4175 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4176 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4177 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 4178 CC = ISD::SETEQ; 4179 BaseOpc = ISD::AND; 4180 break; 4181 } 4182 case ISD::VECREDUCE_OR: 4183 case ISD::VP_REDUCE_OR: 4184 // vpopc x != 0 4185 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 4186 CC = ISD::SETNE; 4187 BaseOpc = ISD::OR; 4188 break; 4189 case ISD::VECREDUCE_XOR: 4190 case ISD::VP_REDUCE_XOR: { 4191 // ((vpopc x) & 1) != 0 4192 SDValue One = DAG.getConstant(1, DL, XLenVT); 4193 Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL); 4194 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4195 CC = ISD::SETNE; 4196 BaseOpc = ISD::XOR; 4197 break; 4198 } 4199 } 4200 4201 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4202 4203 if (!IsVP) 4204 return SetCC; 4205 4206 // Now include the start value in the operation. 4207 // Note that we must return the start value when no elements are operated 4208 // upon. The vpopc instructions we've emitted in each case above will return 4209 // 0 for an inactive vector, and so we've already received the neutral value: 4210 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4211 // can simply include the start value. 4212 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4213 } 4214 4215 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4216 SelectionDAG &DAG) const { 4217 SDLoc DL(Op); 4218 SDValue Vec = Op.getOperand(0); 4219 EVT VecEVT = Vec.getValueType(); 4220 4221 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4222 4223 // Due to ordering in legalize types we may have a vector type that needs to 4224 // be split. Do that manually so we can get down to a legal type. 4225 while (getTypeAction(*DAG.getContext(), VecEVT) == 4226 TargetLowering::TypeSplitVector) { 4227 SDValue Lo, Hi; 4228 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4229 VecEVT = Lo.getValueType(); 4230 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4231 } 4232 4233 // TODO: The type may need to be widened rather than split. Or widened before 4234 // it can be split. 4235 if (!isTypeLegal(VecEVT)) 4236 return SDValue(); 4237 4238 MVT VecVT = VecEVT.getSimpleVT(); 4239 MVT VecEltVT = VecVT.getVectorElementType(); 4240 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4241 4242 MVT ContainerVT = VecVT; 4243 if (VecVT.isFixedLengthVector()) { 4244 ContainerVT = getContainerForFixedLengthVector(VecVT); 4245 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4246 } 4247 4248 MVT M1VT = getLMUL1VT(ContainerVT); 4249 4250 SDValue Mask, VL; 4251 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4252 4253 // FIXME: This is a VLMAX splat which might be too large and can prevent 4254 // vsetvli removal. 4255 SDValue NeutralElem = 4256 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4257 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 4258 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4259 IdentitySplat, Mask, VL); 4260 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4261 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4262 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4263 } 4264 4265 // Given a reduction op, this function returns the matching reduction opcode, 4266 // the vector SDValue and the scalar SDValue required to lower this to a 4267 // RISCVISD node. 4268 static std::tuple<unsigned, SDValue, SDValue> 4269 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4270 SDLoc DL(Op); 4271 auto Flags = Op->getFlags(); 4272 unsigned Opcode = Op.getOpcode(); 4273 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4274 switch (Opcode) { 4275 default: 4276 llvm_unreachable("Unhandled reduction"); 4277 case ISD::VECREDUCE_FADD: 4278 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 4279 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4280 case ISD::VECREDUCE_SEQ_FADD: 4281 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4282 Op.getOperand(0)); 4283 case ISD::VECREDUCE_FMIN: 4284 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4285 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4286 case ISD::VECREDUCE_FMAX: 4287 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4288 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4289 } 4290 } 4291 4292 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4293 SelectionDAG &DAG) const { 4294 SDLoc DL(Op); 4295 MVT VecEltVT = Op.getSimpleValueType(); 4296 4297 unsigned RVVOpcode; 4298 SDValue VectorVal, ScalarVal; 4299 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4300 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4301 MVT VecVT = VectorVal.getSimpleValueType(); 4302 4303 MVT ContainerVT = VecVT; 4304 if (VecVT.isFixedLengthVector()) { 4305 ContainerVT = getContainerForFixedLengthVector(VecVT); 4306 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4307 } 4308 4309 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4310 4311 SDValue Mask, VL; 4312 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4313 4314 // FIXME: This is a VLMAX splat which might be too large and can prevent 4315 // vsetvli removal. 4316 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 4317 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4318 VectorVal, ScalarSplat, Mask, VL); 4319 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4320 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4321 } 4322 4323 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4324 switch (ISDOpcode) { 4325 default: 4326 llvm_unreachable("Unhandled reduction"); 4327 case ISD::VP_REDUCE_ADD: 4328 return RISCVISD::VECREDUCE_ADD_VL; 4329 case ISD::VP_REDUCE_UMAX: 4330 return RISCVISD::VECREDUCE_UMAX_VL; 4331 case ISD::VP_REDUCE_SMAX: 4332 return RISCVISD::VECREDUCE_SMAX_VL; 4333 case ISD::VP_REDUCE_UMIN: 4334 return RISCVISD::VECREDUCE_UMIN_VL; 4335 case ISD::VP_REDUCE_SMIN: 4336 return RISCVISD::VECREDUCE_SMIN_VL; 4337 case ISD::VP_REDUCE_AND: 4338 return RISCVISD::VECREDUCE_AND_VL; 4339 case ISD::VP_REDUCE_OR: 4340 return RISCVISD::VECREDUCE_OR_VL; 4341 case ISD::VP_REDUCE_XOR: 4342 return RISCVISD::VECREDUCE_XOR_VL; 4343 case ISD::VP_REDUCE_FADD: 4344 return RISCVISD::VECREDUCE_FADD_VL; 4345 case ISD::VP_REDUCE_SEQ_FADD: 4346 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4347 case ISD::VP_REDUCE_FMAX: 4348 return RISCVISD::VECREDUCE_FMAX_VL; 4349 case ISD::VP_REDUCE_FMIN: 4350 return RISCVISD::VECREDUCE_FMIN_VL; 4351 } 4352 } 4353 4354 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4355 SelectionDAG &DAG) const { 4356 SDLoc DL(Op); 4357 SDValue Vec = Op.getOperand(1); 4358 EVT VecEVT = Vec.getValueType(); 4359 4360 // TODO: The type may need to be widened rather than split. Or widened before 4361 // it can be split. 4362 if (!isTypeLegal(VecEVT)) 4363 return SDValue(); 4364 4365 MVT VecVT = VecEVT.getSimpleVT(); 4366 MVT VecEltVT = VecVT.getVectorElementType(); 4367 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4368 4369 MVT ContainerVT = VecVT; 4370 if (VecVT.isFixedLengthVector()) { 4371 ContainerVT = getContainerForFixedLengthVector(VecVT); 4372 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4373 } 4374 4375 SDValue VL = Op.getOperand(3); 4376 SDValue Mask = Op.getOperand(2); 4377 4378 MVT M1VT = getLMUL1VT(ContainerVT); 4379 MVT XLenVT = Subtarget.getXLenVT(); 4380 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4381 4382 // FIXME: This is a VLMAX splat which might be too large and can prevent 4383 // vsetvli removal. 4384 SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0)); 4385 SDValue Reduction = 4386 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4387 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4388 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 4389 if (!VecVT.isInteger()) 4390 return Elt0; 4391 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4392 } 4393 4394 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4395 SelectionDAG &DAG) const { 4396 SDValue Vec = Op.getOperand(0); 4397 SDValue SubVec = Op.getOperand(1); 4398 MVT VecVT = Vec.getSimpleValueType(); 4399 MVT SubVecVT = SubVec.getSimpleValueType(); 4400 4401 SDLoc DL(Op); 4402 MVT XLenVT = Subtarget.getXLenVT(); 4403 unsigned OrigIdx = Op.getConstantOperandVal(2); 4404 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4405 4406 // We don't have the ability to slide mask vectors up indexed by their i1 4407 // elements; the smallest we can do is i8. Often we are able to bitcast to 4408 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4409 // into a scalable one, we might not necessarily have enough scalable 4410 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4411 if (SubVecVT.getVectorElementType() == MVT::i1 && 4412 (OrigIdx != 0 || !Vec.isUndef())) { 4413 if (VecVT.getVectorMinNumElements() >= 8 && 4414 SubVecVT.getVectorMinNumElements() >= 8) { 4415 assert(OrigIdx % 8 == 0 && "Invalid index"); 4416 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4417 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4418 "Unexpected mask vector lowering"); 4419 OrigIdx /= 8; 4420 SubVecVT = 4421 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4422 SubVecVT.isScalableVector()); 4423 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4424 VecVT.isScalableVector()); 4425 Vec = DAG.getBitcast(VecVT, Vec); 4426 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4427 } else { 4428 // We can't slide this mask vector up indexed by its i1 elements. 4429 // This poses a problem when we wish to insert a scalable vector which 4430 // can't be re-expressed as a larger type. Just choose the slow path and 4431 // extend to a larger type, then truncate back down. 4432 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4433 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4434 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4435 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4436 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4437 Op.getOperand(2)); 4438 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4439 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4440 } 4441 } 4442 4443 // If the subvector vector is a fixed-length type, we cannot use subregister 4444 // manipulation to simplify the codegen; we don't know which register of a 4445 // LMUL group contains the specific subvector as we only know the minimum 4446 // register size. Therefore we must slide the vector group up the full 4447 // amount. 4448 if (SubVecVT.isFixedLengthVector()) { 4449 if (OrigIdx == 0 && Vec.isUndef()) 4450 return Op; 4451 MVT ContainerVT = VecVT; 4452 if (VecVT.isFixedLengthVector()) { 4453 ContainerVT = getContainerForFixedLengthVector(VecVT); 4454 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4455 } 4456 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4457 DAG.getUNDEF(ContainerVT), SubVec, 4458 DAG.getConstant(0, DL, XLenVT)); 4459 SDValue Mask = 4460 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4461 // Set the vector length to only the number of elements we care about. Note 4462 // that for slideup this includes the offset. 4463 SDValue VL = 4464 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4465 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4466 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4467 SubVec, SlideupAmt, Mask, VL); 4468 if (VecVT.isFixedLengthVector()) 4469 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4470 return DAG.getBitcast(Op.getValueType(), Slideup); 4471 } 4472 4473 unsigned SubRegIdx, RemIdx; 4474 std::tie(SubRegIdx, RemIdx) = 4475 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4476 VecVT, SubVecVT, OrigIdx, TRI); 4477 4478 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4479 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4480 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4481 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4482 4483 // 1. If the Idx has been completely eliminated and this subvector's size is 4484 // a vector register or a multiple thereof, or the surrounding elements are 4485 // undef, then this is a subvector insert which naturally aligns to a vector 4486 // register. These can easily be handled using subregister manipulation. 4487 // 2. If the subvector is smaller than a vector register, then the insertion 4488 // must preserve the undisturbed elements of the register. We do this by 4489 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4490 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4491 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4492 // LMUL=1 type back into the larger vector (resolving to another subregister 4493 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4494 // to avoid allocating a large register group to hold our subvector. 4495 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4496 return Op; 4497 4498 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4499 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4500 // (in our case undisturbed). This means we can set up a subvector insertion 4501 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4502 // size of the subvector. 4503 MVT InterSubVT = VecVT; 4504 SDValue AlignedExtract = Vec; 4505 unsigned AlignedIdx = OrigIdx - RemIdx; 4506 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4507 InterSubVT = getLMUL1VT(VecVT); 4508 // Extract a subvector equal to the nearest full vector register type. This 4509 // should resolve to a EXTRACT_SUBREG instruction. 4510 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4511 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4512 } 4513 4514 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4515 // For scalable vectors this must be further multiplied by vscale. 4516 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4517 4518 SDValue Mask, VL; 4519 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4520 4521 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4522 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4523 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4524 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4525 4526 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4527 DAG.getUNDEF(InterSubVT), SubVec, 4528 DAG.getConstant(0, DL, XLenVT)); 4529 4530 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4531 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4532 4533 // If required, insert this subvector back into the correct vector register. 4534 // This should resolve to an INSERT_SUBREG instruction. 4535 if (VecVT.bitsGT(InterSubVT)) 4536 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4537 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4538 4539 // We might have bitcast from a mask type: cast back to the original type if 4540 // required. 4541 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4542 } 4543 4544 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4545 SelectionDAG &DAG) const { 4546 SDValue Vec = Op.getOperand(0); 4547 MVT SubVecVT = Op.getSimpleValueType(); 4548 MVT VecVT = Vec.getSimpleValueType(); 4549 4550 SDLoc DL(Op); 4551 MVT XLenVT = Subtarget.getXLenVT(); 4552 unsigned OrigIdx = Op.getConstantOperandVal(1); 4553 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4554 4555 // We don't have the ability to slide mask vectors down indexed by their i1 4556 // elements; the smallest we can do is i8. Often we are able to bitcast to 4557 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4558 // from a scalable one, we might not necessarily have enough scalable 4559 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4560 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4561 if (VecVT.getVectorMinNumElements() >= 8 && 4562 SubVecVT.getVectorMinNumElements() >= 8) { 4563 assert(OrigIdx % 8 == 0 && "Invalid index"); 4564 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4565 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4566 "Unexpected mask vector lowering"); 4567 OrigIdx /= 8; 4568 SubVecVT = 4569 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4570 SubVecVT.isScalableVector()); 4571 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4572 VecVT.isScalableVector()); 4573 Vec = DAG.getBitcast(VecVT, Vec); 4574 } else { 4575 // We can't slide this mask vector down, indexed by its i1 elements. 4576 // This poses a problem when we wish to extract a scalable vector which 4577 // can't be re-expressed as a larger type. Just choose the slow path and 4578 // extend to a larger type, then truncate back down. 4579 // TODO: We could probably improve this when extracting certain fixed 4580 // from fixed, where we can extract as i8 and shift the correct element 4581 // right to reach the desired subvector? 4582 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4583 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4584 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4585 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4586 Op.getOperand(1)); 4587 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4588 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4589 } 4590 } 4591 4592 // If the subvector vector is a fixed-length type, we cannot use subregister 4593 // manipulation to simplify the codegen; we don't know which register of a 4594 // LMUL group contains the specific subvector as we only know the minimum 4595 // register size. Therefore we must slide the vector group down the full 4596 // amount. 4597 if (SubVecVT.isFixedLengthVector()) { 4598 // With an index of 0 this is a cast-like subvector, which can be performed 4599 // with subregister operations. 4600 if (OrigIdx == 0) 4601 return Op; 4602 MVT ContainerVT = VecVT; 4603 if (VecVT.isFixedLengthVector()) { 4604 ContainerVT = getContainerForFixedLengthVector(VecVT); 4605 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4606 } 4607 SDValue Mask = 4608 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4609 // Set the vector length to only the number of elements we care about. This 4610 // avoids sliding down elements we're going to discard straight away. 4611 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4612 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4613 SDValue Slidedown = 4614 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4615 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4616 // Now we can use a cast-like subvector extract to get the result. 4617 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4618 DAG.getConstant(0, DL, XLenVT)); 4619 return DAG.getBitcast(Op.getValueType(), Slidedown); 4620 } 4621 4622 unsigned SubRegIdx, RemIdx; 4623 std::tie(SubRegIdx, RemIdx) = 4624 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4625 VecVT, SubVecVT, OrigIdx, TRI); 4626 4627 // If the Idx has been completely eliminated then this is a subvector extract 4628 // which naturally aligns to a vector register. These can easily be handled 4629 // using subregister manipulation. 4630 if (RemIdx == 0) 4631 return Op; 4632 4633 // Else we must shift our vector register directly to extract the subvector. 4634 // Do this using VSLIDEDOWN. 4635 4636 // If the vector type is an LMUL-group type, extract a subvector equal to the 4637 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4638 // instruction. 4639 MVT InterSubVT = VecVT; 4640 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4641 InterSubVT = getLMUL1VT(VecVT); 4642 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4643 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4644 } 4645 4646 // Slide this vector register down by the desired number of elements in order 4647 // to place the desired subvector starting at element 0. 4648 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4649 // For scalable vectors this must be further multiplied by vscale. 4650 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4651 4652 SDValue Mask, VL; 4653 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4654 SDValue Slidedown = 4655 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4656 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4657 4658 // Now the vector is in the right position, extract our final subvector. This 4659 // should resolve to a COPY. 4660 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4661 DAG.getConstant(0, DL, XLenVT)); 4662 4663 // We might have bitcast from a mask type: cast back to the original type if 4664 // required. 4665 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4666 } 4667 4668 // Lower step_vector to the vid instruction. Any non-identity step value must 4669 // be accounted for my manual expansion. 4670 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4671 SelectionDAG &DAG) const { 4672 SDLoc DL(Op); 4673 MVT VT = Op.getSimpleValueType(); 4674 MVT XLenVT = Subtarget.getXLenVT(); 4675 SDValue Mask, VL; 4676 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4677 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4678 uint64_t StepValImm = Op.getConstantOperandVal(0); 4679 if (StepValImm != 1) { 4680 if (isPowerOf2_64(StepValImm)) { 4681 SDValue StepVal = 4682 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4683 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4684 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4685 } else { 4686 SDValue StepVal = lowerScalarSplat( 4687 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4688 DL, DAG, Subtarget); 4689 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4690 } 4691 } 4692 return StepVec; 4693 } 4694 4695 // Implement vector_reverse using vrgather.vv with indices determined by 4696 // subtracting the id of each element from (VLMAX-1). This will convert 4697 // the indices like so: 4698 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4699 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4700 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4701 SelectionDAG &DAG) const { 4702 SDLoc DL(Op); 4703 MVT VecVT = Op.getSimpleValueType(); 4704 unsigned EltSize = VecVT.getScalarSizeInBits(); 4705 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4706 4707 unsigned MaxVLMAX = 0; 4708 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4709 if (VectorBitsMax != 0) 4710 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4711 4712 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4713 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4714 4715 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4716 // to use vrgatherei16.vv. 4717 // TODO: It's also possible to use vrgatherei16.vv for other types to 4718 // decrease register width for the index calculation. 4719 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4720 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4721 // Reverse each half, then reassemble them in reverse order. 4722 // NOTE: It's also possible that after splitting that VLMAX no longer 4723 // requires vrgatherei16.vv. 4724 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4725 SDValue Lo, Hi; 4726 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4727 EVT LoVT, HiVT; 4728 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 4729 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 4730 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 4731 // Reassemble the low and high pieces reversed. 4732 // FIXME: This is a CONCAT_VECTORS. 4733 SDValue Res = 4734 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 4735 DAG.getIntPtrConstant(0, DL)); 4736 return DAG.getNode( 4737 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 4738 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 4739 } 4740 4741 // Just promote the int type to i16 which will double the LMUL. 4742 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 4743 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 4744 } 4745 4746 MVT XLenVT = Subtarget.getXLenVT(); 4747 SDValue Mask, VL; 4748 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4749 4750 // Calculate VLMAX-1 for the desired SEW. 4751 unsigned MinElts = VecVT.getVectorMinNumElements(); 4752 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 4753 DAG.getConstant(MinElts, DL, XLenVT)); 4754 SDValue VLMinus1 = 4755 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 4756 4757 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 4758 bool IsRV32E64 = 4759 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 4760 SDValue SplatVL; 4761 if (!IsRV32E64) 4762 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 4763 else 4764 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 4765 4766 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 4767 SDValue Indices = 4768 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 4769 4770 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 4771 } 4772 4773 SDValue 4774 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 4775 SelectionDAG &DAG) const { 4776 SDLoc DL(Op); 4777 auto *Load = cast<LoadSDNode>(Op); 4778 4779 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4780 Load->getMemoryVT(), 4781 *Load->getMemOperand()) && 4782 "Expecting a correctly-aligned load"); 4783 4784 MVT VT = Op.getSimpleValueType(); 4785 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4786 4787 SDValue VL = 4788 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4789 4790 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4791 SDValue NewLoad = DAG.getMemIntrinsicNode( 4792 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 4793 Load->getMemoryVT(), Load->getMemOperand()); 4794 4795 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 4796 return DAG.getMergeValues({Result, Load->getChain()}, DL); 4797 } 4798 4799 SDValue 4800 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 4801 SelectionDAG &DAG) const { 4802 SDLoc DL(Op); 4803 auto *Store = cast<StoreSDNode>(Op); 4804 4805 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 4806 Store->getMemoryVT(), 4807 *Store->getMemOperand()) && 4808 "Expecting a correctly-aligned store"); 4809 4810 SDValue StoreVal = Store->getValue(); 4811 MVT VT = StoreVal.getSimpleValueType(); 4812 4813 // If the size less than a byte, we need to pad with zeros to make a byte. 4814 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 4815 VT = MVT::v8i1; 4816 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 4817 DAG.getConstant(0, DL, VT), StoreVal, 4818 DAG.getIntPtrConstant(0, DL)); 4819 } 4820 4821 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4822 4823 SDValue VL = 4824 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4825 4826 SDValue NewValue = 4827 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 4828 return DAG.getMemIntrinsicNode( 4829 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 4830 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 4831 Store->getMemoryVT(), Store->getMemOperand()); 4832 } 4833 4834 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 4835 SelectionDAG &DAG) const { 4836 SDLoc DL(Op); 4837 MVT VT = Op.getSimpleValueType(); 4838 4839 const auto *MemSD = cast<MemSDNode>(Op); 4840 EVT MemVT = MemSD->getMemoryVT(); 4841 MachineMemOperand *MMO = MemSD->getMemOperand(); 4842 SDValue Chain = MemSD->getChain(); 4843 SDValue BasePtr = MemSD->getBasePtr(); 4844 4845 SDValue Mask, PassThru, VL; 4846 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 4847 Mask = VPLoad->getMask(); 4848 PassThru = DAG.getUNDEF(VT); 4849 VL = VPLoad->getVectorLength(); 4850 } else { 4851 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 4852 Mask = MLoad->getMask(); 4853 PassThru = MLoad->getPassThru(); 4854 } 4855 4856 MVT XLenVT = Subtarget.getXLenVT(); 4857 4858 MVT ContainerVT = VT; 4859 if (VT.isFixedLengthVector()) { 4860 ContainerVT = getContainerForFixedLengthVector(VT); 4861 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4862 4863 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4864 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4865 } 4866 4867 if (!VL) 4868 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4869 4870 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4871 SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT); 4872 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4873 SDValue Ops[] = {Chain, IntID, PassThru, BasePtr, Mask, VL, Policy}; 4874 SDValue Result = 4875 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 4876 Chain = Result.getValue(1); 4877 4878 if (VT.isFixedLengthVector()) 4879 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4880 4881 return DAG.getMergeValues({Result, Chain}, DL); 4882 } 4883 4884 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 4885 SelectionDAG &DAG) const { 4886 SDLoc DL(Op); 4887 4888 const auto *MemSD = cast<MemSDNode>(Op); 4889 EVT MemVT = MemSD->getMemoryVT(); 4890 MachineMemOperand *MMO = MemSD->getMemOperand(); 4891 SDValue Chain = MemSD->getChain(); 4892 SDValue BasePtr = MemSD->getBasePtr(); 4893 SDValue Val, Mask, VL; 4894 4895 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 4896 Val = VPStore->getValue(); 4897 Mask = VPStore->getMask(); 4898 VL = VPStore->getVectorLength(); 4899 } else { 4900 const auto *MStore = cast<MaskedStoreSDNode>(Op); 4901 Val = MStore->getValue(); 4902 Mask = MStore->getMask(); 4903 } 4904 4905 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4906 4907 MVT VT = Val.getSimpleValueType(); 4908 MVT XLenVT = Subtarget.getXLenVT(); 4909 4910 MVT ContainerVT = VT; 4911 if (VT.isFixedLengthVector()) { 4912 ContainerVT = getContainerForFixedLengthVector(VT); 4913 4914 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4915 if (!IsUnmasked) { 4916 MVT MaskVT = 4917 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4918 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4919 } 4920 } 4921 4922 if (!VL) 4923 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 4924 4925 unsigned IntID = 4926 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 4927 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 4928 Ops.push_back(Val); 4929 Ops.push_back(BasePtr); 4930 if (!IsUnmasked) 4931 Ops.push_back(Mask); 4932 Ops.push_back(VL); 4933 4934 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 4935 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 4936 } 4937 4938 SDValue 4939 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 4940 SelectionDAG &DAG) const { 4941 MVT InVT = Op.getOperand(0).getSimpleValueType(); 4942 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 4943 4944 MVT VT = Op.getSimpleValueType(); 4945 4946 SDValue Op1 = 4947 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4948 SDValue Op2 = 4949 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 4950 4951 SDLoc DL(Op); 4952 SDValue VL = 4953 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 4954 4955 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4956 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4957 4958 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 4959 Op.getOperand(2), Mask, VL); 4960 4961 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 4962 } 4963 4964 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 4965 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 4966 MVT VT = Op.getSimpleValueType(); 4967 4968 if (VT.getVectorElementType() == MVT::i1) 4969 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 4970 4971 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 4972 } 4973 4974 SDValue 4975 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 4976 SelectionDAG &DAG) const { 4977 unsigned Opc; 4978 switch (Op.getOpcode()) { 4979 default: llvm_unreachable("Unexpected opcode!"); 4980 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 4981 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 4982 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 4983 } 4984 4985 return lowerToScalableOp(Op, DAG, Opc); 4986 } 4987 4988 // Lower vector ABS to smax(X, sub(0, X)). 4989 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 4990 SDLoc DL(Op); 4991 MVT VT = Op.getSimpleValueType(); 4992 SDValue X = Op.getOperand(0); 4993 4994 assert(VT.isFixedLengthVector() && "Unexpected type"); 4995 4996 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4997 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 4998 4999 SDValue Mask, VL; 5000 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5001 5002 SDValue SplatZero = 5003 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5004 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5005 SDValue NegX = 5006 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5007 SDValue Max = 5008 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5009 5010 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5011 } 5012 5013 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5014 SDValue Op, SelectionDAG &DAG) const { 5015 SDLoc DL(Op); 5016 MVT VT = Op.getSimpleValueType(); 5017 SDValue Mag = Op.getOperand(0); 5018 SDValue Sign = Op.getOperand(1); 5019 assert(Mag.getValueType() == Sign.getValueType() && 5020 "Can only handle COPYSIGN with matching types."); 5021 5022 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5023 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5024 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5025 5026 SDValue Mask, VL; 5027 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5028 5029 SDValue CopySign = 5030 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5031 5032 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5033 } 5034 5035 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5036 SDValue Op, SelectionDAG &DAG) const { 5037 MVT VT = Op.getSimpleValueType(); 5038 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5039 5040 MVT I1ContainerVT = 5041 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5042 5043 SDValue CC = 5044 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5045 SDValue Op1 = 5046 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5047 SDValue Op2 = 5048 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5049 5050 SDLoc DL(Op); 5051 SDValue Mask, VL; 5052 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5053 5054 SDValue Select = 5055 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5056 5057 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5058 } 5059 5060 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5061 unsigned NewOpc, 5062 bool HasMask) const { 5063 MVT VT = Op.getSimpleValueType(); 5064 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5065 5066 // Create list of operands by converting existing ones to scalable types. 5067 SmallVector<SDValue, 6> Ops; 5068 for (const SDValue &V : Op->op_values()) { 5069 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5070 5071 // Pass through non-vector operands. 5072 if (!V.getValueType().isVector()) { 5073 Ops.push_back(V); 5074 continue; 5075 } 5076 5077 // "cast" fixed length vector to a scalable vector. 5078 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5079 "Only fixed length vectors are supported!"); 5080 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5081 } 5082 5083 SDLoc DL(Op); 5084 SDValue Mask, VL; 5085 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5086 if (HasMask) 5087 Ops.push_back(Mask); 5088 Ops.push_back(VL); 5089 5090 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5091 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5092 } 5093 5094 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5095 // * Operands of each node are assumed to be in the same order. 5096 // * The EVL operand is promoted from i32 to i64 on RV64. 5097 // * Fixed-length vectors are converted to their scalable-vector container 5098 // types. 5099 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5100 unsigned RISCVISDOpc) const { 5101 SDLoc DL(Op); 5102 MVT VT = Op.getSimpleValueType(); 5103 SmallVector<SDValue, 4> Ops; 5104 5105 for (const auto &OpIdx : enumerate(Op->ops())) { 5106 SDValue V = OpIdx.value(); 5107 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5108 // Pass through operands which aren't fixed-length vectors. 5109 if (!V.getValueType().isFixedLengthVector()) { 5110 Ops.push_back(V); 5111 continue; 5112 } 5113 // "cast" fixed length vector to a scalable vector. 5114 MVT OpVT = V.getSimpleValueType(); 5115 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5116 assert(useRVVForFixedLengthVectorVT(OpVT) && 5117 "Only fixed length vectors are supported!"); 5118 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5119 } 5120 5121 if (!VT.isFixedLengthVector()) 5122 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5123 5124 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5125 5126 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5127 5128 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5129 } 5130 5131 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5132 // matched to a RVV indexed load. The RVV indexed load instructions only 5133 // support the "unsigned unscaled" addressing mode; indices are implicitly 5134 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5135 // signed or scaled indexing is extended to the XLEN value type and scaled 5136 // accordingly. 5137 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5138 SelectionDAG &DAG) const { 5139 SDLoc DL(Op); 5140 MVT VT = Op.getSimpleValueType(); 5141 5142 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5143 EVT MemVT = MemSD->getMemoryVT(); 5144 MachineMemOperand *MMO = MemSD->getMemOperand(); 5145 SDValue Chain = MemSD->getChain(); 5146 SDValue BasePtr = MemSD->getBasePtr(); 5147 5148 ISD::LoadExtType LoadExtType; 5149 SDValue Index, Mask, PassThru, VL; 5150 5151 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5152 Index = VPGN->getIndex(); 5153 Mask = VPGN->getMask(); 5154 PassThru = DAG.getUNDEF(VT); 5155 VL = VPGN->getVectorLength(); 5156 // VP doesn't support extending loads. 5157 LoadExtType = ISD::NON_EXTLOAD; 5158 } else { 5159 // Else it must be a MGATHER. 5160 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5161 Index = MGN->getIndex(); 5162 Mask = MGN->getMask(); 5163 PassThru = MGN->getPassThru(); 5164 LoadExtType = MGN->getExtensionType(); 5165 } 5166 5167 MVT IndexVT = Index.getSimpleValueType(); 5168 MVT XLenVT = Subtarget.getXLenVT(); 5169 5170 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5171 "Unexpected VTs!"); 5172 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5173 // Targets have to explicitly opt-in for extending vector loads. 5174 assert(LoadExtType == ISD::NON_EXTLOAD && 5175 "Unexpected extending MGATHER/VP_GATHER"); 5176 (void)LoadExtType; 5177 5178 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5179 // the selection of the masked intrinsics doesn't do this for us. 5180 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5181 5182 MVT ContainerVT = VT; 5183 if (VT.isFixedLengthVector()) { 5184 // We need to use the larger of the result and index type to determine the 5185 // scalable type to use so we don't increase LMUL for any operand/result. 5186 if (VT.bitsGE(IndexVT)) { 5187 ContainerVT = getContainerForFixedLengthVector(VT); 5188 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5189 ContainerVT.getVectorElementCount()); 5190 } else { 5191 IndexVT = getContainerForFixedLengthVector(IndexVT); 5192 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5193 IndexVT.getVectorElementCount()); 5194 } 5195 5196 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5197 5198 if (!IsUnmasked) { 5199 MVT MaskVT = 5200 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5201 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5202 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5203 } 5204 } 5205 5206 if (!VL) 5207 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5208 5209 unsigned IntID = 5210 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5211 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5212 if (!IsUnmasked) 5213 Ops.push_back(PassThru); 5214 Ops.push_back(BasePtr); 5215 Ops.push_back(Index); 5216 if (!IsUnmasked) 5217 Ops.push_back(Mask); 5218 Ops.push_back(VL); 5219 if (!IsUnmasked) 5220 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5221 5222 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5223 SDValue Result = 5224 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5225 Chain = Result.getValue(1); 5226 5227 if (VT.isFixedLengthVector()) 5228 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5229 5230 return DAG.getMergeValues({Result, Chain}, DL); 5231 } 5232 5233 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5234 // matched to a RVV indexed store. The RVV indexed store instructions only 5235 // support the "unsigned unscaled" addressing mode; indices are implicitly 5236 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5237 // signed or scaled indexing is extended to the XLEN value type and scaled 5238 // accordingly. 5239 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5240 SelectionDAG &DAG) const { 5241 SDLoc DL(Op); 5242 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5243 EVT MemVT = MemSD->getMemoryVT(); 5244 MachineMemOperand *MMO = MemSD->getMemOperand(); 5245 SDValue Chain = MemSD->getChain(); 5246 SDValue BasePtr = MemSD->getBasePtr(); 5247 5248 bool IsTruncatingStore = false; 5249 SDValue Index, Mask, Val, VL; 5250 5251 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5252 Index = VPSN->getIndex(); 5253 Mask = VPSN->getMask(); 5254 Val = VPSN->getValue(); 5255 VL = VPSN->getVectorLength(); 5256 // VP doesn't support truncating stores. 5257 IsTruncatingStore = false; 5258 } else { 5259 // Else it must be a MSCATTER. 5260 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5261 Index = MSN->getIndex(); 5262 Mask = MSN->getMask(); 5263 Val = MSN->getValue(); 5264 IsTruncatingStore = MSN->isTruncatingStore(); 5265 } 5266 5267 MVT VT = Val.getSimpleValueType(); 5268 MVT IndexVT = Index.getSimpleValueType(); 5269 MVT XLenVT = Subtarget.getXLenVT(); 5270 5271 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5272 "Unexpected VTs!"); 5273 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5274 // Targets have to explicitly opt-in for extending vector loads and 5275 // truncating vector stores. 5276 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5277 (void)IsTruncatingStore; 5278 5279 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5280 // the selection of the masked intrinsics doesn't do this for us. 5281 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5282 5283 MVT ContainerVT = VT; 5284 if (VT.isFixedLengthVector()) { 5285 // We need to use the larger of the value and index type to determine the 5286 // scalable type to use so we don't increase LMUL for any operand/result. 5287 if (VT.bitsGE(IndexVT)) { 5288 ContainerVT = getContainerForFixedLengthVector(VT); 5289 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5290 ContainerVT.getVectorElementCount()); 5291 } else { 5292 IndexVT = getContainerForFixedLengthVector(IndexVT); 5293 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5294 IndexVT.getVectorElementCount()); 5295 } 5296 5297 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5298 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5299 5300 if (!IsUnmasked) { 5301 MVT MaskVT = 5302 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5303 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5304 } 5305 } 5306 5307 if (!VL) 5308 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5309 5310 unsigned IntID = 5311 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5312 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5313 Ops.push_back(Val); 5314 Ops.push_back(BasePtr); 5315 Ops.push_back(Index); 5316 if (!IsUnmasked) 5317 Ops.push_back(Mask); 5318 Ops.push_back(VL); 5319 5320 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5321 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5322 } 5323 5324 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5325 SelectionDAG &DAG) const { 5326 const MVT XLenVT = Subtarget.getXLenVT(); 5327 SDLoc DL(Op); 5328 SDValue Chain = Op->getOperand(0); 5329 SDValue SysRegNo = DAG.getConstant( 5330 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5331 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5332 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5333 5334 // Encoding used for rounding mode in RISCV differs from that used in 5335 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5336 // table, which consists of a sequence of 4-bit fields, each representing 5337 // corresponding FLT_ROUNDS mode. 5338 static const int Table = 5339 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5340 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5341 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5342 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5343 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5344 5345 SDValue Shift = 5346 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5347 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5348 DAG.getConstant(Table, DL, XLenVT), Shift); 5349 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5350 DAG.getConstant(7, DL, XLenVT)); 5351 5352 return DAG.getMergeValues({Masked, Chain}, DL); 5353 } 5354 5355 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5356 SelectionDAG &DAG) const { 5357 const MVT XLenVT = Subtarget.getXLenVT(); 5358 SDLoc DL(Op); 5359 SDValue Chain = Op->getOperand(0); 5360 SDValue RMValue = Op->getOperand(1); 5361 SDValue SysRegNo = DAG.getConstant( 5362 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5363 5364 // Encoding used for rounding mode in RISCV differs from that used in 5365 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5366 // a table, which consists of a sequence of 4-bit fields, each representing 5367 // corresponding RISCV mode. 5368 static const unsigned Table = 5369 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5370 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5371 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5372 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5373 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5374 5375 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5376 DAG.getConstant(2, DL, XLenVT)); 5377 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5378 DAG.getConstant(Table, DL, XLenVT), Shift); 5379 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5380 DAG.getConstant(0x7, DL, XLenVT)); 5381 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5382 RMValue); 5383 } 5384 5385 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5386 // form of the given Opcode. 5387 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5388 switch (Opcode) { 5389 default: 5390 llvm_unreachable("Unexpected opcode"); 5391 case ISD::SHL: 5392 return RISCVISD::SLLW; 5393 case ISD::SRA: 5394 return RISCVISD::SRAW; 5395 case ISD::SRL: 5396 return RISCVISD::SRLW; 5397 case ISD::SDIV: 5398 return RISCVISD::DIVW; 5399 case ISD::UDIV: 5400 return RISCVISD::DIVUW; 5401 case ISD::UREM: 5402 return RISCVISD::REMUW; 5403 case ISD::ROTL: 5404 return RISCVISD::ROLW; 5405 case ISD::ROTR: 5406 return RISCVISD::RORW; 5407 case RISCVISD::GREV: 5408 return RISCVISD::GREVW; 5409 case RISCVISD::GORC: 5410 return RISCVISD::GORCW; 5411 } 5412 } 5413 5414 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5415 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5416 // otherwise be promoted to i64, making it difficult to select the 5417 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5418 // type i8/i16/i32 is lost. 5419 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5420 unsigned ExtOpc = ISD::ANY_EXTEND) { 5421 SDLoc DL(N); 5422 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5423 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5424 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5425 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5426 // ReplaceNodeResults requires we maintain the same type for the return value. 5427 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5428 } 5429 5430 // Converts the given 32-bit operation to a i64 operation with signed extension 5431 // semantic to reduce the signed extension instructions. 5432 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5433 SDLoc DL(N); 5434 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5435 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5436 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5437 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5438 DAG.getValueType(MVT::i32)); 5439 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5440 } 5441 5442 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5443 SmallVectorImpl<SDValue> &Results, 5444 SelectionDAG &DAG) const { 5445 SDLoc DL(N); 5446 switch (N->getOpcode()) { 5447 default: 5448 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5449 case ISD::STRICT_FP_TO_SINT: 5450 case ISD::STRICT_FP_TO_UINT: 5451 case ISD::FP_TO_SINT: 5452 case ISD::FP_TO_UINT: { 5453 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5454 "Unexpected custom legalisation"); 5455 bool IsStrict = N->isStrictFPOpcode(); 5456 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5457 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5458 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5459 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5460 TargetLowering::TypeSoftenFloat) { 5461 // FIXME: Support strict FP. 5462 if (IsStrict) 5463 return; 5464 if (!isTypeLegal(Op0.getValueType())) 5465 return; 5466 unsigned Opc = 5467 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5468 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5469 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5470 return; 5471 } 5472 // If the FP type needs to be softened, emit a library call using the 'si' 5473 // version. If we left it to default legalization we'd end up with 'di'. If 5474 // the FP type doesn't need to be softened just let generic type 5475 // legalization promote the result type. 5476 RTLIB::Libcall LC; 5477 if (IsSigned) 5478 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5479 else 5480 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5481 MakeLibCallOptions CallOptions; 5482 EVT OpVT = Op0.getValueType(); 5483 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5484 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5485 SDValue Result; 5486 std::tie(Result, Chain) = 5487 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5488 Results.push_back(Result); 5489 if (IsStrict) 5490 Results.push_back(Chain); 5491 break; 5492 } 5493 case ISD::READCYCLECOUNTER: { 5494 assert(!Subtarget.is64Bit() && 5495 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5496 5497 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5498 SDValue RCW = 5499 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5500 5501 Results.push_back( 5502 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5503 Results.push_back(RCW.getValue(2)); 5504 break; 5505 } 5506 case ISD::MUL: { 5507 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5508 unsigned XLen = Subtarget.getXLen(); 5509 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5510 if (Size > XLen) { 5511 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5512 SDValue LHS = N->getOperand(0); 5513 SDValue RHS = N->getOperand(1); 5514 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5515 5516 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5517 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5518 // We need exactly one side to be unsigned. 5519 if (LHSIsU == RHSIsU) 5520 return; 5521 5522 auto MakeMULPair = [&](SDValue S, SDValue U) { 5523 MVT XLenVT = Subtarget.getXLenVT(); 5524 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5525 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5526 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5527 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5528 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5529 }; 5530 5531 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5532 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5533 5534 // The other operand should be signed, but still prefer MULH when 5535 // possible. 5536 if (RHSIsU && LHSIsS && !RHSIsS) 5537 Results.push_back(MakeMULPair(LHS, RHS)); 5538 else if (LHSIsU && RHSIsS && !LHSIsS) 5539 Results.push_back(MakeMULPair(RHS, LHS)); 5540 5541 return; 5542 } 5543 LLVM_FALLTHROUGH; 5544 } 5545 case ISD::ADD: 5546 case ISD::SUB: 5547 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5548 "Unexpected custom legalisation"); 5549 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5550 break; 5551 case ISD::SHL: 5552 case ISD::SRA: 5553 case ISD::SRL: 5554 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5555 "Unexpected custom legalisation"); 5556 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5557 Results.push_back(customLegalizeToWOp(N, DAG)); 5558 break; 5559 } 5560 5561 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5562 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5563 // shift amount. 5564 if (N->getOpcode() == ISD::SHL) { 5565 SDLoc DL(N); 5566 SDValue NewOp0 = 5567 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5568 SDValue NewOp1 = 5569 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5570 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5571 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5572 DAG.getValueType(MVT::i32)); 5573 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5574 } 5575 5576 break; 5577 case ISD::ROTL: 5578 case ISD::ROTR: 5579 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5580 "Unexpected custom legalisation"); 5581 Results.push_back(customLegalizeToWOp(N, DAG)); 5582 break; 5583 case ISD::CTTZ: 5584 case ISD::CTTZ_ZERO_UNDEF: 5585 case ISD::CTLZ: 5586 case ISD::CTLZ_ZERO_UNDEF: { 5587 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5588 "Unexpected custom legalisation"); 5589 5590 SDValue NewOp0 = 5591 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5592 bool IsCTZ = 5593 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5594 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5595 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5596 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5597 return; 5598 } 5599 case ISD::SDIV: 5600 case ISD::UDIV: 5601 case ISD::UREM: { 5602 MVT VT = N->getSimpleValueType(0); 5603 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5604 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5605 "Unexpected custom legalisation"); 5606 // Don't promote division/remainder by constant since we should expand those 5607 // to multiply by magic constant. 5608 // FIXME: What if the expansion is disabled for minsize. 5609 if (N->getOperand(1).getOpcode() == ISD::Constant) 5610 return; 5611 5612 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5613 // the upper 32 bits. For other types we need to sign or zero extend 5614 // based on the opcode. 5615 unsigned ExtOpc = ISD::ANY_EXTEND; 5616 if (VT != MVT::i32) 5617 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5618 : ISD::ZERO_EXTEND; 5619 5620 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5621 break; 5622 } 5623 case ISD::UADDO: 5624 case ISD::USUBO: { 5625 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5626 "Unexpected custom legalisation"); 5627 bool IsAdd = N->getOpcode() == ISD::UADDO; 5628 // Create an ADDW or SUBW. 5629 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5630 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5631 SDValue Res = 5632 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5633 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5634 DAG.getValueType(MVT::i32)); 5635 5636 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5637 // Since the inputs are sign extended from i32, this is equivalent to 5638 // comparing the lower 32 bits. 5639 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5640 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5641 IsAdd ? ISD::SETULT : ISD::SETUGT); 5642 5643 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5644 Results.push_back(Overflow); 5645 return; 5646 } 5647 case ISD::UADDSAT: 5648 case ISD::USUBSAT: { 5649 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5650 "Unexpected custom legalisation"); 5651 if (Subtarget.hasStdExtZbb()) { 5652 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5653 // sign extend allows overflow of the lower 32 bits to be detected on 5654 // the promoted size. 5655 SDValue LHS = 5656 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5657 SDValue RHS = 5658 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5659 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5660 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5661 return; 5662 } 5663 5664 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5665 // promotion for UADDO/USUBO. 5666 Results.push_back(expandAddSubSat(N, DAG)); 5667 return; 5668 } 5669 case ISD::BITCAST: { 5670 EVT VT = N->getValueType(0); 5671 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5672 SDValue Op0 = N->getOperand(0); 5673 EVT Op0VT = Op0.getValueType(); 5674 MVT XLenVT = Subtarget.getXLenVT(); 5675 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5676 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5677 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5678 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 5679 Subtarget.hasStdExtF()) { 5680 SDValue FPConv = 5681 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 5682 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 5683 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 5684 isTypeLegal(Op0VT)) { 5685 // Custom-legalize bitcasts from fixed-length vector types to illegal 5686 // scalar types in order to improve codegen. Bitcast the vector to a 5687 // one-element vector type whose element type is the same as the result 5688 // type, and extract the first element. 5689 LLVMContext &Context = *DAG.getContext(); 5690 SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0); 5691 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 5692 DAG.getConstant(0, DL, XLenVT))); 5693 } 5694 break; 5695 } 5696 case RISCVISD::GREV: 5697 case RISCVISD::GORC: { 5698 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5699 "Unexpected custom legalisation"); 5700 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5701 // This is similar to customLegalizeToWOp, except that we pass the second 5702 // operand (a TargetConstant) straight through: it is already of type 5703 // XLenVT. 5704 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5705 SDValue NewOp0 = 5706 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5707 SDValue NewOp1 = 5708 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5709 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5710 // ReplaceNodeResults requires we maintain the same type for the return 5711 // value. 5712 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5713 break; 5714 } 5715 case RISCVISD::SHFL: { 5716 // There is no SHFLIW instruction, but we can just promote the operation. 5717 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5718 "Unexpected custom legalisation"); 5719 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 5720 SDValue NewOp0 = 5721 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5722 SDValue NewOp1 = 5723 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5724 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 5725 // ReplaceNodeResults requires we maintain the same type for the return 5726 // value. 5727 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5728 break; 5729 } 5730 case ISD::BSWAP: 5731 case ISD::BITREVERSE: { 5732 MVT VT = N->getSimpleValueType(0); 5733 MVT XLenVT = Subtarget.getXLenVT(); 5734 assert((VT == MVT::i8 || VT == MVT::i16 || 5735 (VT == MVT::i32 && Subtarget.is64Bit())) && 5736 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 5737 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 5738 unsigned Imm = VT.getSizeInBits() - 1; 5739 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 5740 if (N->getOpcode() == ISD::BSWAP) 5741 Imm &= ~0x7U; 5742 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 5743 SDValue GREVI = 5744 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 5745 // ReplaceNodeResults requires we maintain the same type for the return 5746 // value. 5747 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 5748 break; 5749 } 5750 case ISD::FSHL: 5751 case ISD::FSHR: { 5752 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5753 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 5754 SDValue NewOp0 = 5755 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5756 SDValue NewOp1 = 5757 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5758 SDValue NewOp2 = 5759 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5760 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 5761 // Mask the shift amount to 5 bits. 5762 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5763 DAG.getConstant(0x1f, DL, MVT::i64)); 5764 unsigned Opc = 5765 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 5766 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 5767 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 5768 break; 5769 } 5770 case ISD::EXTRACT_VECTOR_ELT: { 5771 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 5772 // type is illegal (currently only vXi64 RV32). 5773 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 5774 // transferred to the destination register. We issue two of these from the 5775 // upper- and lower- halves of the SEW-bit vector element, slid down to the 5776 // first element. 5777 SDValue Vec = N->getOperand(0); 5778 SDValue Idx = N->getOperand(1); 5779 5780 // The vector type hasn't been legalized yet so we can't issue target 5781 // specific nodes if it needs legalization. 5782 // FIXME: We would manually legalize if it's important. 5783 if (!isTypeLegal(Vec.getValueType())) 5784 return; 5785 5786 MVT VecVT = Vec.getSimpleValueType(); 5787 5788 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 5789 VecVT.getVectorElementType() == MVT::i64 && 5790 "Unexpected EXTRACT_VECTOR_ELT legalization"); 5791 5792 // If this is a fixed vector, we need to convert it to a scalable vector. 5793 MVT ContainerVT = VecVT; 5794 if (VecVT.isFixedLengthVector()) { 5795 ContainerVT = getContainerForFixedLengthVector(VecVT); 5796 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5797 } 5798 5799 MVT XLenVT = Subtarget.getXLenVT(); 5800 5801 // Use a VL of 1 to avoid processing more elements than we need. 5802 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5803 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5804 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5805 5806 // Unless the index is known to be 0, we must slide the vector down to get 5807 // the desired element into index 0. 5808 if (!isNullConstant(Idx)) { 5809 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5810 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 5811 } 5812 5813 // Extract the lower XLEN bits of the correct vector element. 5814 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5815 5816 // To extract the upper XLEN bits of the vector element, shift the first 5817 // element right by 32 bits and re-extract the lower XLEN bits. 5818 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5819 DAG.getConstant(32, DL, XLenVT), VL); 5820 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 5821 ThirtyTwoV, Mask, VL); 5822 5823 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5824 5825 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5826 break; 5827 } 5828 case ISD::INTRINSIC_WO_CHAIN: { 5829 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5830 switch (IntNo) { 5831 default: 5832 llvm_unreachable( 5833 "Don't know how to custom type legalize this intrinsic!"); 5834 case Intrinsic::riscv_orc_b: { 5835 // Lower to the GORCI encoding for orc.b with the operand extended. 5836 SDValue NewOp = 5837 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5838 // If Zbp is enabled, use GORCIW which will sign extend the result. 5839 unsigned Opc = 5840 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 5841 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 5842 DAG.getConstant(7, DL, MVT::i64)); 5843 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5844 return; 5845 } 5846 case Intrinsic::riscv_grev: 5847 case Intrinsic::riscv_gorc: { 5848 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5849 "Unexpected custom legalisation"); 5850 SDValue NewOp1 = 5851 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5852 SDValue NewOp2 = 5853 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5854 unsigned Opc = 5855 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 5856 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5857 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5858 break; 5859 } 5860 case Intrinsic::riscv_shfl: 5861 case Intrinsic::riscv_unshfl: { 5862 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5863 "Unexpected custom legalisation"); 5864 SDValue NewOp1 = 5865 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5866 SDValue NewOp2 = 5867 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5868 unsigned Opc = 5869 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 5870 if (isa<ConstantSDNode>(N->getOperand(2))) { 5871 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 5872 DAG.getConstant(0xf, DL, MVT::i64)); 5873 Opc = 5874 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 5875 } 5876 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5877 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5878 break; 5879 } 5880 case Intrinsic::riscv_bcompress: 5881 case Intrinsic::riscv_bdecompress: { 5882 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5883 "Unexpected custom legalisation"); 5884 SDValue NewOp1 = 5885 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5886 SDValue NewOp2 = 5887 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5888 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 5889 ? RISCVISD::BCOMPRESSW 5890 : RISCVISD::BDECOMPRESSW; 5891 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 5892 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5893 break; 5894 } 5895 case Intrinsic::riscv_vmv_x_s: { 5896 EVT VT = N->getValueType(0); 5897 MVT XLenVT = Subtarget.getXLenVT(); 5898 if (VT.bitsLT(XLenVT)) { 5899 // Simple case just extract using vmv.x.s and truncate. 5900 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 5901 Subtarget.getXLenVT(), N->getOperand(1)); 5902 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 5903 return; 5904 } 5905 5906 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 5907 "Unexpected custom legalization"); 5908 5909 // We need to do the move in two steps. 5910 SDValue Vec = N->getOperand(1); 5911 MVT VecVT = Vec.getSimpleValueType(); 5912 5913 // First extract the lower XLEN bits of the element. 5914 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 5915 5916 // To extract the upper XLEN bits of the vector element, shift the first 5917 // element right by 32 bits and re-extract the lower XLEN bits. 5918 SDValue VL = DAG.getConstant(1, DL, XLenVT); 5919 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 5920 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5921 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 5922 DAG.getConstant(32, DL, XLenVT), VL); 5923 SDValue LShr32 = 5924 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 5925 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 5926 5927 Results.push_back( 5928 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 5929 break; 5930 } 5931 } 5932 break; 5933 } 5934 case ISD::VECREDUCE_ADD: 5935 case ISD::VECREDUCE_AND: 5936 case ISD::VECREDUCE_OR: 5937 case ISD::VECREDUCE_XOR: 5938 case ISD::VECREDUCE_SMAX: 5939 case ISD::VECREDUCE_UMAX: 5940 case ISD::VECREDUCE_SMIN: 5941 case ISD::VECREDUCE_UMIN: 5942 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 5943 Results.push_back(V); 5944 break; 5945 case ISD::VP_REDUCE_ADD: 5946 case ISD::VP_REDUCE_AND: 5947 case ISD::VP_REDUCE_OR: 5948 case ISD::VP_REDUCE_XOR: 5949 case ISD::VP_REDUCE_SMAX: 5950 case ISD::VP_REDUCE_UMAX: 5951 case ISD::VP_REDUCE_SMIN: 5952 case ISD::VP_REDUCE_UMIN: 5953 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 5954 Results.push_back(V); 5955 break; 5956 case ISD::FLT_ROUNDS_: { 5957 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 5958 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 5959 Results.push_back(Res.getValue(0)); 5960 Results.push_back(Res.getValue(1)); 5961 break; 5962 } 5963 } 5964 } 5965 5966 // A structure to hold one of the bit-manipulation patterns below. Together, a 5967 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 5968 // (or (and (shl x, 1), 0xAAAAAAAA), 5969 // (and (srl x, 1), 0x55555555)) 5970 struct RISCVBitmanipPat { 5971 SDValue Op; 5972 unsigned ShAmt; 5973 bool IsSHL; 5974 5975 bool formsPairWith(const RISCVBitmanipPat &Other) const { 5976 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 5977 } 5978 }; 5979 5980 // Matches patterns of the form 5981 // (and (shl x, C2), (C1 << C2)) 5982 // (and (srl x, C2), C1) 5983 // (shl (and x, C1), C2) 5984 // (srl (and x, (C1 << C2)), C2) 5985 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 5986 // The expected masks for each shift amount are specified in BitmanipMasks where 5987 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 5988 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 5989 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 5990 // XLen is 64. 5991 static Optional<RISCVBitmanipPat> 5992 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 5993 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 5994 "Unexpected number of masks"); 5995 Optional<uint64_t> Mask; 5996 // Optionally consume a mask around the shift operation. 5997 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 5998 Mask = Op.getConstantOperandVal(1); 5999 Op = Op.getOperand(0); 6000 } 6001 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6002 return None; 6003 bool IsSHL = Op.getOpcode() == ISD::SHL; 6004 6005 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6006 return None; 6007 uint64_t ShAmt = Op.getConstantOperandVal(1); 6008 6009 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6010 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6011 return None; 6012 // If we don't have enough masks for 64 bit, then we must be trying to 6013 // match SHFL so we're only allowed to shift 1/4 of the width. 6014 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6015 return None; 6016 6017 SDValue Src = Op.getOperand(0); 6018 6019 // The expected mask is shifted left when the AND is found around SHL 6020 // patterns. 6021 // ((x >> 1) & 0x55555555) 6022 // ((x << 1) & 0xAAAAAAAA) 6023 bool SHLExpMask = IsSHL; 6024 6025 if (!Mask) { 6026 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6027 // the mask is all ones: consume that now. 6028 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6029 Mask = Src.getConstantOperandVal(1); 6030 Src = Src.getOperand(0); 6031 // The expected mask is now in fact shifted left for SRL, so reverse the 6032 // decision. 6033 // ((x & 0xAAAAAAAA) >> 1) 6034 // ((x & 0x55555555) << 1) 6035 SHLExpMask = !SHLExpMask; 6036 } else { 6037 // Use a default shifted mask of all-ones if there's no AND, truncated 6038 // down to the expected width. This simplifies the logic later on. 6039 Mask = maskTrailingOnes<uint64_t>(Width); 6040 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6041 } 6042 } 6043 6044 unsigned MaskIdx = Log2_32(ShAmt); 6045 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6046 6047 if (SHLExpMask) 6048 ExpMask <<= ShAmt; 6049 6050 if (Mask != ExpMask) 6051 return None; 6052 6053 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6054 } 6055 6056 // Matches any of the following bit-manipulation patterns: 6057 // (and (shl x, 1), (0x55555555 << 1)) 6058 // (and (srl x, 1), 0x55555555) 6059 // (shl (and x, 0x55555555), 1) 6060 // (srl (and x, (0x55555555 << 1)), 1) 6061 // where the shift amount and mask may vary thus: 6062 // [1] = 0x55555555 / 0xAAAAAAAA 6063 // [2] = 0x33333333 / 0xCCCCCCCC 6064 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6065 // [8] = 0x00FF00FF / 0xFF00FF00 6066 // [16] = 0x0000FFFF / 0xFFFFFFFF 6067 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6068 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6069 // These are the unshifted masks which we use to match bit-manipulation 6070 // patterns. They may be shifted left in certain circumstances. 6071 static const uint64_t BitmanipMasks[] = { 6072 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6073 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6074 6075 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6076 } 6077 6078 // Match the following pattern as a GREVI(W) operation 6079 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6080 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6081 const RISCVSubtarget &Subtarget) { 6082 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6083 EVT VT = Op.getValueType(); 6084 6085 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6086 auto LHS = matchGREVIPat(Op.getOperand(0)); 6087 auto RHS = matchGREVIPat(Op.getOperand(1)); 6088 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6089 SDLoc DL(Op); 6090 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6091 DAG.getConstant(LHS->ShAmt, DL, VT)); 6092 } 6093 } 6094 return SDValue(); 6095 } 6096 6097 // Matches any the following pattern as a GORCI(W) operation 6098 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6099 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6100 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6101 // Note that with the variant of 3., 6102 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6103 // the inner pattern will first be matched as GREVI and then the outer 6104 // pattern will be matched to GORC via the first rule above. 6105 // 4. (or (rotl/rotr x, bitwidth/2), x) 6106 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6107 const RISCVSubtarget &Subtarget) { 6108 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6109 EVT VT = Op.getValueType(); 6110 6111 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6112 SDLoc DL(Op); 6113 SDValue Op0 = Op.getOperand(0); 6114 SDValue Op1 = Op.getOperand(1); 6115 6116 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6117 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6118 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6119 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6120 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6121 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6122 if ((Reverse.getOpcode() == ISD::ROTL || 6123 Reverse.getOpcode() == ISD::ROTR) && 6124 Reverse.getOperand(0) == X && 6125 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6126 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6127 if (RotAmt == (VT.getSizeInBits() / 2)) 6128 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6129 DAG.getConstant(RotAmt, DL, VT)); 6130 } 6131 return SDValue(); 6132 }; 6133 6134 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6135 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6136 return V; 6137 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6138 return V; 6139 6140 // OR is commutable so canonicalize its OR operand to the left 6141 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6142 std::swap(Op0, Op1); 6143 if (Op0.getOpcode() != ISD::OR) 6144 return SDValue(); 6145 SDValue OrOp0 = Op0.getOperand(0); 6146 SDValue OrOp1 = Op0.getOperand(1); 6147 auto LHS = matchGREVIPat(OrOp0); 6148 // OR is commutable so swap the operands and try again: x might have been 6149 // on the left 6150 if (!LHS) { 6151 std::swap(OrOp0, OrOp1); 6152 LHS = matchGREVIPat(OrOp0); 6153 } 6154 auto RHS = matchGREVIPat(Op1); 6155 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6156 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6157 DAG.getConstant(LHS->ShAmt, DL, VT)); 6158 } 6159 } 6160 return SDValue(); 6161 } 6162 6163 // Matches any of the following bit-manipulation patterns: 6164 // (and (shl x, 1), (0x22222222 << 1)) 6165 // (and (srl x, 1), 0x22222222) 6166 // (shl (and x, 0x22222222), 1) 6167 // (srl (and x, (0x22222222 << 1)), 1) 6168 // where the shift amount and mask may vary thus: 6169 // [1] = 0x22222222 / 0x44444444 6170 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6171 // [4] = 0x00F000F0 / 0x0F000F00 6172 // [8] = 0x0000FF00 / 0x00FF0000 6173 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6174 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6175 // These are the unshifted masks which we use to match bit-manipulation 6176 // patterns. They may be shifted left in certain circumstances. 6177 static const uint64_t BitmanipMasks[] = { 6178 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6179 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6180 6181 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6182 } 6183 6184 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6185 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6186 const RISCVSubtarget &Subtarget) { 6187 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6188 EVT VT = Op.getValueType(); 6189 6190 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6191 return SDValue(); 6192 6193 SDValue Op0 = Op.getOperand(0); 6194 SDValue Op1 = Op.getOperand(1); 6195 6196 // Or is commutable so canonicalize the second OR to the LHS. 6197 if (Op0.getOpcode() != ISD::OR) 6198 std::swap(Op0, Op1); 6199 if (Op0.getOpcode() != ISD::OR) 6200 return SDValue(); 6201 6202 // We found an inner OR, so our operands are the operands of the inner OR 6203 // and the other operand of the outer OR. 6204 SDValue A = Op0.getOperand(0); 6205 SDValue B = Op0.getOperand(1); 6206 SDValue C = Op1; 6207 6208 auto Match1 = matchSHFLPat(A); 6209 auto Match2 = matchSHFLPat(B); 6210 6211 // If neither matched, we failed. 6212 if (!Match1 && !Match2) 6213 return SDValue(); 6214 6215 // We had at least one match. if one failed, try the remaining C operand. 6216 if (!Match1) { 6217 std::swap(A, C); 6218 Match1 = matchSHFLPat(A); 6219 if (!Match1) 6220 return SDValue(); 6221 } else if (!Match2) { 6222 std::swap(B, C); 6223 Match2 = matchSHFLPat(B); 6224 if (!Match2) 6225 return SDValue(); 6226 } 6227 assert(Match1 && Match2); 6228 6229 // Make sure our matches pair up. 6230 if (!Match1->formsPairWith(*Match2)) 6231 return SDValue(); 6232 6233 // All the remains is to make sure C is an AND with the same input, that masks 6234 // out the bits that are being shuffled. 6235 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6236 C.getOperand(0) != Match1->Op) 6237 return SDValue(); 6238 6239 uint64_t Mask = C.getConstantOperandVal(1); 6240 6241 static const uint64_t BitmanipMasks[] = { 6242 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6243 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6244 }; 6245 6246 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6247 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6248 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6249 6250 if (Mask != ExpMask) 6251 return SDValue(); 6252 6253 SDLoc DL(Op); 6254 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6255 DAG.getConstant(Match1->ShAmt, DL, VT)); 6256 } 6257 6258 // Optimize (add (shl x, c0), (shl y, c1)) -> 6259 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6260 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6261 const RISCVSubtarget &Subtarget) { 6262 // Perform this optimization only in the zba extension. 6263 if (!Subtarget.hasStdExtZba()) 6264 return SDValue(); 6265 6266 // Skip for vector types and larger types. 6267 EVT VT = N->getValueType(0); 6268 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6269 return SDValue(); 6270 6271 // The two operand nodes must be SHL and have no other use. 6272 SDValue N0 = N->getOperand(0); 6273 SDValue N1 = N->getOperand(1); 6274 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6275 !N0->hasOneUse() || !N1->hasOneUse()) 6276 return SDValue(); 6277 6278 // Check c0 and c1. 6279 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6280 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6281 if (!N0C || !N1C) 6282 return SDValue(); 6283 int64_t C0 = N0C->getSExtValue(); 6284 int64_t C1 = N1C->getSExtValue(); 6285 if (C0 <= 0 || C1 <= 0) 6286 return SDValue(); 6287 6288 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6289 int64_t Bits = std::min(C0, C1); 6290 int64_t Diff = std::abs(C0 - C1); 6291 if (Diff != 1 && Diff != 2 && Diff != 3) 6292 return SDValue(); 6293 6294 // Build nodes. 6295 SDLoc DL(N); 6296 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6297 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6298 SDValue NA0 = 6299 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6300 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6301 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6302 } 6303 6304 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6305 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6306 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6307 // not undo itself, but they are redundant. 6308 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6309 SDValue Src = N->getOperand(0); 6310 6311 if (Src.getOpcode() != N->getOpcode()) 6312 return SDValue(); 6313 6314 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6315 !isa<ConstantSDNode>(Src.getOperand(1))) 6316 return SDValue(); 6317 6318 unsigned ShAmt1 = N->getConstantOperandVal(1); 6319 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6320 Src = Src.getOperand(0); 6321 6322 unsigned CombinedShAmt; 6323 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6324 CombinedShAmt = ShAmt1 | ShAmt2; 6325 else 6326 CombinedShAmt = ShAmt1 ^ ShAmt2; 6327 6328 if (CombinedShAmt == 0) 6329 return Src; 6330 6331 SDLoc DL(N); 6332 return DAG.getNode( 6333 N->getOpcode(), DL, N->getValueType(0), Src, 6334 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6335 } 6336 6337 // Combine a constant select operand into its use: 6338 // 6339 // (and (select cond, -1, c), x) 6340 // -> (select cond, x, (and x, c)) [AllOnes=1] 6341 // (or (select cond, 0, c), x) 6342 // -> (select cond, x, (or x, c)) [AllOnes=0] 6343 // (xor (select cond, 0, c), x) 6344 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6345 // (add (select cond, 0, c), x) 6346 // -> (select cond, x, (add x, c)) [AllOnes=0] 6347 // (sub x, (select cond, 0, c)) 6348 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6349 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6350 SelectionDAG &DAG, bool AllOnes) { 6351 EVT VT = N->getValueType(0); 6352 6353 // Skip vectors. 6354 if (VT.isVector()) 6355 return SDValue(); 6356 6357 if ((Slct.getOpcode() != ISD::SELECT && 6358 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6359 !Slct.hasOneUse()) 6360 return SDValue(); 6361 6362 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6363 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6364 }; 6365 6366 bool SwapSelectOps; 6367 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6368 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6369 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6370 SDValue NonConstantVal; 6371 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6372 SwapSelectOps = false; 6373 NonConstantVal = FalseVal; 6374 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6375 SwapSelectOps = true; 6376 NonConstantVal = TrueVal; 6377 } else 6378 return SDValue(); 6379 6380 // Slct is now know to be the desired identity constant when CC is true. 6381 TrueVal = OtherOp; 6382 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6383 // Unless SwapSelectOps says the condition should be false. 6384 if (SwapSelectOps) 6385 std::swap(TrueVal, FalseVal); 6386 6387 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6388 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6389 {Slct.getOperand(0), Slct.getOperand(1), 6390 Slct.getOperand(2), TrueVal, FalseVal}); 6391 6392 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6393 {Slct.getOperand(0), TrueVal, FalseVal}); 6394 } 6395 6396 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6397 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6398 bool AllOnes) { 6399 SDValue N0 = N->getOperand(0); 6400 SDValue N1 = N->getOperand(1); 6401 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6402 return Result; 6403 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6404 return Result; 6405 return SDValue(); 6406 } 6407 6408 // Transform (add (mul x, c0), c1) -> 6409 // (add (mul (add x, c1/c0), c0), c1%c0). 6410 // if c1/c0 and c1%c0 are simm12, while c1 is not. 6411 // Or transform (add (mul x, c0), c1) -> 6412 // (mul (add x, c1/c0), c0). 6413 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6414 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6415 const RISCVSubtarget &Subtarget) { 6416 // Skip for vector types and larger types. 6417 EVT VT = N->getValueType(0); 6418 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6419 return SDValue(); 6420 // The first operand node must be a MUL and has no other use. 6421 SDValue N0 = N->getOperand(0); 6422 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6423 return SDValue(); 6424 // Check if c0 and c1 match above conditions. 6425 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6426 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6427 if (!N0C || !N1C) 6428 return SDValue(); 6429 int64_t C0 = N0C->getSExtValue(); 6430 int64_t C1 = N1C->getSExtValue(); 6431 if (C0 == -1 || C0 == 0 || C0 == 1 || (C1 / C0) == 0 || isInt<12>(C1) || 6432 !isInt<12>(C1 % C0) || !isInt<12>(C1 / C0)) 6433 return SDValue(); 6434 // If C0 * (C1 / C0) is a 12-bit integer, this transform will be reversed. 6435 if (isInt<12>(C0 * (C1 / C0))) 6436 return SDValue(); 6437 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6438 SDLoc DL(N); 6439 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6440 DAG.getConstant(C1 / C0, DL, VT)); 6441 SDValue New1 = 6442 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6443 if ((C1 % C0) == 0) 6444 return New1; 6445 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(C1 % C0, DL, VT)); 6446 } 6447 6448 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6449 const RISCVSubtarget &Subtarget) { 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. 6453 // Or transform (add (mul x, c0), c1) -> 6454 // (mul (add x, c1/c0), c0). 6455 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6456 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6457 return V; 6458 // Fold (add (shl x, c0), (shl y, c1)) -> 6459 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6460 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6461 return V; 6462 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6463 // (select lhs, rhs, cc, x, (add x, y)) 6464 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6465 } 6466 6467 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6468 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6469 // (select lhs, rhs, cc, x, (sub x, y)) 6470 SDValue N0 = N->getOperand(0); 6471 SDValue N1 = N->getOperand(1); 6472 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6473 } 6474 6475 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6476 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6477 // (select lhs, rhs, cc, x, (and x, y)) 6478 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6479 } 6480 6481 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6482 const RISCVSubtarget &Subtarget) { 6483 if (Subtarget.hasStdExtZbp()) { 6484 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6485 return GREV; 6486 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6487 return GORC; 6488 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6489 return SHFL; 6490 } 6491 6492 // fold (or (select cond, 0, y), x) -> 6493 // (select cond, x, (or x, y)) 6494 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6495 } 6496 6497 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6498 // fold (xor (select cond, 0, y), x) -> 6499 // (select cond, x, (xor x, y)) 6500 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6501 } 6502 6503 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6504 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6505 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6506 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6507 // ADDW/SUBW/MULW. 6508 static SDValue performANY_EXTENDCombine(SDNode *N, 6509 TargetLowering::DAGCombinerInfo &DCI, 6510 const RISCVSubtarget &Subtarget) { 6511 if (!Subtarget.is64Bit()) 6512 return SDValue(); 6513 6514 SelectionDAG &DAG = DCI.DAG; 6515 6516 SDValue Src = N->getOperand(0); 6517 EVT VT = N->getValueType(0); 6518 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6519 return SDValue(); 6520 6521 // The opcode must be one that can implicitly sign_extend. 6522 // FIXME: Additional opcodes. 6523 switch (Src.getOpcode()) { 6524 default: 6525 return SDValue(); 6526 case ISD::MUL: 6527 if (!Subtarget.hasStdExtM()) 6528 return SDValue(); 6529 LLVM_FALLTHROUGH; 6530 case ISD::ADD: 6531 case ISD::SUB: 6532 break; 6533 } 6534 6535 // Only handle cases where the result is used by a CopyToReg. That likely 6536 // means the value is a liveout of the basic block. This helps prevent 6537 // infinite combine loops like PR51206. 6538 if (none_of(N->uses(), 6539 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6540 return SDValue(); 6541 6542 SmallVector<SDNode *, 4> SetCCs; 6543 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6544 UE = Src.getNode()->use_end(); 6545 UI != UE; ++UI) { 6546 SDNode *User = *UI; 6547 if (User == N) 6548 continue; 6549 if (UI.getUse().getResNo() != Src.getResNo()) 6550 continue; 6551 // All i32 setccs are legalized by sign extending operands. 6552 if (User->getOpcode() == ISD::SETCC) { 6553 SetCCs.push_back(User); 6554 continue; 6555 } 6556 // We don't know if we can extend this user. 6557 break; 6558 } 6559 6560 // If we don't have any SetCCs, this isn't worthwhile. 6561 if (SetCCs.empty()) 6562 return SDValue(); 6563 6564 SDLoc DL(N); 6565 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6566 DCI.CombineTo(N, SExt); 6567 6568 // Promote all the setccs. 6569 for (SDNode *SetCC : SetCCs) { 6570 SmallVector<SDValue, 4> Ops; 6571 6572 for (unsigned j = 0; j != 2; ++j) { 6573 SDValue SOp = SetCC->getOperand(j); 6574 if (SOp == Src) 6575 Ops.push_back(SExt); 6576 else 6577 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6578 } 6579 6580 Ops.push_back(SetCC->getOperand(2)); 6581 DCI.CombineTo(SetCC, 6582 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6583 } 6584 return SDValue(N, 0); 6585 } 6586 6587 // Try to form VWMUL or VWMULU. 6588 // FIXME: Support VWMULSU. 6589 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6590 SelectionDAG &DAG) { 6591 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6592 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6593 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6594 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6595 return SDValue(); 6596 6597 SDValue Mask = N->getOperand(2); 6598 SDValue VL = N->getOperand(3); 6599 6600 // Make sure the mask and VL match. 6601 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6602 return SDValue(); 6603 6604 MVT VT = N->getSimpleValueType(0); 6605 6606 // Determine the narrow size for a widening multiply. 6607 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 6608 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 6609 VT.getVectorElementCount()); 6610 6611 SDLoc DL(N); 6612 6613 // See if the other operand is the same opcode. 6614 if (Op0.getOpcode() == Op1.getOpcode()) { 6615 if (!Op1.hasOneUse()) 6616 return SDValue(); 6617 6618 // Make sure the mask and VL match. 6619 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 6620 return SDValue(); 6621 6622 Op1 = Op1.getOperand(0); 6623 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 6624 // The operand is a splat of a scalar. 6625 6626 // The VL must be the same. 6627 if (Op1.getOperand(1) != VL) 6628 return SDValue(); 6629 6630 // Get the scalar value. 6631 Op1 = Op1.getOperand(0); 6632 6633 // See if have enough sign bits or zero bits in the scalar to use a 6634 // widening multiply by splatting to smaller element size. 6635 unsigned EltBits = VT.getScalarSizeInBits(); 6636 unsigned ScalarBits = Op1.getValueSizeInBits(); 6637 // Make sure we're getting all element bits from the scalar register. 6638 // FIXME: Support implicit sign extension of vmv.v.x? 6639 if (ScalarBits < EltBits) 6640 return SDValue(); 6641 6642 if (IsSignExt) { 6643 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 6644 return SDValue(); 6645 } else { 6646 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 6647 if (!DAG.MaskedValueIsZero(Op1, Mask)) 6648 return SDValue(); 6649 } 6650 6651 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 6652 } else 6653 return SDValue(); 6654 6655 Op0 = Op0.getOperand(0); 6656 6657 // Re-introduce narrower extends if needed. 6658 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 6659 if (Op0.getValueType() != NarrowVT) 6660 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 6661 if (Op1.getValueType() != NarrowVT) 6662 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 6663 6664 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 6665 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 6666 } 6667 6668 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 6669 DAGCombinerInfo &DCI) const { 6670 SelectionDAG &DAG = DCI.DAG; 6671 6672 // Helper to call SimplifyDemandedBits on an operand of N where only some low 6673 // bits are demanded. N will be added to the Worklist if it was not deleted. 6674 // Caller should return SDValue(N, 0) if this returns true. 6675 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 6676 SDValue Op = N->getOperand(OpNo); 6677 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 6678 if (!SimplifyDemandedBits(Op, Mask, DCI)) 6679 return false; 6680 6681 if (N->getOpcode() != ISD::DELETED_NODE) 6682 DCI.AddToWorklist(N); 6683 return true; 6684 }; 6685 6686 switch (N->getOpcode()) { 6687 default: 6688 break; 6689 case RISCVISD::SplitF64: { 6690 SDValue Op0 = N->getOperand(0); 6691 // If the input to SplitF64 is just BuildPairF64 then the operation is 6692 // redundant. Instead, use BuildPairF64's operands directly. 6693 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 6694 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 6695 6696 SDLoc DL(N); 6697 6698 // It's cheaper to materialise two 32-bit integers than to load a double 6699 // from the constant pool and transfer it to integer registers through the 6700 // stack. 6701 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 6702 APInt V = C->getValueAPF().bitcastToAPInt(); 6703 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 6704 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 6705 return DCI.CombineTo(N, Lo, Hi); 6706 } 6707 6708 // This is a target-specific version of a DAGCombine performed in 6709 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6710 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6711 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6712 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6713 !Op0.getNode()->hasOneUse()) 6714 break; 6715 SDValue NewSplitF64 = 6716 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 6717 Op0.getOperand(0)); 6718 SDValue Lo = NewSplitF64.getValue(0); 6719 SDValue Hi = NewSplitF64.getValue(1); 6720 APInt SignBit = APInt::getSignMask(32); 6721 if (Op0.getOpcode() == ISD::FNEG) { 6722 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 6723 DAG.getConstant(SignBit, DL, MVT::i32)); 6724 return DCI.CombineTo(N, Lo, NewHi); 6725 } 6726 assert(Op0.getOpcode() == ISD::FABS); 6727 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 6728 DAG.getConstant(~SignBit, DL, MVT::i32)); 6729 return DCI.CombineTo(N, Lo, NewHi); 6730 } 6731 case RISCVISD::SLLW: 6732 case RISCVISD::SRAW: 6733 case RISCVISD::SRLW: 6734 case RISCVISD::ROLW: 6735 case RISCVISD::RORW: { 6736 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6737 if (SimplifyDemandedLowBitsHelper(0, 32) || 6738 SimplifyDemandedLowBitsHelper(1, 5)) 6739 return SDValue(N, 0); 6740 break; 6741 } 6742 case RISCVISD::CLZW: 6743 case RISCVISD::CTZW: { 6744 // Only the lower 32 bits of the first operand are read 6745 if (SimplifyDemandedLowBitsHelper(0, 32)) 6746 return SDValue(N, 0); 6747 break; 6748 } 6749 case RISCVISD::FSL: 6750 case RISCVISD::FSR: { 6751 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 6752 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 6753 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6754 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 6755 return SDValue(N, 0); 6756 break; 6757 } 6758 case RISCVISD::FSLW: 6759 case RISCVISD::FSRW: { 6760 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 6761 // read. 6762 if (SimplifyDemandedLowBitsHelper(0, 32) || 6763 SimplifyDemandedLowBitsHelper(1, 32) || 6764 SimplifyDemandedLowBitsHelper(2, 6)) 6765 return SDValue(N, 0); 6766 break; 6767 } 6768 case RISCVISD::GREV: 6769 case RISCVISD::GORC: { 6770 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 6771 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6772 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6773 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 6774 return SDValue(N, 0); 6775 6776 return combineGREVI_GORCI(N, DCI.DAG); 6777 } 6778 case RISCVISD::GREVW: 6779 case RISCVISD::GORCW: { 6780 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 6781 if (SimplifyDemandedLowBitsHelper(0, 32) || 6782 SimplifyDemandedLowBitsHelper(1, 5)) 6783 return SDValue(N, 0); 6784 6785 return combineGREVI_GORCI(N, DCI.DAG); 6786 } 6787 case RISCVISD::SHFL: 6788 case RISCVISD::UNSHFL: { 6789 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 6790 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 6791 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 6792 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 6793 return SDValue(N, 0); 6794 6795 break; 6796 } 6797 case RISCVISD::SHFLW: 6798 case RISCVISD::UNSHFLW: { 6799 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 6800 SDValue LHS = N->getOperand(0); 6801 SDValue RHS = N->getOperand(1); 6802 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 6803 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 6804 if (SimplifyDemandedLowBitsHelper(0, 32) || 6805 SimplifyDemandedLowBitsHelper(1, 4)) 6806 return SDValue(N, 0); 6807 6808 break; 6809 } 6810 case RISCVISD::BCOMPRESSW: 6811 case RISCVISD::BDECOMPRESSW: { 6812 // Only the lower 32 bits of LHS and RHS are read. 6813 if (SimplifyDemandedLowBitsHelper(0, 32) || 6814 SimplifyDemandedLowBitsHelper(1, 32)) 6815 return SDValue(N, 0); 6816 6817 break; 6818 } 6819 case RISCVISD::FMV_X_ANYEXTH: 6820 case RISCVISD::FMV_X_ANYEXTW_RV64: { 6821 SDLoc DL(N); 6822 SDValue Op0 = N->getOperand(0); 6823 MVT VT = N->getSimpleValueType(0); 6824 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 6825 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 6826 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 6827 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 6828 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 6829 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 6830 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 6831 assert(Op0.getOperand(0).getValueType() == VT && 6832 "Unexpected value type!"); 6833 return Op0.getOperand(0); 6834 } 6835 6836 // This is a target-specific version of a DAGCombine performed in 6837 // DAGCombiner::visitBITCAST. It performs the equivalent of: 6838 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6839 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6840 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 6841 !Op0.getNode()->hasOneUse()) 6842 break; 6843 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 6844 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 6845 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 6846 if (Op0.getOpcode() == ISD::FNEG) 6847 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 6848 DAG.getConstant(SignBit, DL, VT)); 6849 6850 assert(Op0.getOpcode() == ISD::FABS); 6851 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 6852 DAG.getConstant(~SignBit, DL, VT)); 6853 } 6854 case ISD::ADD: 6855 return performADDCombine(N, DAG, Subtarget); 6856 case ISD::SUB: 6857 return performSUBCombine(N, DAG); 6858 case ISD::AND: 6859 return performANDCombine(N, DAG); 6860 case ISD::OR: 6861 return performORCombine(N, DAG, Subtarget); 6862 case ISD::XOR: 6863 return performXORCombine(N, DAG); 6864 case ISD::ANY_EXTEND: 6865 return performANY_EXTENDCombine(N, DCI, Subtarget); 6866 case ISD::ZERO_EXTEND: 6867 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 6868 // type legalization. This is safe because fp_to_uint produces poison if 6869 // it overflows. 6870 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() && 6871 N->getOperand(0).getOpcode() == ISD::FP_TO_UINT && 6872 isTypeLegal(N->getOperand(0).getOperand(0).getValueType())) 6873 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 6874 N->getOperand(0).getOperand(0)); 6875 return SDValue(); 6876 case RISCVISD::SELECT_CC: { 6877 // Transform 6878 SDValue LHS = N->getOperand(0); 6879 SDValue RHS = N->getOperand(1); 6880 SDValue TrueV = N->getOperand(3); 6881 SDValue FalseV = N->getOperand(4); 6882 6883 // If the True and False values are the same, we don't need a select_cc. 6884 if (TrueV == FalseV) 6885 return TrueV; 6886 6887 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6888 if (!ISD::isIntEqualitySetCC(CCVal)) 6889 break; 6890 6891 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 6892 // (select_cc X, Y, lt, trueV, falseV) 6893 // Sometimes the setcc is introduced after select_cc has been formed. 6894 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6895 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6896 // If we're looking for eq 0 instead of ne 0, we need to invert the 6897 // condition. 6898 bool Invert = CCVal == ISD::SETEQ; 6899 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6900 if (Invert) 6901 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6902 6903 SDLoc DL(N); 6904 RHS = LHS.getOperand(1); 6905 LHS = LHS.getOperand(0); 6906 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6907 6908 SDValue TargetCC = DAG.getCondCode(CCVal); 6909 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6910 {LHS, RHS, TargetCC, TrueV, FalseV}); 6911 } 6912 6913 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 6914 // (select_cc X, Y, eq/ne, trueV, falseV) 6915 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6916 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 6917 {LHS.getOperand(0), LHS.getOperand(1), 6918 N->getOperand(2), TrueV, FalseV}); 6919 // (select_cc X, 1, setne, trueV, falseV) -> 6920 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 6921 // This can occur when legalizing some floating point comparisons. 6922 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6923 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6924 SDLoc DL(N); 6925 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6926 SDValue TargetCC = DAG.getCondCode(CCVal); 6927 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6928 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 6929 {LHS, RHS, TargetCC, TrueV, FalseV}); 6930 } 6931 6932 break; 6933 } 6934 case RISCVISD::BR_CC: { 6935 SDValue LHS = N->getOperand(1); 6936 SDValue RHS = N->getOperand(2); 6937 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 6938 if (!ISD::isIntEqualitySetCC(CCVal)) 6939 break; 6940 6941 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 6942 // (br_cc X, Y, lt, dest) 6943 // Sometimes the setcc is introduced after br_cc has been formed. 6944 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 6945 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 6946 // If we're looking for eq 0 instead of ne 0, we need to invert the 6947 // condition. 6948 bool Invert = CCVal == ISD::SETEQ; 6949 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6950 if (Invert) 6951 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6952 6953 SDLoc DL(N); 6954 RHS = LHS.getOperand(1); 6955 LHS = LHS.getOperand(0); 6956 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 6957 6958 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 6959 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 6960 N->getOperand(4)); 6961 } 6962 6963 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 6964 // (br_cc X, Y, eq/ne, trueV, falseV) 6965 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 6966 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 6967 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 6968 N->getOperand(3), N->getOperand(4)); 6969 6970 // (br_cc X, 1, setne, br_cc) -> 6971 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 6972 // This can occur when legalizing some floating point comparisons. 6973 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 6974 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 6975 SDLoc DL(N); 6976 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 6977 SDValue TargetCC = DAG.getCondCode(CCVal); 6978 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 6979 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 6980 N->getOperand(0), LHS, RHS, TargetCC, 6981 N->getOperand(4)); 6982 } 6983 break; 6984 } 6985 case ISD::FCOPYSIGN: { 6986 EVT VT = N->getValueType(0); 6987 if (!VT.isVector()) 6988 break; 6989 // There is a form of VFSGNJ which injects the negated sign of its second 6990 // operand. Try and bubble any FNEG up after the extend/round to produce 6991 // this optimized pattern. Avoid modifying cases where FP_ROUND and 6992 // TRUNC=1. 6993 SDValue In2 = N->getOperand(1); 6994 // Avoid cases where the extend/round has multiple uses, as duplicating 6995 // those is typically more expensive than removing a fneg. 6996 if (!In2.hasOneUse()) 6997 break; 6998 if (In2.getOpcode() != ISD::FP_EXTEND && 6999 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7000 break; 7001 In2 = In2.getOperand(0); 7002 if (In2.getOpcode() != ISD::FNEG) 7003 break; 7004 SDLoc DL(N); 7005 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7006 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7007 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7008 } 7009 case ISD::MGATHER: 7010 case ISD::MSCATTER: 7011 case ISD::VP_GATHER: 7012 case ISD::VP_SCATTER: { 7013 if (!DCI.isBeforeLegalize()) 7014 break; 7015 SDValue Index, ScaleOp; 7016 bool IsIndexScaled = false; 7017 bool IsIndexSigned = false; 7018 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7019 Index = VPGSN->getIndex(); 7020 ScaleOp = VPGSN->getScale(); 7021 IsIndexScaled = VPGSN->isIndexScaled(); 7022 IsIndexSigned = VPGSN->isIndexSigned(); 7023 } else { 7024 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7025 Index = MGSN->getIndex(); 7026 ScaleOp = MGSN->getScale(); 7027 IsIndexScaled = MGSN->isIndexScaled(); 7028 IsIndexSigned = MGSN->isIndexSigned(); 7029 } 7030 EVT IndexVT = Index.getValueType(); 7031 MVT XLenVT = Subtarget.getXLenVT(); 7032 // RISCV indexed loads only support the "unsigned unscaled" addressing 7033 // mode, so anything else must be manually legalized. 7034 bool NeedsIdxLegalization = 7035 IsIndexScaled || 7036 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7037 if (!NeedsIdxLegalization) 7038 break; 7039 7040 SDLoc DL(N); 7041 7042 // Any index legalization should first promote to XLenVT, so we don't lose 7043 // bits when scaling. This may create an illegal index type so we let 7044 // LLVM's legalization take care of the splitting. 7045 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7046 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7047 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7048 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7049 DL, IndexVT, Index); 7050 } 7051 7052 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7053 if (IsIndexScaled && Scale != 1) { 7054 // Manually scale the indices by the element size. 7055 // TODO: Sanitize the scale operand here? 7056 // TODO: For VP nodes, should we use VP_SHL here? 7057 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7058 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7059 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7060 } 7061 7062 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7063 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7064 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7065 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7066 VPGN->getScale(), VPGN->getMask(), 7067 VPGN->getVectorLength()}, 7068 VPGN->getMemOperand(), NewIndexTy); 7069 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7070 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7071 {VPSN->getChain(), VPSN->getValue(), 7072 VPSN->getBasePtr(), Index, VPSN->getScale(), 7073 VPSN->getMask(), VPSN->getVectorLength()}, 7074 VPSN->getMemOperand(), NewIndexTy); 7075 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7076 return DAG.getMaskedGather( 7077 N->getVTList(), MGN->getMemoryVT(), DL, 7078 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7079 MGN->getBasePtr(), Index, MGN->getScale()}, 7080 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7081 const auto *MSN = cast<MaskedScatterSDNode>(N); 7082 return DAG.getMaskedScatter( 7083 N->getVTList(), MSN->getMemoryVT(), DL, 7084 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7085 Index, MSN->getScale()}, 7086 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7087 } 7088 case RISCVISD::SRA_VL: 7089 case RISCVISD::SRL_VL: 7090 case RISCVISD::SHL_VL: { 7091 SDValue ShAmt = N->getOperand(1); 7092 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7093 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7094 SDLoc DL(N); 7095 SDValue VL = N->getOperand(3); 7096 EVT VT = N->getValueType(0); 7097 ShAmt = 7098 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7099 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7100 N->getOperand(2), N->getOperand(3)); 7101 } 7102 break; 7103 } 7104 case ISD::SRA: 7105 case ISD::SRL: 7106 case ISD::SHL: { 7107 SDValue ShAmt = N->getOperand(1); 7108 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7109 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7110 SDLoc DL(N); 7111 EVT VT = N->getValueType(0); 7112 ShAmt = 7113 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7114 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7115 } 7116 break; 7117 } 7118 case RISCVISD::MUL_VL: { 7119 SDValue Op0 = N->getOperand(0); 7120 SDValue Op1 = N->getOperand(1); 7121 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7122 return V; 7123 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7124 return V; 7125 return SDValue(); 7126 } 7127 case ISD::STORE: { 7128 auto *Store = cast<StoreSDNode>(N); 7129 SDValue Val = Store->getValue(); 7130 // Combine store of vmv.x.s to vse with VL of 1. 7131 // FIXME: Support FP. 7132 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7133 SDValue Src = Val.getOperand(0); 7134 EVT VecVT = Src.getValueType(); 7135 EVT MemVT = Store->getMemoryVT(); 7136 // The memory VT and the element type must match. 7137 if (VecVT.getVectorElementType() == MemVT) { 7138 SDLoc DL(N); 7139 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7140 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7141 DAG.getConstant(1, DL, MaskVT), 7142 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7143 Store->getPointerInfo(), 7144 Store->getOriginalAlign(), 7145 Store->getMemOperand()->getFlags()); 7146 } 7147 } 7148 7149 break; 7150 } 7151 } 7152 7153 return SDValue(); 7154 } 7155 7156 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7157 const SDNode *N, CombineLevel Level) const { 7158 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7159 // materialised in fewer instructions than `(OP _, c1)`: 7160 // 7161 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7162 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7163 SDValue N0 = N->getOperand(0); 7164 EVT Ty = N0.getValueType(); 7165 if (Ty.isScalarInteger() && 7166 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7167 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7168 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7169 if (C1 && C2) { 7170 const APInt &C1Int = C1->getAPIntValue(); 7171 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7172 7173 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7174 // and the combine should happen, to potentially allow further combines 7175 // later. 7176 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7177 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7178 return true; 7179 7180 // We can materialise `c1` in an add immediate, so it's "free", and the 7181 // combine should be prevented. 7182 if (C1Int.getMinSignedBits() <= 64 && 7183 isLegalAddImmediate(C1Int.getSExtValue())) 7184 return false; 7185 7186 // Neither constant will fit into an immediate, so find materialisation 7187 // costs. 7188 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7189 Subtarget.getFeatureBits(), 7190 /*CompressionCost*/true); 7191 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7192 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7193 /*CompressionCost*/true); 7194 7195 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7196 // combine should be prevented. 7197 if (C1Cost < ShiftedC1Cost) 7198 return false; 7199 } 7200 } 7201 return true; 7202 } 7203 7204 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7205 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7206 TargetLoweringOpt &TLO) const { 7207 // Delay this optimization as late as possible. 7208 if (!TLO.LegalOps) 7209 return false; 7210 7211 EVT VT = Op.getValueType(); 7212 if (VT.isVector()) 7213 return false; 7214 7215 // Only handle AND for now. 7216 if (Op.getOpcode() != ISD::AND) 7217 return false; 7218 7219 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7220 if (!C) 7221 return false; 7222 7223 const APInt &Mask = C->getAPIntValue(); 7224 7225 // Clear all non-demanded bits initially. 7226 APInt ShrunkMask = Mask & DemandedBits; 7227 7228 // Try to make a smaller immediate by setting undemanded bits. 7229 7230 APInt ExpandedMask = Mask | ~DemandedBits; 7231 7232 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7233 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7234 }; 7235 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7236 if (NewMask == Mask) 7237 return true; 7238 SDLoc DL(Op); 7239 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7240 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7241 return TLO.CombineTo(Op, NewOp); 7242 }; 7243 7244 // If the shrunk mask fits in sign extended 12 bits, let the target 7245 // independent code apply it. 7246 if (ShrunkMask.isSignedIntN(12)) 7247 return false; 7248 7249 // Preserve (and X, 0xffff) when zext.h is supported. 7250 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7251 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7252 if (IsLegalMask(NewMask)) 7253 return UseMask(NewMask); 7254 } 7255 7256 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7257 if (VT == MVT::i64) { 7258 APInt NewMask = APInt(64, 0xffffffff); 7259 if (IsLegalMask(NewMask)) 7260 return UseMask(NewMask); 7261 } 7262 7263 // For the remaining optimizations, we need to be able to make a negative 7264 // number through a combination of mask and undemanded bits. 7265 if (!ExpandedMask.isNegative()) 7266 return false; 7267 7268 // What is the fewest number of bits we need to represent the negative number. 7269 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7270 7271 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7272 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7273 APInt NewMask = ShrunkMask; 7274 if (MinSignedBits <= 12) 7275 NewMask.setBitsFrom(11); 7276 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7277 NewMask.setBitsFrom(31); 7278 else 7279 return false; 7280 7281 // Sanity check that our new mask is a subset of the demanded mask. 7282 assert(IsLegalMask(NewMask)); 7283 return UseMask(NewMask); 7284 } 7285 7286 static void computeGREV(APInt &Src, unsigned ShAmt) { 7287 ShAmt &= Src.getBitWidth() - 1; 7288 uint64_t x = Src.getZExtValue(); 7289 if (ShAmt & 1) 7290 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7291 if (ShAmt & 2) 7292 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7293 if (ShAmt & 4) 7294 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7295 if (ShAmt & 8) 7296 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7297 if (ShAmt & 16) 7298 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7299 if (ShAmt & 32) 7300 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7301 Src = x; 7302 } 7303 7304 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7305 KnownBits &Known, 7306 const APInt &DemandedElts, 7307 const SelectionDAG &DAG, 7308 unsigned Depth) const { 7309 unsigned BitWidth = Known.getBitWidth(); 7310 unsigned Opc = Op.getOpcode(); 7311 assert((Opc >= ISD::BUILTIN_OP_END || 7312 Opc == ISD::INTRINSIC_WO_CHAIN || 7313 Opc == ISD::INTRINSIC_W_CHAIN || 7314 Opc == ISD::INTRINSIC_VOID) && 7315 "Should use MaskedValueIsZero if you don't know whether Op" 7316 " is a target node!"); 7317 7318 Known.resetAll(); 7319 switch (Opc) { 7320 default: break; 7321 case RISCVISD::SELECT_CC: { 7322 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7323 // If we don't know any bits, early out. 7324 if (Known.isUnknown()) 7325 break; 7326 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7327 7328 // Only known if known in both the LHS and RHS. 7329 Known = KnownBits::commonBits(Known, Known2); 7330 break; 7331 } 7332 case RISCVISD::REMUW: { 7333 KnownBits Known2; 7334 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7335 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7336 // We only care about the lower 32 bits. 7337 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7338 // Restore the original width by sign extending. 7339 Known = Known.sext(BitWidth); 7340 break; 7341 } 7342 case RISCVISD::DIVUW: { 7343 KnownBits Known2; 7344 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7345 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7346 // We only care about the lower 32 bits. 7347 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7348 // Restore the original width by sign extending. 7349 Known = Known.sext(BitWidth); 7350 break; 7351 } 7352 case RISCVISD::CTZW: { 7353 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7354 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7355 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7356 Known.Zero.setBitsFrom(LowBits); 7357 break; 7358 } 7359 case RISCVISD::CLZW: { 7360 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7361 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7362 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7363 Known.Zero.setBitsFrom(LowBits); 7364 break; 7365 } 7366 case RISCVISD::GREV: 7367 case RISCVISD::GREVW: { 7368 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7369 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7370 if (Opc == RISCVISD::GREVW) 7371 Known = Known.trunc(32); 7372 unsigned ShAmt = C->getZExtValue(); 7373 computeGREV(Known.Zero, ShAmt); 7374 computeGREV(Known.One, ShAmt); 7375 if (Opc == RISCVISD::GREVW) 7376 Known = Known.sext(BitWidth); 7377 } 7378 break; 7379 } 7380 case RISCVISD::READ_VLENB: 7381 // We assume VLENB is at least 16 bytes. 7382 Known.Zero.setLowBits(4); 7383 // We assume VLENB is no more than 65536 / 8 bytes. 7384 Known.Zero.setBitsFrom(14); 7385 break; 7386 case ISD::INTRINSIC_W_CHAIN: { 7387 unsigned IntNo = Op.getConstantOperandVal(1); 7388 switch (IntNo) { 7389 default: 7390 // We can't do anything for most intrinsics. 7391 break; 7392 case Intrinsic::riscv_vsetvli: 7393 case Intrinsic::riscv_vsetvlimax: 7394 // Assume that VL output is positive and would fit in an int32_t. 7395 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7396 if (BitWidth >= 32) 7397 Known.Zero.setBitsFrom(31); 7398 break; 7399 } 7400 break; 7401 } 7402 } 7403 } 7404 7405 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7406 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7407 unsigned Depth) const { 7408 switch (Op.getOpcode()) { 7409 default: 7410 break; 7411 case RISCVISD::SELECT_CC: { 7412 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7413 if (Tmp == 1) return 1; // Early out. 7414 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7415 return std::min(Tmp, Tmp2); 7416 } 7417 case RISCVISD::SLLW: 7418 case RISCVISD::SRAW: 7419 case RISCVISD::SRLW: 7420 case RISCVISD::DIVW: 7421 case RISCVISD::DIVUW: 7422 case RISCVISD::REMUW: 7423 case RISCVISD::ROLW: 7424 case RISCVISD::RORW: 7425 case RISCVISD::GREVW: 7426 case RISCVISD::GORCW: 7427 case RISCVISD::FSLW: 7428 case RISCVISD::FSRW: 7429 case RISCVISD::SHFLW: 7430 case RISCVISD::UNSHFLW: 7431 case RISCVISD::BCOMPRESSW: 7432 case RISCVISD::BDECOMPRESSW: 7433 case RISCVISD::FCVT_W_RTZ_RV64: 7434 case RISCVISD::FCVT_WU_RTZ_RV64: 7435 // TODO: As the result is sign-extended, this is conservatively correct. A 7436 // more precise answer could be calculated for SRAW depending on known 7437 // bits in the shift amount. 7438 return 33; 7439 case RISCVISD::SHFL: 7440 case RISCVISD::UNSHFL: { 7441 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7442 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7443 // will stay within the upper 32 bits. If there were more than 32 sign bits 7444 // before there will be at least 33 sign bits after. 7445 if (Op.getValueType() == MVT::i64 && 7446 isa<ConstantSDNode>(Op.getOperand(1)) && 7447 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7448 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7449 if (Tmp > 32) 7450 return 33; 7451 } 7452 break; 7453 } 7454 case RISCVISD::VMV_X_S: 7455 // The number of sign bits of the scalar result is computed by obtaining the 7456 // element type of the input vector operand, subtracting its width from the 7457 // XLEN, and then adding one (sign bit within the element type). If the 7458 // element type is wider than XLen, the least-significant XLEN bits are 7459 // taken. 7460 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7461 return 1; 7462 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7463 } 7464 7465 return 1; 7466 } 7467 7468 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7469 MachineBasicBlock *BB) { 7470 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7471 7472 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7473 // Should the count have wrapped while it was being read, we need to try 7474 // again. 7475 // ... 7476 // read: 7477 // rdcycleh x3 # load high word of cycle 7478 // rdcycle x2 # load low word of cycle 7479 // rdcycleh x4 # load high word of cycle 7480 // bne x3, x4, read # check if high word reads match, otherwise try again 7481 // ... 7482 7483 MachineFunction &MF = *BB->getParent(); 7484 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7485 MachineFunction::iterator It = ++BB->getIterator(); 7486 7487 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7488 MF.insert(It, LoopMBB); 7489 7490 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7491 MF.insert(It, DoneMBB); 7492 7493 // Transfer the remainder of BB and its successor edges to DoneMBB. 7494 DoneMBB->splice(DoneMBB->begin(), BB, 7495 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7496 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7497 7498 BB->addSuccessor(LoopMBB); 7499 7500 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7501 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7502 Register LoReg = MI.getOperand(0).getReg(); 7503 Register HiReg = MI.getOperand(1).getReg(); 7504 DebugLoc DL = MI.getDebugLoc(); 7505 7506 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7507 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7508 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7509 .addReg(RISCV::X0); 7510 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7511 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7512 .addReg(RISCV::X0); 7513 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7514 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7515 .addReg(RISCV::X0); 7516 7517 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7518 .addReg(HiReg) 7519 .addReg(ReadAgainReg) 7520 .addMBB(LoopMBB); 7521 7522 LoopMBB->addSuccessor(LoopMBB); 7523 LoopMBB->addSuccessor(DoneMBB); 7524 7525 MI.eraseFromParent(); 7526 7527 return DoneMBB; 7528 } 7529 7530 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7531 MachineBasicBlock *BB) { 7532 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7533 7534 MachineFunction &MF = *BB->getParent(); 7535 DebugLoc DL = MI.getDebugLoc(); 7536 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7537 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7538 Register LoReg = MI.getOperand(0).getReg(); 7539 Register HiReg = MI.getOperand(1).getReg(); 7540 Register SrcReg = MI.getOperand(2).getReg(); 7541 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7542 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7543 7544 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7545 RI); 7546 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7547 MachineMemOperand *MMOLo = 7548 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7549 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7550 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7551 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7552 .addFrameIndex(FI) 7553 .addImm(0) 7554 .addMemOperand(MMOLo); 7555 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7556 .addFrameIndex(FI) 7557 .addImm(4) 7558 .addMemOperand(MMOHi); 7559 MI.eraseFromParent(); // The pseudo instruction is gone now. 7560 return BB; 7561 } 7562 7563 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7564 MachineBasicBlock *BB) { 7565 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7566 "Unexpected instruction"); 7567 7568 MachineFunction &MF = *BB->getParent(); 7569 DebugLoc DL = MI.getDebugLoc(); 7570 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7571 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7572 Register DstReg = MI.getOperand(0).getReg(); 7573 Register LoReg = MI.getOperand(1).getReg(); 7574 Register HiReg = MI.getOperand(2).getReg(); 7575 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7576 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7577 7578 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7579 MachineMemOperand *MMOLo = 7580 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7581 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7582 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7583 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7584 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7585 .addFrameIndex(FI) 7586 .addImm(0) 7587 .addMemOperand(MMOLo); 7588 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7589 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7590 .addFrameIndex(FI) 7591 .addImm(4) 7592 .addMemOperand(MMOHi); 7593 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7594 MI.eraseFromParent(); // The pseudo instruction is gone now. 7595 return BB; 7596 } 7597 7598 static bool isSelectPseudo(MachineInstr &MI) { 7599 switch (MI.getOpcode()) { 7600 default: 7601 return false; 7602 case RISCV::Select_GPR_Using_CC_GPR: 7603 case RISCV::Select_FPR16_Using_CC_GPR: 7604 case RISCV::Select_FPR32_Using_CC_GPR: 7605 case RISCV::Select_FPR64_Using_CC_GPR: 7606 return true; 7607 } 7608 } 7609 7610 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7611 MachineBasicBlock *BB, 7612 const RISCVSubtarget &Subtarget) { 7613 // To "insert" Select_* instructions, we actually have to insert the triangle 7614 // control-flow pattern. The incoming instructions know the destination vreg 7615 // to set, the condition code register to branch on, the true/false values to 7616 // select between, and the condcode to use to select the appropriate branch. 7617 // 7618 // We produce the following control flow: 7619 // HeadMBB 7620 // | \ 7621 // | IfFalseMBB 7622 // | / 7623 // TailMBB 7624 // 7625 // When we find a sequence of selects we attempt to optimize their emission 7626 // by sharing the control flow. Currently we only handle cases where we have 7627 // multiple selects with the exact same condition (same LHS, RHS and CC). 7628 // The selects may be interleaved with other instructions if the other 7629 // instructions meet some requirements we deem safe: 7630 // - They are debug instructions. Otherwise, 7631 // - They do not have side-effects, do not access memory and their inputs do 7632 // not depend on the results of the select pseudo-instructions. 7633 // The TrueV/FalseV operands of the selects cannot depend on the result of 7634 // previous selects in the sequence. 7635 // These conditions could be further relaxed. See the X86 target for a 7636 // related approach and more information. 7637 Register LHS = MI.getOperand(1).getReg(); 7638 Register RHS = MI.getOperand(2).getReg(); 7639 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 7640 7641 SmallVector<MachineInstr *, 4> SelectDebugValues; 7642 SmallSet<Register, 4> SelectDests; 7643 SelectDests.insert(MI.getOperand(0).getReg()); 7644 7645 MachineInstr *LastSelectPseudo = &MI; 7646 7647 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 7648 SequenceMBBI != E; ++SequenceMBBI) { 7649 if (SequenceMBBI->isDebugInstr()) 7650 continue; 7651 else if (isSelectPseudo(*SequenceMBBI)) { 7652 if (SequenceMBBI->getOperand(1).getReg() != LHS || 7653 SequenceMBBI->getOperand(2).getReg() != RHS || 7654 SequenceMBBI->getOperand(3).getImm() != CC || 7655 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 7656 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 7657 break; 7658 LastSelectPseudo = &*SequenceMBBI; 7659 SequenceMBBI->collectDebugValues(SelectDebugValues); 7660 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 7661 } else { 7662 if (SequenceMBBI->hasUnmodeledSideEffects() || 7663 SequenceMBBI->mayLoadOrStore()) 7664 break; 7665 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 7666 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 7667 })) 7668 break; 7669 } 7670 } 7671 7672 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 7673 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7674 DebugLoc DL = MI.getDebugLoc(); 7675 MachineFunction::iterator I = ++BB->getIterator(); 7676 7677 MachineBasicBlock *HeadMBB = BB; 7678 MachineFunction *F = BB->getParent(); 7679 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 7680 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 7681 7682 F->insert(I, IfFalseMBB); 7683 F->insert(I, TailMBB); 7684 7685 // Transfer debug instructions associated with the selects to TailMBB. 7686 for (MachineInstr *DebugInstr : SelectDebugValues) { 7687 TailMBB->push_back(DebugInstr->removeFromParent()); 7688 } 7689 7690 // Move all instructions after the sequence to TailMBB. 7691 TailMBB->splice(TailMBB->end(), HeadMBB, 7692 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 7693 // Update machine-CFG edges by transferring all successors of the current 7694 // block to the new block which will contain the Phi nodes for the selects. 7695 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 7696 // Set the successors for HeadMBB. 7697 HeadMBB->addSuccessor(IfFalseMBB); 7698 HeadMBB->addSuccessor(TailMBB); 7699 7700 // Insert appropriate branch. 7701 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 7702 .addReg(LHS) 7703 .addReg(RHS) 7704 .addMBB(TailMBB); 7705 7706 // IfFalseMBB just falls through to TailMBB. 7707 IfFalseMBB->addSuccessor(TailMBB); 7708 7709 // Create PHIs for all of the select pseudo-instructions. 7710 auto SelectMBBI = MI.getIterator(); 7711 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 7712 auto InsertionPoint = TailMBB->begin(); 7713 while (SelectMBBI != SelectEnd) { 7714 auto Next = std::next(SelectMBBI); 7715 if (isSelectPseudo(*SelectMBBI)) { 7716 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 7717 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 7718 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 7719 .addReg(SelectMBBI->getOperand(4).getReg()) 7720 .addMBB(HeadMBB) 7721 .addReg(SelectMBBI->getOperand(5).getReg()) 7722 .addMBB(IfFalseMBB); 7723 SelectMBBI->eraseFromParent(); 7724 } 7725 SelectMBBI = Next; 7726 } 7727 7728 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 7729 return TailMBB; 7730 } 7731 7732 MachineBasicBlock * 7733 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 7734 MachineBasicBlock *BB) const { 7735 switch (MI.getOpcode()) { 7736 default: 7737 llvm_unreachable("Unexpected instr type to insert"); 7738 case RISCV::ReadCycleWide: 7739 assert(!Subtarget.is64Bit() && 7740 "ReadCycleWrite is only to be used on riscv32"); 7741 return emitReadCycleWidePseudo(MI, BB); 7742 case RISCV::Select_GPR_Using_CC_GPR: 7743 case RISCV::Select_FPR16_Using_CC_GPR: 7744 case RISCV::Select_FPR32_Using_CC_GPR: 7745 case RISCV::Select_FPR64_Using_CC_GPR: 7746 return emitSelectPseudo(MI, BB, Subtarget); 7747 case RISCV::BuildPairF64Pseudo: 7748 return emitBuildPairF64Pseudo(MI, BB); 7749 case RISCV::SplitF64Pseudo: 7750 return emitSplitF64Pseudo(MI, BB); 7751 } 7752 } 7753 7754 // Calling Convention Implementation. 7755 // The expectations for frontend ABI lowering vary from target to target. 7756 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 7757 // details, but this is a longer term goal. For now, we simply try to keep the 7758 // role of the frontend as simple and well-defined as possible. The rules can 7759 // be summarised as: 7760 // * Never split up large scalar arguments. We handle them here. 7761 // * If a hardfloat calling convention is being used, and the struct may be 7762 // passed in a pair of registers (fp+fp, int+fp), and both registers are 7763 // available, then pass as two separate arguments. If either the GPRs or FPRs 7764 // are exhausted, then pass according to the rule below. 7765 // * If a struct could never be passed in registers or directly in a stack 7766 // slot (as it is larger than 2*XLEN and the floating point rules don't 7767 // apply), then pass it using a pointer with the byval attribute. 7768 // * If a struct is less than 2*XLEN, then coerce to either a two-element 7769 // word-sized array or a 2*XLEN scalar (depending on alignment). 7770 // * The frontend can determine whether a struct is returned by reference or 7771 // not based on its size and fields. If it will be returned by reference, the 7772 // frontend must modify the prototype so a pointer with the sret annotation is 7773 // passed as the first argument. This is not necessary for large scalar 7774 // returns. 7775 // * Struct return values and varargs should be coerced to structs containing 7776 // register-size fields in the same situations they would be for fixed 7777 // arguments. 7778 7779 static const MCPhysReg ArgGPRs[] = { 7780 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 7781 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 7782 }; 7783 static const MCPhysReg ArgFPR16s[] = { 7784 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 7785 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 7786 }; 7787 static const MCPhysReg ArgFPR32s[] = { 7788 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 7789 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 7790 }; 7791 static const MCPhysReg ArgFPR64s[] = { 7792 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 7793 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 7794 }; 7795 // This is an interim calling convention and it may be changed in the future. 7796 static const MCPhysReg ArgVRs[] = { 7797 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 7798 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 7799 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 7800 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 7801 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 7802 RISCV::V20M2, RISCV::V22M2}; 7803 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 7804 RISCV::V20M4}; 7805 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 7806 7807 // Pass a 2*XLEN argument that has been split into two XLEN values through 7808 // registers or the stack as necessary. 7809 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 7810 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 7811 MVT ValVT2, MVT LocVT2, 7812 ISD::ArgFlagsTy ArgFlags2) { 7813 unsigned XLenInBytes = XLen / 8; 7814 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7815 // At least one half can be passed via register. 7816 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 7817 VA1.getLocVT(), CCValAssign::Full)); 7818 } else { 7819 // Both halves must be passed on the stack, with proper alignment. 7820 Align StackAlign = 7821 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 7822 State.addLoc( 7823 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 7824 State.AllocateStack(XLenInBytes, StackAlign), 7825 VA1.getLocVT(), CCValAssign::Full)); 7826 State.addLoc(CCValAssign::getMem( 7827 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7828 LocVT2, CCValAssign::Full)); 7829 return false; 7830 } 7831 7832 if (Register Reg = State.AllocateReg(ArgGPRs)) { 7833 // The second half can also be passed via register. 7834 State.addLoc( 7835 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 7836 } else { 7837 // The second half is passed via the stack, without additional alignment. 7838 State.addLoc(CCValAssign::getMem( 7839 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 7840 LocVT2, CCValAssign::Full)); 7841 } 7842 7843 return false; 7844 } 7845 7846 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 7847 Optional<unsigned> FirstMaskArgument, 7848 CCState &State, const RISCVTargetLowering &TLI) { 7849 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 7850 if (RC == &RISCV::VRRegClass) { 7851 // Assign the first mask argument to V0. 7852 // This is an interim calling convention and it may be changed in the 7853 // future. 7854 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 7855 return State.AllocateReg(RISCV::V0); 7856 return State.AllocateReg(ArgVRs); 7857 } 7858 if (RC == &RISCV::VRM2RegClass) 7859 return State.AllocateReg(ArgVRM2s); 7860 if (RC == &RISCV::VRM4RegClass) 7861 return State.AllocateReg(ArgVRM4s); 7862 if (RC == &RISCV::VRM8RegClass) 7863 return State.AllocateReg(ArgVRM8s); 7864 llvm_unreachable("Unhandled register class for ValueType"); 7865 } 7866 7867 // Implements the RISC-V calling convention. Returns true upon failure. 7868 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 7869 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 7870 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 7871 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 7872 Optional<unsigned> FirstMaskArgument) { 7873 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 7874 assert(XLen == 32 || XLen == 64); 7875 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 7876 7877 // Any return value split in to more than two values can't be returned 7878 // directly. Vectors are returned via the available vector registers. 7879 if (!LocVT.isVector() && IsRet && ValNo > 1) 7880 return true; 7881 7882 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 7883 // variadic argument, or if no F16/F32 argument registers are available. 7884 bool UseGPRForF16_F32 = true; 7885 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 7886 // variadic argument, or if no F64 argument registers are available. 7887 bool UseGPRForF64 = true; 7888 7889 switch (ABI) { 7890 default: 7891 llvm_unreachable("Unexpected ABI"); 7892 case RISCVABI::ABI_ILP32: 7893 case RISCVABI::ABI_LP64: 7894 break; 7895 case RISCVABI::ABI_ILP32F: 7896 case RISCVABI::ABI_LP64F: 7897 UseGPRForF16_F32 = !IsFixed; 7898 break; 7899 case RISCVABI::ABI_ILP32D: 7900 case RISCVABI::ABI_LP64D: 7901 UseGPRForF16_F32 = !IsFixed; 7902 UseGPRForF64 = !IsFixed; 7903 break; 7904 } 7905 7906 // FPR16, FPR32, and FPR64 alias each other. 7907 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 7908 UseGPRForF16_F32 = true; 7909 UseGPRForF64 = true; 7910 } 7911 7912 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 7913 // similar local variables rather than directly checking against the target 7914 // ABI. 7915 7916 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 7917 LocVT = XLenVT; 7918 LocInfo = CCValAssign::BCvt; 7919 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 7920 LocVT = MVT::i64; 7921 LocInfo = CCValAssign::BCvt; 7922 } 7923 7924 // If this is a variadic argument, the RISC-V calling convention requires 7925 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 7926 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 7927 // be used regardless of whether the original argument was split during 7928 // legalisation or not. The argument will not be passed by registers if the 7929 // original type is larger than 2*XLEN, so the register alignment rule does 7930 // not apply. 7931 unsigned TwoXLenInBytes = (2 * XLen) / 8; 7932 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 7933 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 7934 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 7935 // Skip 'odd' register if necessary. 7936 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 7937 State.AllocateReg(ArgGPRs); 7938 } 7939 7940 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 7941 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 7942 State.getPendingArgFlags(); 7943 7944 assert(PendingLocs.size() == PendingArgFlags.size() && 7945 "PendingLocs and PendingArgFlags out of sync"); 7946 7947 // Handle passing f64 on RV32D with a soft float ABI or when floating point 7948 // registers are exhausted. 7949 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 7950 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 7951 "Can't lower f64 if it is split"); 7952 // Depending on available argument GPRS, f64 may be passed in a pair of 7953 // GPRs, split between a GPR and the stack, or passed completely on the 7954 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 7955 // cases. 7956 Register Reg = State.AllocateReg(ArgGPRs); 7957 LocVT = MVT::i32; 7958 if (!Reg) { 7959 unsigned StackOffset = State.AllocateStack(8, Align(8)); 7960 State.addLoc( 7961 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 7962 return false; 7963 } 7964 if (!State.AllocateReg(ArgGPRs)) 7965 State.AllocateStack(4, Align(4)); 7966 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 7967 return false; 7968 } 7969 7970 // Fixed-length vectors are located in the corresponding scalable-vector 7971 // container types. 7972 if (ValVT.isFixedLengthVector()) 7973 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 7974 7975 // Split arguments might be passed indirectly, so keep track of the pending 7976 // values. Split vectors are passed via a mix of registers and indirectly, so 7977 // treat them as we would any other argument. 7978 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 7979 LocVT = XLenVT; 7980 LocInfo = CCValAssign::Indirect; 7981 PendingLocs.push_back( 7982 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 7983 PendingArgFlags.push_back(ArgFlags); 7984 if (!ArgFlags.isSplitEnd()) { 7985 return false; 7986 } 7987 } 7988 7989 // If the split argument only had two elements, it should be passed directly 7990 // in registers or on the stack. 7991 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 7992 PendingLocs.size() <= 2) { 7993 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 7994 // Apply the normal calling convention rules to the first half of the 7995 // split argument. 7996 CCValAssign VA = PendingLocs[0]; 7997 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 7998 PendingLocs.clear(); 7999 PendingArgFlags.clear(); 8000 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8001 ArgFlags); 8002 } 8003 8004 // Allocate to a register if possible, or else a stack slot. 8005 Register Reg; 8006 unsigned StoreSizeBytes = XLen / 8; 8007 Align StackAlign = Align(XLen / 8); 8008 8009 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8010 Reg = State.AllocateReg(ArgFPR16s); 8011 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8012 Reg = State.AllocateReg(ArgFPR32s); 8013 else if (ValVT == MVT::f64 && !UseGPRForF64) 8014 Reg = State.AllocateReg(ArgFPR64s); 8015 else if (ValVT.isVector()) { 8016 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8017 if (!Reg) { 8018 // For return values, the vector must be passed fully via registers or 8019 // via the stack. 8020 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8021 // but we're using all of them. 8022 if (IsRet) 8023 return true; 8024 // Try using a GPR to pass the address 8025 if ((Reg = State.AllocateReg(ArgGPRs))) { 8026 LocVT = XLenVT; 8027 LocInfo = CCValAssign::Indirect; 8028 } else if (ValVT.isScalableVector()) { 8029 report_fatal_error("Unable to pass scalable vector types on the stack"); 8030 } else { 8031 // Pass fixed-length vectors on the stack. 8032 LocVT = ValVT; 8033 StoreSizeBytes = ValVT.getStoreSize(); 8034 // Align vectors to their element sizes, being careful for vXi1 8035 // vectors. 8036 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8037 } 8038 } 8039 } else { 8040 Reg = State.AllocateReg(ArgGPRs); 8041 } 8042 8043 unsigned StackOffset = 8044 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8045 8046 // If we reach this point and PendingLocs is non-empty, we must be at the 8047 // end of a split argument that must be passed indirectly. 8048 if (!PendingLocs.empty()) { 8049 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8050 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8051 8052 for (auto &It : PendingLocs) { 8053 if (Reg) 8054 It.convertToReg(Reg); 8055 else 8056 It.convertToMem(StackOffset); 8057 State.addLoc(It); 8058 } 8059 PendingLocs.clear(); 8060 PendingArgFlags.clear(); 8061 return false; 8062 } 8063 8064 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8065 (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) && 8066 "Expected an XLenVT or vector types at this stage"); 8067 8068 if (Reg) { 8069 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8070 return false; 8071 } 8072 8073 // When a floating-point value is passed on the stack, no bit-conversion is 8074 // needed. 8075 if (ValVT.isFloatingPoint()) { 8076 LocVT = ValVT; 8077 LocInfo = CCValAssign::Full; 8078 } 8079 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8080 return false; 8081 } 8082 8083 template <typename ArgTy> 8084 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8085 for (const auto &ArgIdx : enumerate(Args)) { 8086 MVT ArgVT = ArgIdx.value().VT; 8087 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8088 return ArgIdx.index(); 8089 } 8090 return None; 8091 } 8092 8093 void RISCVTargetLowering::analyzeInputArgs( 8094 MachineFunction &MF, CCState &CCInfo, 8095 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8096 RISCVCCAssignFn Fn) const { 8097 unsigned NumArgs = Ins.size(); 8098 FunctionType *FType = MF.getFunction().getFunctionType(); 8099 8100 Optional<unsigned> FirstMaskArgument; 8101 if (Subtarget.hasStdExtV()) 8102 FirstMaskArgument = preAssignMask(Ins); 8103 8104 for (unsigned i = 0; i != NumArgs; ++i) { 8105 MVT ArgVT = Ins[i].VT; 8106 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8107 8108 Type *ArgTy = nullptr; 8109 if (IsRet) 8110 ArgTy = FType->getReturnType(); 8111 else if (Ins[i].isOrigArg()) 8112 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8113 8114 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8115 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8116 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8117 FirstMaskArgument)) { 8118 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8119 << EVT(ArgVT).getEVTString() << '\n'); 8120 llvm_unreachable(nullptr); 8121 } 8122 } 8123 } 8124 8125 void RISCVTargetLowering::analyzeOutputArgs( 8126 MachineFunction &MF, CCState &CCInfo, 8127 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8128 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8129 unsigned NumArgs = Outs.size(); 8130 8131 Optional<unsigned> FirstMaskArgument; 8132 if (Subtarget.hasStdExtV()) 8133 FirstMaskArgument = preAssignMask(Outs); 8134 8135 for (unsigned i = 0; i != NumArgs; i++) { 8136 MVT ArgVT = Outs[i].VT; 8137 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8138 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8139 8140 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8141 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8142 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8143 FirstMaskArgument)) { 8144 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8145 << EVT(ArgVT).getEVTString() << "\n"); 8146 llvm_unreachable(nullptr); 8147 } 8148 } 8149 } 8150 8151 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8152 // values. 8153 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8154 const CCValAssign &VA, const SDLoc &DL, 8155 const RISCVSubtarget &Subtarget) { 8156 switch (VA.getLocInfo()) { 8157 default: 8158 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8159 case CCValAssign::Full: 8160 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8161 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8162 break; 8163 case CCValAssign::BCvt: 8164 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8165 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8166 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8167 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8168 else 8169 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8170 break; 8171 } 8172 return Val; 8173 } 8174 8175 // The caller is responsible for loading the full value if the argument is 8176 // passed with CCValAssign::Indirect. 8177 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8178 const CCValAssign &VA, const SDLoc &DL, 8179 const RISCVTargetLowering &TLI) { 8180 MachineFunction &MF = DAG.getMachineFunction(); 8181 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8182 EVT LocVT = VA.getLocVT(); 8183 SDValue Val; 8184 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8185 Register VReg = RegInfo.createVirtualRegister(RC); 8186 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8187 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8188 8189 if (VA.getLocInfo() == CCValAssign::Indirect) 8190 return Val; 8191 8192 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8193 } 8194 8195 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8196 const CCValAssign &VA, const SDLoc &DL, 8197 const RISCVSubtarget &Subtarget) { 8198 EVT LocVT = VA.getLocVT(); 8199 8200 switch (VA.getLocInfo()) { 8201 default: 8202 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8203 case CCValAssign::Full: 8204 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8205 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8206 break; 8207 case CCValAssign::BCvt: 8208 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8209 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8210 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8211 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8212 else 8213 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8214 break; 8215 } 8216 return Val; 8217 } 8218 8219 // The caller is responsible for loading the full value if the argument is 8220 // passed with CCValAssign::Indirect. 8221 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8222 const CCValAssign &VA, const SDLoc &DL) { 8223 MachineFunction &MF = DAG.getMachineFunction(); 8224 MachineFrameInfo &MFI = MF.getFrameInfo(); 8225 EVT LocVT = VA.getLocVT(); 8226 EVT ValVT = VA.getValVT(); 8227 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8228 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8229 /*Immutable=*/true); 8230 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8231 SDValue Val; 8232 8233 ISD::LoadExtType ExtType; 8234 switch (VA.getLocInfo()) { 8235 default: 8236 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8237 case CCValAssign::Full: 8238 case CCValAssign::Indirect: 8239 case CCValAssign::BCvt: 8240 ExtType = ISD::NON_EXTLOAD; 8241 break; 8242 } 8243 Val = DAG.getExtLoad( 8244 ExtType, DL, LocVT, Chain, FIN, 8245 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8246 return Val; 8247 } 8248 8249 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8250 const CCValAssign &VA, const SDLoc &DL) { 8251 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8252 "Unexpected VA"); 8253 MachineFunction &MF = DAG.getMachineFunction(); 8254 MachineFrameInfo &MFI = MF.getFrameInfo(); 8255 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8256 8257 if (VA.isMemLoc()) { 8258 // f64 is passed on the stack. 8259 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8260 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8261 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8262 MachinePointerInfo::getFixedStack(MF, FI)); 8263 } 8264 8265 assert(VA.isRegLoc() && "Expected register VA assignment"); 8266 8267 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8268 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8269 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8270 SDValue Hi; 8271 if (VA.getLocReg() == RISCV::X17) { 8272 // Second half of f64 is passed on the stack. 8273 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8274 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8275 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8276 MachinePointerInfo::getFixedStack(MF, FI)); 8277 } else { 8278 // Second half of f64 is passed in another GPR. 8279 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8280 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8281 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8282 } 8283 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8284 } 8285 8286 // FastCC has less than 1% performance improvement for some particular 8287 // benchmark. But theoretically, it may has benenfit for some cases. 8288 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8289 unsigned ValNo, MVT ValVT, MVT LocVT, 8290 CCValAssign::LocInfo LocInfo, 8291 ISD::ArgFlagsTy ArgFlags, CCState &State, 8292 bool IsFixed, bool IsRet, Type *OrigTy, 8293 const RISCVTargetLowering &TLI, 8294 Optional<unsigned> FirstMaskArgument) { 8295 8296 // X5 and X6 might be used for save-restore libcall. 8297 static const MCPhysReg GPRList[] = { 8298 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8299 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8300 RISCV::X29, RISCV::X30, RISCV::X31}; 8301 8302 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8303 if (unsigned Reg = State.AllocateReg(GPRList)) { 8304 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8305 return false; 8306 } 8307 } 8308 8309 if (LocVT == MVT::f16) { 8310 static const MCPhysReg FPR16List[] = { 8311 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8312 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8313 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8314 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8315 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8316 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8317 return false; 8318 } 8319 } 8320 8321 if (LocVT == MVT::f32) { 8322 static const MCPhysReg FPR32List[] = { 8323 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8324 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8325 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8326 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8327 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8328 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8329 return false; 8330 } 8331 } 8332 8333 if (LocVT == MVT::f64) { 8334 static const MCPhysReg FPR64List[] = { 8335 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8336 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8337 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8338 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8339 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8340 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8341 return false; 8342 } 8343 } 8344 8345 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8346 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8347 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8348 return false; 8349 } 8350 8351 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8352 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8353 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8354 return false; 8355 } 8356 8357 if (LocVT.isVector()) { 8358 if (unsigned Reg = 8359 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8360 // Fixed-length vectors are located in the corresponding scalable-vector 8361 // container types. 8362 if (ValVT.isFixedLengthVector()) 8363 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8364 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8365 } else { 8366 // Try and pass the address via a "fast" GPR. 8367 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8368 LocInfo = CCValAssign::Indirect; 8369 LocVT = TLI.getSubtarget().getXLenVT(); 8370 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8371 } else if (ValVT.isFixedLengthVector()) { 8372 auto StackAlign = 8373 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8374 unsigned StackOffset = 8375 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8376 State.addLoc( 8377 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8378 } else { 8379 // Can't pass scalable vectors on the stack. 8380 return true; 8381 } 8382 } 8383 8384 return false; 8385 } 8386 8387 return true; // CC didn't match. 8388 } 8389 8390 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8391 CCValAssign::LocInfo LocInfo, 8392 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8393 8394 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8395 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8396 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8397 static const MCPhysReg GPRList[] = { 8398 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8399 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8400 if (unsigned Reg = State.AllocateReg(GPRList)) { 8401 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8402 return false; 8403 } 8404 } 8405 8406 if (LocVT == MVT::f32) { 8407 // Pass in STG registers: F1, ..., F6 8408 // fs0 ... fs5 8409 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8410 RISCV::F18_F, RISCV::F19_F, 8411 RISCV::F20_F, RISCV::F21_F}; 8412 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8413 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8414 return false; 8415 } 8416 } 8417 8418 if (LocVT == MVT::f64) { 8419 // Pass in STG registers: D1, ..., D6 8420 // fs6 ... fs11 8421 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8422 RISCV::F24_D, RISCV::F25_D, 8423 RISCV::F26_D, RISCV::F27_D}; 8424 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8425 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8426 return false; 8427 } 8428 } 8429 8430 report_fatal_error("No registers left in GHC calling convention"); 8431 return true; 8432 } 8433 8434 // Transform physical registers into virtual registers. 8435 SDValue RISCVTargetLowering::LowerFormalArguments( 8436 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8437 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8438 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8439 8440 MachineFunction &MF = DAG.getMachineFunction(); 8441 8442 switch (CallConv) { 8443 default: 8444 report_fatal_error("Unsupported calling convention"); 8445 case CallingConv::C: 8446 case CallingConv::Fast: 8447 break; 8448 case CallingConv::GHC: 8449 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8450 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8451 report_fatal_error( 8452 "GHC calling convention requires the F and D instruction set extensions"); 8453 } 8454 8455 const Function &Func = MF.getFunction(); 8456 if (Func.hasFnAttribute("interrupt")) { 8457 if (!Func.arg_empty()) 8458 report_fatal_error( 8459 "Functions with the interrupt attribute cannot have arguments!"); 8460 8461 StringRef Kind = 8462 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8463 8464 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8465 report_fatal_error( 8466 "Function interrupt attribute argument not supported!"); 8467 } 8468 8469 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8470 MVT XLenVT = Subtarget.getXLenVT(); 8471 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8472 // Used with vargs to acumulate store chains. 8473 std::vector<SDValue> OutChains; 8474 8475 // Assign locations to all of the incoming arguments. 8476 SmallVector<CCValAssign, 16> ArgLocs; 8477 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8478 8479 if (CallConv == CallingConv::GHC) 8480 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8481 else 8482 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8483 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8484 : CC_RISCV); 8485 8486 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8487 CCValAssign &VA = ArgLocs[i]; 8488 SDValue ArgValue; 8489 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8490 // case. 8491 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8492 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8493 else if (VA.isRegLoc()) 8494 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8495 else 8496 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8497 8498 if (VA.getLocInfo() == CCValAssign::Indirect) { 8499 // If the original argument was split and passed by reference (e.g. i128 8500 // on RV32), we need to load all parts of it here (using the same 8501 // address). Vectors may be partly split to registers and partly to the 8502 // stack, in which case the base address is partly offset and subsequent 8503 // stores are relative to that. 8504 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8505 MachinePointerInfo())); 8506 unsigned ArgIndex = Ins[i].OrigArgIndex; 8507 unsigned ArgPartOffset = Ins[i].PartOffset; 8508 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8509 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8510 CCValAssign &PartVA = ArgLocs[i + 1]; 8511 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8512 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8513 if (PartVA.getValVT().isScalableVector()) 8514 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8515 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8516 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8517 MachinePointerInfo())); 8518 ++i; 8519 } 8520 continue; 8521 } 8522 InVals.push_back(ArgValue); 8523 } 8524 8525 if (IsVarArg) { 8526 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8527 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8528 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8529 MachineFrameInfo &MFI = MF.getFrameInfo(); 8530 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8531 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8532 8533 // Offset of the first variable argument from stack pointer, and size of 8534 // the vararg save area. For now, the varargs save area is either zero or 8535 // large enough to hold a0-a7. 8536 int VaArgOffset, VarArgsSaveSize; 8537 8538 // If all registers are allocated, then all varargs must be passed on the 8539 // stack and we don't need to save any argregs. 8540 if (ArgRegs.size() == Idx) { 8541 VaArgOffset = CCInfo.getNextStackOffset(); 8542 VarArgsSaveSize = 0; 8543 } else { 8544 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8545 VaArgOffset = -VarArgsSaveSize; 8546 } 8547 8548 // Record the frame index of the first variable argument 8549 // which is a value necessary to VASTART. 8550 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8551 RVFI->setVarArgsFrameIndex(FI); 8552 8553 // If saving an odd number of registers then create an extra stack slot to 8554 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8555 // offsets to even-numbered registered remain 2*XLEN-aligned. 8556 if (Idx % 2) { 8557 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8558 VarArgsSaveSize += XLenInBytes; 8559 } 8560 8561 // Copy the integer registers that may have been used for passing varargs 8562 // to the vararg save area. 8563 for (unsigned I = Idx; I < ArgRegs.size(); 8564 ++I, VaArgOffset += XLenInBytes) { 8565 const Register Reg = RegInfo.createVirtualRegister(RC); 8566 RegInfo.addLiveIn(ArgRegs[I], Reg); 8567 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8568 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8569 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8570 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8571 MachinePointerInfo::getFixedStack(MF, FI)); 8572 cast<StoreSDNode>(Store.getNode()) 8573 ->getMemOperand() 8574 ->setValue((Value *)nullptr); 8575 OutChains.push_back(Store); 8576 } 8577 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8578 } 8579 8580 // All stores are grouped in one node to allow the matching between 8581 // the size of Ins and InVals. This only happens for vararg functions. 8582 if (!OutChains.empty()) { 8583 OutChains.push_back(Chain); 8584 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8585 } 8586 8587 return Chain; 8588 } 8589 8590 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8591 /// for tail call optimization. 8592 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8593 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8594 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8595 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8596 8597 auto &Callee = CLI.Callee; 8598 auto CalleeCC = CLI.CallConv; 8599 auto &Outs = CLI.Outs; 8600 auto &Caller = MF.getFunction(); 8601 auto CallerCC = Caller.getCallingConv(); 8602 8603 // Exception-handling functions need a special set of instructions to 8604 // indicate a return to the hardware. Tail-calling another function would 8605 // probably break this. 8606 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8607 // should be expanded as new function attributes are introduced. 8608 if (Caller.hasFnAttribute("interrupt")) 8609 return false; 8610 8611 // Do not tail call opt if the stack is used to pass parameters. 8612 if (CCInfo.getNextStackOffset() != 0) 8613 return false; 8614 8615 // Do not tail call opt if any parameters need to be passed indirectly. 8616 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 8617 // passed indirectly. So the address of the value will be passed in a 8618 // register, or if not available, then the address is put on the stack. In 8619 // order to pass indirectly, space on the stack often needs to be allocated 8620 // in order to store the value. In this case the CCInfo.getNextStackOffset() 8621 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 8622 // are passed CCValAssign::Indirect. 8623 for (auto &VA : ArgLocs) 8624 if (VA.getLocInfo() == CCValAssign::Indirect) 8625 return false; 8626 8627 // Do not tail call opt if either caller or callee uses struct return 8628 // semantics. 8629 auto IsCallerStructRet = Caller.hasStructRetAttr(); 8630 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 8631 if (IsCallerStructRet || IsCalleeStructRet) 8632 return false; 8633 8634 // Externally-defined functions with weak linkage should not be 8635 // tail-called. The behaviour of branch instructions in this situation (as 8636 // used for tail calls) is implementation-defined, so we cannot rely on the 8637 // linker replacing the tail call with a return. 8638 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 8639 const GlobalValue *GV = G->getGlobal(); 8640 if (GV->hasExternalWeakLinkage()) 8641 return false; 8642 } 8643 8644 // The callee has to preserve all registers the caller needs to preserve. 8645 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8646 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 8647 if (CalleeCC != CallerCC) { 8648 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 8649 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 8650 return false; 8651 } 8652 8653 // Byval parameters hand the function a pointer directly into the stack area 8654 // we want to reuse during a tail call. Working around this *is* possible 8655 // but less efficient and uglier in LowerCall. 8656 for (auto &Arg : Outs) 8657 if (Arg.Flags.isByVal()) 8658 return false; 8659 8660 return true; 8661 } 8662 8663 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 8664 return DAG.getDataLayout().getPrefTypeAlign( 8665 VT.getTypeForEVT(*DAG.getContext())); 8666 } 8667 8668 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 8669 // and output parameter nodes. 8670 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 8671 SmallVectorImpl<SDValue> &InVals) const { 8672 SelectionDAG &DAG = CLI.DAG; 8673 SDLoc &DL = CLI.DL; 8674 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 8675 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 8676 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 8677 SDValue Chain = CLI.Chain; 8678 SDValue Callee = CLI.Callee; 8679 bool &IsTailCall = CLI.IsTailCall; 8680 CallingConv::ID CallConv = CLI.CallConv; 8681 bool IsVarArg = CLI.IsVarArg; 8682 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8683 MVT XLenVT = Subtarget.getXLenVT(); 8684 8685 MachineFunction &MF = DAG.getMachineFunction(); 8686 8687 // Analyze the operands of the call, assigning locations to each operand. 8688 SmallVector<CCValAssign, 16> ArgLocs; 8689 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8690 8691 if (CallConv == CallingConv::GHC) 8692 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 8693 else 8694 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 8695 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8696 : CC_RISCV); 8697 8698 // Check if it's really possible to do a tail call. 8699 if (IsTailCall) 8700 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 8701 8702 if (IsTailCall) 8703 ++NumTailCalls; 8704 else if (CLI.CB && CLI.CB->isMustTailCall()) 8705 report_fatal_error("failed to perform tail call elimination on a call " 8706 "site marked musttail"); 8707 8708 // Get a count of how many bytes are to be pushed on the stack. 8709 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 8710 8711 // Create local copies for byval args 8712 SmallVector<SDValue, 8> ByValArgs; 8713 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8714 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8715 if (!Flags.isByVal()) 8716 continue; 8717 8718 SDValue Arg = OutVals[i]; 8719 unsigned Size = Flags.getByValSize(); 8720 Align Alignment = Flags.getNonZeroByValAlign(); 8721 8722 int FI = 8723 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 8724 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8725 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 8726 8727 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 8728 /*IsVolatile=*/false, 8729 /*AlwaysInline=*/false, IsTailCall, 8730 MachinePointerInfo(), MachinePointerInfo()); 8731 ByValArgs.push_back(FIPtr); 8732 } 8733 8734 if (!IsTailCall) 8735 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 8736 8737 // Copy argument values to their designated locations. 8738 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 8739 SmallVector<SDValue, 8> MemOpChains; 8740 SDValue StackPtr; 8741 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 8742 CCValAssign &VA = ArgLocs[i]; 8743 SDValue ArgValue = OutVals[i]; 8744 ISD::ArgFlagsTy Flags = Outs[i].Flags; 8745 8746 // Handle passing f64 on RV32D with a soft float ABI as a special case. 8747 bool IsF64OnRV32DSoftABI = 8748 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 8749 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 8750 SDValue SplitF64 = DAG.getNode( 8751 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 8752 SDValue Lo = SplitF64.getValue(0); 8753 SDValue Hi = SplitF64.getValue(1); 8754 8755 Register RegLo = VA.getLocReg(); 8756 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 8757 8758 if (RegLo == RISCV::X17) { 8759 // Second half of f64 is passed on the stack. 8760 // Work out the address of the stack slot. 8761 if (!StackPtr.getNode()) 8762 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8763 // Emit the store. 8764 MemOpChains.push_back( 8765 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 8766 } else { 8767 // Second half of f64 is passed in another GPR. 8768 assert(RegLo < RISCV::X31 && "Invalid register pair"); 8769 Register RegHigh = RegLo + 1; 8770 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 8771 } 8772 continue; 8773 } 8774 8775 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 8776 // as any other MemLoc. 8777 8778 // Promote the value if needed. 8779 // For now, only handle fully promoted and indirect arguments. 8780 if (VA.getLocInfo() == CCValAssign::Indirect) { 8781 // Store the argument in a stack slot and pass its address. 8782 Align StackAlign = 8783 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 8784 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 8785 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 8786 // If the original argument was split (e.g. i128), we need 8787 // to store the required parts of it here (and pass just one address). 8788 // Vectors may be partly split to registers and partly to the stack, in 8789 // which case the base address is partly offset and subsequent stores are 8790 // relative to that. 8791 unsigned ArgIndex = Outs[i].OrigArgIndex; 8792 unsigned ArgPartOffset = Outs[i].PartOffset; 8793 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8794 // Calculate the total size to store. We don't have access to what we're 8795 // actually storing other than performing the loop and collecting the 8796 // info. 8797 SmallVector<std::pair<SDValue, SDValue>> Parts; 8798 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 8799 SDValue PartValue = OutVals[i + 1]; 8800 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 8801 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8802 EVT PartVT = PartValue.getValueType(); 8803 if (PartVT.isScalableVector()) 8804 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8805 StoredSize += PartVT.getStoreSize(); 8806 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 8807 Parts.push_back(std::make_pair(PartValue, Offset)); 8808 ++i; 8809 } 8810 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 8811 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 8812 MemOpChains.push_back( 8813 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 8814 MachinePointerInfo::getFixedStack(MF, FI))); 8815 for (const auto &Part : Parts) { 8816 SDValue PartValue = Part.first; 8817 SDValue PartOffset = Part.second; 8818 SDValue Address = 8819 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 8820 MemOpChains.push_back( 8821 DAG.getStore(Chain, DL, PartValue, Address, 8822 MachinePointerInfo::getFixedStack(MF, FI))); 8823 } 8824 ArgValue = SpillSlot; 8825 } else { 8826 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 8827 } 8828 8829 // Use local copy if it is a byval arg. 8830 if (Flags.isByVal()) 8831 ArgValue = ByValArgs[j++]; 8832 8833 if (VA.isRegLoc()) { 8834 // Queue up the argument copies and emit them at the end. 8835 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 8836 } else { 8837 assert(VA.isMemLoc() && "Argument not register or memory"); 8838 assert(!IsTailCall && "Tail call not allowed if stack is used " 8839 "for passing parameters"); 8840 8841 // Work out the address of the stack slot. 8842 if (!StackPtr.getNode()) 8843 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 8844 SDValue Address = 8845 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 8846 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 8847 8848 // Emit the store. 8849 MemOpChains.push_back( 8850 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 8851 } 8852 } 8853 8854 // Join the stores, which are independent of one another. 8855 if (!MemOpChains.empty()) 8856 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 8857 8858 SDValue Glue; 8859 8860 // Build a sequence of copy-to-reg nodes, chained and glued together. 8861 for (auto &Reg : RegsToPass) { 8862 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 8863 Glue = Chain.getValue(1); 8864 } 8865 8866 // Validate that none of the argument registers have been marked as 8867 // reserved, if so report an error. Do the same for the return address if this 8868 // is not a tailcall. 8869 validateCCReservedRegs(RegsToPass, MF); 8870 if (!IsTailCall && 8871 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 8872 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 8873 MF.getFunction(), 8874 "Return address register required, but has been reserved."}); 8875 8876 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 8877 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 8878 // split it and then direct call can be matched by PseudoCALL. 8879 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 8880 const GlobalValue *GV = S->getGlobal(); 8881 8882 unsigned OpFlags = RISCVII::MO_CALL; 8883 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 8884 OpFlags = RISCVII::MO_PLT; 8885 8886 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 8887 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 8888 unsigned OpFlags = RISCVII::MO_CALL; 8889 8890 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 8891 nullptr)) 8892 OpFlags = RISCVII::MO_PLT; 8893 8894 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 8895 } 8896 8897 // The first call operand is the chain and the second is the target address. 8898 SmallVector<SDValue, 8> Ops; 8899 Ops.push_back(Chain); 8900 Ops.push_back(Callee); 8901 8902 // Add argument registers to the end of the list so that they are 8903 // known live into the call. 8904 for (auto &Reg : RegsToPass) 8905 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 8906 8907 if (!IsTailCall) { 8908 // Add a register mask operand representing the call-preserved registers. 8909 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8910 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 8911 assert(Mask && "Missing call preserved mask for calling convention"); 8912 Ops.push_back(DAG.getRegisterMask(Mask)); 8913 } 8914 8915 // Glue the call to the argument copies, if any. 8916 if (Glue.getNode()) 8917 Ops.push_back(Glue); 8918 8919 // Emit the call. 8920 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8921 8922 if (IsTailCall) { 8923 MF.getFrameInfo().setHasTailCall(); 8924 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 8925 } 8926 8927 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 8928 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 8929 Glue = Chain.getValue(1); 8930 8931 // Mark the end of the call, which is glued to the call itself. 8932 Chain = DAG.getCALLSEQ_END(Chain, 8933 DAG.getConstant(NumBytes, DL, PtrVT, true), 8934 DAG.getConstant(0, DL, PtrVT, true), 8935 Glue, DL); 8936 Glue = Chain.getValue(1); 8937 8938 // Assign locations to each value returned by this call. 8939 SmallVector<CCValAssign, 16> RVLocs; 8940 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 8941 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 8942 8943 // Copy all of the result registers out of their specified physreg. 8944 for (auto &VA : RVLocs) { 8945 // Copy the value out 8946 SDValue RetValue = 8947 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 8948 // Glue the RetValue to the end of the call sequence 8949 Chain = RetValue.getValue(1); 8950 Glue = RetValue.getValue(2); 8951 8952 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 8953 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 8954 SDValue RetValue2 = 8955 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 8956 Chain = RetValue2.getValue(1); 8957 Glue = RetValue2.getValue(2); 8958 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 8959 RetValue2); 8960 } 8961 8962 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 8963 8964 InVals.push_back(RetValue); 8965 } 8966 8967 return Chain; 8968 } 8969 8970 bool RISCVTargetLowering::CanLowerReturn( 8971 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 8972 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 8973 SmallVector<CCValAssign, 16> RVLocs; 8974 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 8975 8976 Optional<unsigned> FirstMaskArgument; 8977 if (Subtarget.hasStdExtV()) 8978 FirstMaskArgument = preAssignMask(Outs); 8979 8980 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 8981 MVT VT = Outs[i].VT; 8982 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8983 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8984 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 8985 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 8986 *this, FirstMaskArgument)) 8987 return false; 8988 } 8989 return true; 8990 } 8991 8992 SDValue 8993 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 8994 bool IsVarArg, 8995 const SmallVectorImpl<ISD::OutputArg> &Outs, 8996 const SmallVectorImpl<SDValue> &OutVals, 8997 const SDLoc &DL, SelectionDAG &DAG) const { 8998 const MachineFunction &MF = DAG.getMachineFunction(); 8999 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9000 9001 // Stores the assignment of the return value to a location. 9002 SmallVector<CCValAssign, 16> RVLocs; 9003 9004 // Info about the registers and stack slot. 9005 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9006 *DAG.getContext()); 9007 9008 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9009 nullptr, CC_RISCV); 9010 9011 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9012 report_fatal_error("GHC functions return void only"); 9013 9014 SDValue Glue; 9015 SmallVector<SDValue, 4> RetOps(1, Chain); 9016 9017 // Copy the result values into the output registers. 9018 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9019 SDValue Val = OutVals[i]; 9020 CCValAssign &VA = RVLocs[i]; 9021 assert(VA.isRegLoc() && "Can only return in registers!"); 9022 9023 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9024 // Handle returning f64 on RV32D with a soft float ABI. 9025 assert(VA.isRegLoc() && "Expected return via registers"); 9026 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9027 DAG.getVTList(MVT::i32, MVT::i32), Val); 9028 SDValue Lo = SplitF64.getValue(0); 9029 SDValue Hi = SplitF64.getValue(1); 9030 Register RegLo = VA.getLocReg(); 9031 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9032 Register RegHi = RegLo + 1; 9033 9034 if (STI.isRegisterReservedByUser(RegLo) || 9035 STI.isRegisterReservedByUser(RegHi)) 9036 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9037 MF.getFunction(), 9038 "Return value register required, but has been reserved."}); 9039 9040 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9041 Glue = Chain.getValue(1); 9042 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9043 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9044 Glue = Chain.getValue(1); 9045 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9046 } else { 9047 // Handle a 'normal' return. 9048 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9049 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9050 9051 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9052 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9053 MF.getFunction(), 9054 "Return value register required, but has been reserved."}); 9055 9056 // Guarantee that all emitted copies are stuck together. 9057 Glue = Chain.getValue(1); 9058 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9059 } 9060 } 9061 9062 RetOps[0] = Chain; // Update chain. 9063 9064 // Add the glue node if we have it. 9065 if (Glue.getNode()) { 9066 RetOps.push_back(Glue); 9067 } 9068 9069 unsigned RetOpc = RISCVISD::RET_FLAG; 9070 // Interrupt service routines use different return instructions. 9071 const Function &Func = DAG.getMachineFunction().getFunction(); 9072 if (Func.hasFnAttribute("interrupt")) { 9073 if (!Func.getReturnType()->isVoidTy()) 9074 report_fatal_error( 9075 "Functions with the interrupt attribute must have void return type!"); 9076 9077 MachineFunction &MF = DAG.getMachineFunction(); 9078 StringRef Kind = 9079 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9080 9081 if (Kind == "user") 9082 RetOpc = RISCVISD::URET_FLAG; 9083 else if (Kind == "supervisor") 9084 RetOpc = RISCVISD::SRET_FLAG; 9085 else 9086 RetOpc = RISCVISD::MRET_FLAG; 9087 } 9088 9089 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9090 } 9091 9092 void RISCVTargetLowering::validateCCReservedRegs( 9093 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9094 MachineFunction &MF) const { 9095 const Function &F = MF.getFunction(); 9096 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9097 9098 if (llvm::any_of(Regs, [&STI](auto Reg) { 9099 return STI.isRegisterReservedByUser(Reg.first); 9100 })) 9101 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9102 F, "Argument register required, but has been reserved."}); 9103 } 9104 9105 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9106 return CI->isTailCall(); 9107 } 9108 9109 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9110 #define NODE_NAME_CASE(NODE) \ 9111 case RISCVISD::NODE: \ 9112 return "RISCVISD::" #NODE; 9113 // clang-format off 9114 switch ((RISCVISD::NodeType)Opcode) { 9115 case RISCVISD::FIRST_NUMBER: 9116 break; 9117 NODE_NAME_CASE(RET_FLAG) 9118 NODE_NAME_CASE(URET_FLAG) 9119 NODE_NAME_CASE(SRET_FLAG) 9120 NODE_NAME_CASE(MRET_FLAG) 9121 NODE_NAME_CASE(CALL) 9122 NODE_NAME_CASE(SELECT_CC) 9123 NODE_NAME_CASE(BR_CC) 9124 NODE_NAME_CASE(BuildPairF64) 9125 NODE_NAME_CASE(SplitF64) 9126 NODE_NAME_CASE(TAIL) 9127 NODE_NAME_CASE(MULHSU) 9128 NODE_NAME_CASE(SLLW) 9129 NODE_NAME_CASE(SRAW) 9130 NODE_NAME_CASE(SRLW) 9131 NODE_NAME_CASE(DIVW) 9132 NODE_NAME_CASE(DIVUW) 9133 NODE_NAME_CASE(REMUW) 9134 NODE_NAME_CASE(ROLW) 9135 NODE_NAME_CASE(RORW) 9136 NODE_NAME_CASE(CLZW) 9137 NODE_NAME_CASE(CTZW) 9138 NODE_NAME_CASE(FSLW) 9139 NODE_NAME_CASE(FSRW) 9140 NODE_NAME_CASE(FSL) 9141 NODE_NAME_CASE(FSR) 9142 NODE_NAME_CASE(FMV_H_X) 9143 NODE_NAME_CASE(FMV_X_ANYEXTH) 9144 NODE_NAME_CASE(FMV_W_X_RV64) 9145 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9146 NODE_NAME_CASE(FCVT_X_RTZ) 9147 NODE_NAME_CASE(FCVT_XU_RTZ) 9148 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9149 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9150 NODE_NAME_CASE(READ_CYCLE_WIDE) 9151 NODE_NAME_CASE(GREV) 9152 NODE_NAME_CASE(GREVW) 9153 NODE_NAME_CASE(GORC) 9154 NODE_NAME_CASE(GORCW) 9155 NODE_NAME_CASE(SHFL) 9156 NODE_NAME_CASE(SHFLW) 9157 NODE_NAME_CASE(UNSHFL) 9158 NODE_NAME_CASE(UNSHFLW) 9159 NODE_NAME_CASE(BCOMPRESS) 9160 NODE_NAME_CASE(BCOMPRESSW) 9161 NODE_NAME_CASE(BDECOMPRESS) 9162 NODE_NAME_CASE(BDECOMPRESSW) 9163 NODE_NAME_CASE(VMV_V_X_VL) 9164 NODE_NAME_CASE(VFMV_V_F_VL) 9165 NODE_NAME_CASE(VMV_X_S) 9166 NODE_NAME_CASE(VMV_S_X_VL) 9167 NODE_NAME_CASE(VFMV_S_F_VL) 9168 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9169 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9170 NODE_NAME_CASE(READ_VLENB) 9171 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9172 NODE_NAME_CASE(VSLIDEUP_VL) 9173 NODE_NAME_CASE(VSLIDE1UP_VL) 9174 NODE_NAME_CASE(VSLIDEDOWN_VL) 9175 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9176 NODE_NAME_CASE(VID_VL) 9177 NODE_NAME_CASE(VFNCVT_ROD_VL) 9178 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9179 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9180 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9181 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9182 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9183 NODE_NAME_CASE(VECREDUCE_AND_VL) 9184 NODE_NAME_CASE(VECREDUCE_OR_VL) 9185 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9186 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9187 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9188 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9189 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9190 NODE_NAME_CASE(ADD_VL) 9191 NODE_NAME_CASE(AND_VL) 9192 NODE_NAME_CASE(MUL_VL) 9193 NODE_NAME_CASE(OR_VL) 9194 NODE_NAME_CASE(SDIV_VL) 9195 NODE_NAME_CASE(SHL_VL) 9196 NODE_NAME_CASE(SREM_VL) 9197 NODE_NAME_CASE(SRA_VL) 9198 NODE_NAME_CASE(SRL_VL) 9199 NODE_NAME_CASE(SUB_VL) 9200 NODE_NAME_CASE(UDIV_VL) 9201 NODE_NAME_CASE(UREM_VL) 9202 NODE_NAME_CASE(XOR_VL) 9203 NODE_NAME_CASE(SADDSAT_VL) 9204 NODE_NAME_CASE(UADDSAT_VL) 9205 NODE_NAME_CASE(SSUBSAT_VL) 9206 NODE_NAME_CASE(USUBSAT_VL) 9207 NODE_NAME_CASE(FADD_VL) 9208 NODE_NAME_CASE(FSUB_VL) 9209 NODE_NAME_CASE(FMUL_VL) 9210 NODE_NAME_CASE(FDIV_VL) 9211 NODE_NAME_CASE(FNEG_VL) 9212 NODE_NAME_CASE(FABS_VL) 9213 NODE_NAME_CASE(FSQRT_VL) 9214 NODE_NAME_CASE(FMA_VL) 9215 NODE_NAME_CASE(FCOPYSIGN_VL) 9216 NODE_NAME_CASE(SMIN_VL) 9217 NODE_NAME_CASE(SMAX_VL) 9218 NODE_NAME_CASE(UMIN_VL) 9219 NODE_NAME_CASE(UMAX_VL) 9220 NODE_NAME_CASE(FMINNUM_VL) 9221 NODE_NAME_CASE(FMAXNUM_VL) 9222 NODE_NAME_CASE(MULHS_VL) 9223 NODE_NAME_CASE(MULHU_VL) 9224 NODE_NAME_CASE(FP_TO_SINT_VL) 9225 NODE_NAME_CASE(FP_TO_UINT_VL) 9226 NODE_NAME_CASE(SINT_TO_FP_VL) 9227 NODE_NAME_CASE(UINT_TO_FP_VL) 9228 NODE_NAME_CASE(FP_EXTEND_VL) 9229 NODE_NAME_CASE(FP_ROUND_VL) 9230 NODE_NAME_CASE(VWMUL_VL) 9231 NODE_NAME_CASE(VWMULU_VL) 9232 NODE_NAME_CASE(SETCC_VL) 9233 NODE_NAME_CASE(VSELECT_VL) 9234 NODE_NAME_CASE(VMAND_VL) 9235 NODE_NAME_CASE(VMOR_VL) 9236 NODE_NAME_CASE(VMXOR_VL) 9237 NODE_NAME_CASE(VMCLR_VL) 9238 NODE_NAME_CASE(VMSET_VL) 9239 NODE_NAME_CASE(VRGATHER_VX_VL) 9240 NODE_NAME_CASE(VRGATHER_VV_VL) 9241 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9242 NODE_NAME_CASE(VSEXT_VL) 9243 NODE_NAME_CASE(VZEXT_VL) 9244 NODE_NAME_CASE(VPOPC_VL) 9245 NODE_NAME_CASE(VLE_VL) 9246 NODE_NAME_CASE(VSE_VL) 9247 NODE_NAME_CASE(READ_CSR) 9248 NODE_NAME_CASE(WRITE_CSR) 9249 NODE_NAME_CASE(SWAP_CSR) 9250 } 9251 // clang-format on 9252 return nullptr; 9253 #undef NODE_NAME_CASE 9254 } 9255 9256 /// getConstraintType - Given a constraint letter, return the type of 9257 /// constraint it is for this target. 9258 RISCVTargetLowering::ConstraintType 9259 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9260 if (Constraint.size() == 1) { 9261 switch (Constraint[0]) { 9262 default: 9263 break; 9264 case 'f': 9265 return C_RegisterClass; 9266 case 'I': 9267 case 'J': 9268 case 'K': 9269 return C_Immediate; 9270 case 'A': 9271 return C_Memory; 9272 case 'S': // A symbolic address 9273 return C_Other; 9274 } 9275 } else { 9276 if (Constraint == "vr" || Constraint == "vm") 9277 return C_RegisterClass; 9278 } 9279 return TargetLowering::getConstraintType(Constraint); 9280 } 9281 9282 std::pair<unsigned, const TargetRegisterClass *> 9283 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9284 StringRef Constraint, 9285 MVT VT) const { 9286 // First, see if this is a constraint that directly corresponds to a 9287 // RISCV register class. 9288 if (Constraint.size() == 1) { 9289 switch (Constraint[0]) { 9290 case 'r': 9291 return std::make_pair(0U, &RISCV::GPRRegClass); 9292 case 'f': 9293 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9294 return std::make_pair(0U, &RISCV::FPR16RegClass); 9295 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9296 return std::make_pair(0U, &RISCV::FPR32RegClass); 9297 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9298 return std::make_pair(0U, &RISCV::FPR64RegClass); 9299 break; 9300 default: 9301 break; 9302 } 9303 } else { 9304 if (Constraint == "vr") { 9305 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9306 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9307 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9308 return std::make_pair(0U, RC); 9309 } 9310 } else if (Constraint == "vm") { 9311 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9312 return std::make_pair(0U, &RISCV::VMRegClass); 9313 } 9314 } 9315 9316 // Clang will correctly decode the usage of register name aliases into their 9317 // official names. However, other frontends like `rustc` do not. This allows 9318 // users of these frontends to use the ABI names for registers in LLVM-style 9319 // register constraints. 9320 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9321 .Case("{zero}", RISCV::X0) 9322 .Case("{ra}", RISCV::X1) 9323 .Case("{sp}", RISCV::X2) 9324 .Case("{gp}", RISCV::X3) 9325 .Case("{tp}", RISCV::X4) 9326 .Case("{t0}", RISCV::X5) 9327 .Case("{t1}", RISCV::X6) 9328 .Case("{t2}", RISCV::X7) 9329 .Cases("{s0}", "{fp}", RISCV::X8) 9330 .Case("{s1}", RISCV::X9) 9331 .Case("{a0}", RISCV::X10) 9332 .Case("{a1}", RISCV::X11) 9333 .Case("{a2}", RISCV::X12) 9334 .Case("{a3}", RISCV::X13) 9335 .Case("{a4}", RISCV::X14) 9336 .Case("{a5}", RISCV::X15) 9337 .Case("{a6}", RISCV::X16) 9338 .Case("{a7}", RISCV::X17) 9339 .Case("{s2}", RISCV::X18) 9340 .Case("{s3}", RISCV::X19) 9341 .Case("{s4}", RISCV::X20) 9342 .Case("{s5}", RISCV::X21) 9343 .Case("{s6}", RISCV::X22) 9344 .Case("{s7}", RISCV::X23) 9345 .Case("{s8}", RISCV::X24) 9346 .Case("{s9}", RISCV::X25) 9347 .Case("{s10}", RISCV::X26) 9348 .Case("{s11}", RISCV::X27) 9349 .Case("{t3}", RISCV::X28) 9350 .Case("{t4}", RISCV::X29) 9351 .Case("{t5}", RISCV::X30) 9352 .Case("{t6}", RISCV::X31) 9353 .Default(RISCV::NoRegister); 9354 if (XRegFromAlias != RISCV::NoRegister) 9355 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9356 9357 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9358 // TableGen record rather than the AsmName to choose registers for InlineAsm 9359 // constraints, plus we want to match those names to the widest floating point 9360 // register type available, manually select floating point registers here. 9361 // 9362 // The second case is the ABI name of the register, so that frontends can also 9363 // use the ABI names in register constraint lists. 9364 if (Subtarget.hasStdExtF()) { 9365 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9366 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9367 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9368 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9369 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9370 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9371 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9372 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9373 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9374 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9375 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9376 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9377 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9378 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9379 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9380 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9381 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9382 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9383 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9384 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9385 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9386 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9387 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9388 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9389 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9390 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9391 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9392 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9393 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9394 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9395 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9396 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9397 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9398 .Default(RISCV::NoRegister); 9399 if (FReg != RISCV::NoRegister) { 9400 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9401 if (Subtarget.hasStdExtD()) { 9402 unsigned RegNo = FReg - RISCV::F0_F; 9403 unsigned DReg = RISCV::F0_D + RegNo; 9404 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9405 } 9406 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9407 } 9408 } 9409 9410 if (Subtarget.hasStdExtV()) { 9411 Register VReg = StringSwitch<Register>(Constraint.lower()) 9412 .Case("{v0}", RISCV::V0) 9413 .Case("{v1}", RISCV::V1) 9414 .Case("{v2}", RISCV::V2) 9415 .Case("{v3}", RISCV::V3) 9416 .Case("{v4}", RISCV::V4) 9417 .Case("{v5}", RISCV::V5) 9418 .Case("{v6}", RISCV::V6) 9419 .Case("{v7}", RISCV::V7) 9420 .Case("{v8}", RISCV::V8) 9421 .Case("{v9}", RISCV::V9) 9422 .Case("{v10}", RISCV::V10) 9423 .Case("{v11}", RISCV::V11) 9424 .Case("{v12}", RISCV::V12) 9425 .Case("{v13}", RISCV::V13) 9426 .Case("{v14}", RISCV::V14) 9427 .Case("{v15}", RISCV::V15) 9428 .Case("{v16}", RISCV::V16) 9429 .Case("{v17}", RISCV::V17) 9430 .Case("{v18}", RISCV::V18) 9431 .Case("{v19}", RISCV::V19) 9432 .Case("{v20}", RISCV::V20) 9433 .Case("{v21}", RISCV::V21) 9434 .Case("{v22}", RISCV::V22) 9435 .Case("{v23}", RISCV::V23) 9436 .Case("{v24}", RISCV::V24) 9437 .Case("{v25}", RISCV::V25) 9438 .Case("{v26}", RISCV::V26) 9439 .Case("{v27}", RISCV::V27) 9440 .Case("{v28}", RISCV::V28) 9441 .Case("{v29}", RISCV::V29) 9442 .Case("{v30}", RISCV::V30) 9443 .Case("{v31}", RISCV::V31) 9444 .Default(RISCV::NoRegister); 9445 if (VReg != RISCV::NoRegister) { 9446 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9447 return std::make_pair(VReg, &RISCV::VMRegClass); 9448 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9449 return std::make_pair(VReg, &RISCV::VRRegClass); 9450 for (const auto *RC : 9451 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9452 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9453 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9454 return std::make_pair(VReg, RC); 9455 } 9456 } 9457 } 9458 } 9459 9460 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9461 } 9462 9463 unsigned 9464 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9465 // Currently only support length 1 constraints. 9466 if (ConstraintCode.size() == 1) { 9467 switch (ConstraintCode[0]) { 9468 case 'A': 9469 return InlineAsm::Constraint_A; 9470 default: 9471 break; 9472 } 9473 } 9474 9475 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9476 } 9477 9478 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9479 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9480 SelectionDAG &DAG) const { 9481 // Currently only support length 1 constraints. 9482 if (Constraint.length() == 1) { 9483 switch (Constraint[0]) { 9484 case 'I': 9485 // Validate & create a 12-bit signed immediate operand. 9486 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9487 uint64_t CVal = C->getSExtValue(); 9488 if (isInt<12>(CVal)) 9489 Ops.push_back( 9490 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9491 } 9492 return; 9493 case 'J': 9494 // Validate & create an integer zero operand. 9495 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9496 if (C->getZExtValue() == 0) 9497 Ops.push_back( 9498 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9499 return; 9500 case 'K': 9501 // Validate & create a 5-bit unsigned immediate operand. 9502 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9503 uint64_t CVal = C->getZExtValue(); 9504 if (isUInt<5>(CVal)) 9505 Ops.push_back( 9506 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9507 } 9508 return; 9509 case 'S': 9510 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9511 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9512 GA->getValueType(0))); 9513 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9514 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9515 BA->getValueType(0))); 9516 } 9517 return; 9518 default: 9519 break; 9520 } 9521 } 9522 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9523 } 9524 9525 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9526 Instruction *Inst, 9527 AtomicOrdering Ord) const { 9528 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9529 return Builder.CreateFence(Ord); 9530 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9531 return Builder.CreateFence(AtomicOrdering::Release); 9532 return nullptr; 9533 } 9534 9535 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9536 Instruction *Inst, 9537 AtomicOrdering Ord) const { 9538 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9539 return Builder.CreateFence(AtomicOrdering::Acquire); 9540 return nullptr; 9541 } 9542 9543 TargetLowering::AtomicExpansionKind 9544 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9545 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9546 // point operations can't be used in an lr/sc sequence without breaking the 9547 // forward-progress guarantee. 9548 if (AI->isFloatingPointOperation()) 9549 return AtomicExpansionKind::CmpXChg; 9550 9551 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9552 if (Size == 8 || Size == 16) 9553 return AtomicExpansionKind::MaskedIntrinsic; 9554 return AtomicExpansionKind::None; 9555 } 9556 9557 static Intrinsic::ID 9558 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9559 if (XLen == 32) { 9560 switch (BinOp) { 9561 default: 9562 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9563 case AtomicRMWInst::Xchg: 9564 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9565 case AtomicRMWInst::Add: 9566 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9567 case AtomicRMWInst::Sub: 9568 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9569 case AtomicRMWInst::Nand: 9570 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9571 case AtomicRMWInst::Max: 9572 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9573 case AtomicRMWInst::Min: 9574 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9575 case AtomicRMWInst::UMax: 9576 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9577 case AtomicRMWInst::UMin: 9578 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9579 } 9580 } 9581 9582 if (XLen == 64) { 9583 switch (BinOp) { 9584 default: 9585 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9586 case AtomicRMWInst::Xchg: 9587 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9588 case AtomicRMWInst::Add: 9589 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9590 case AtomicRMWInst::Sub: 9591 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9592 case AtomicRMWInst::Nand: 9593 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9594 case AtomicRMWInst::Max: 9595 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9596 case AtomicRMWInst::Min: 9597 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9598 case AtomicRMWInst::UMax: 9599 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9600 case AtomicRMWInst::UMin: 9601 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9602 } 9603 } 9604 9605 llvm_unreachable("Unexpected XLen\n"); 9606 } 9607 9608 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 9609 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 9610 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 9611 unsigned XLen = Subtarget.getXLen(); 9612 Value *Ordering = 9613 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 9614 Type *Tys[] = {AlignedAddr->getType()}; 9615 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 9616 AI->getModule(), 9617 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 9618 9619 if (XLen == 64) { 9620 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 9621 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9622 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 9623 } 9624 9625 Value *Result; 9626 9627 // Must pass the shift amount needed to sign extend the loaded value prior 9628 // to performing a signed comparison for min/max. ShiftAmt is the number of 9629 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 9630 // is the number of bits to left+right shift the value in order to 9631 // sign-extend. 9632 if (AI->getOperation() == AtomicRMWInst::Min || 9633 AI->getOperation() == AtomicRMWInst::Max) { 9634 const DataLayout &DL = AI->getModule()->getDataLayout(); 9635 unsigned ValWidth = 9636 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 9637 Value *SextShamt = 9638 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 9639 Result = Builder.CreateCall(LrwOpScwLoop, 9640 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 9641 } else { 9642 Result = 9643 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 9644 } 9645 9646 if (XLen == 64) 9647 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9648 return Result; 9649 } 9650 9651 TargetLowering::AtomicExpansionKind 9652 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 9653 AtomicCmpXchgInst *CI) const { 9654 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 9655 if (Size == 8 || Size == 16) 9656 return AtomicExpansionKind::MaskedIntrinsic; 9657 return AtomicExpansionKind::None; 9658 } 9659 9660 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 9661 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 9662 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 9663 unsigned XLen = Subtarget.getXLen(); 9664 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 9665 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 9666 if (XLen == 64) { 9667 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 9668 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 9669 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9670 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 9671 } 9672 Type *Tys[] = {AlignedAddr->getType()}; 9673 Function *MaskedCmpXchg = 9674 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 9675 Value *Result = Builder.CreateCall( 9676 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 9677 if (XLen == 64) 9678 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 9679 return Result; 9680 } 9681 9682 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 9683 return false; 9684 } 9685 9686 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 9687 EVT VT) const { 9688 VT = VT.getScalarType(); 9689 9690 if (!VT.isSimple()) 9691 return false; 9692 9693 switch (VT.getSimpleVT().SimpleTy) { 9694 case MVT::f16: 9695 return Subtarget.hasStdExtZfh(); 9696 case MVT::f32: 9697 return Subtarget.hasStdExtF(); 9698 case MVT::f64: 9699 return Subtarget.hasStdExtD(); 9700 default: 9701 break; 9702 } 9703 9704 return false; 9705 } 9706 9707 Register RISCVTargetLowering::getExceptionPointerRegister( 9708 const Constant *PersonalityFn) const { 9709 return RISCV::X10; 9710 } 9711 9712 Register RISCVTargetLowering::getExceptionSelectorRegister( 9713 const Constant *PersonalityFn) const { 9714 return RISCV::X11; 9715 } 9716 9717 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 9718 // Return false to suppress the unnecessary extensions if the LibCall 9719 // arguments or return value is f32 type for LP64 ABI. 9720 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 9721 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 9722 return false; 9723 9724 return true; 9725 } 9726 9727 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 9728 if (Subtarget.is64Bit() && Type == MVT::i32) 9729 return true; 9730 9731 return IsSigned; 9732 } 9733 9734 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 9735 SDValue C) const { 9736 // Check integral scalar types. 9737 if (VT.isScalarInteger()) { 9738 // Omit the optimization if the sub target has the M extension and the data 9739 // size exceeds XLen. 9740 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 9741 return false; 9742 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 9743 // Break the MUL to a SLLI and an ADD/SUB. 9744 const APInt &Imm = ConstNode->getAPIntValue(); 9745 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 9746 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 9747 return true; 9748 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 9749 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 9750 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 9751 (Imm - 8).isPowerOf2())) 9752 return true; 9753 // Omit the following optimization if the sub target has the M extension 9754 // and the data size >= XLen. 9755 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 9756 return false; 9757 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 9758 // a pair of LUI/ADDI. 9759 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 9760 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 9761 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 9762 (1 - ImmS).isPowerOf2()) 9763 return true; 9764 } 9765 } 9766 } 9767 9768 return false; 9769 } 9770 9771 bool RISCVTargetLowering::isMulAddWithConstProfitable( 9772 const SDValue &AddNode, const SDValue &ConstNode) const { 9773 // Let the DAGCombiner decide for vectors. 9774 EVT VT = AddNode.getValueType(); 9775 if (VT.isVector()) 9776 return true; 9777 9778 // Let the DAGCombiner decide for larger types. 9779 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 9780 return true; 9781 9782 // It is worse if c1 is simm12 while c1*c2 is not. 9783 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 9784 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 9785 const APInt &C1 = C1Node->getAPIntValue(); 9786 const APInt &C2 = C2Node->getAPIntValue(); 9787 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 9788 return false; 9789 9790 // Default to true and let the DAGCombiner decide. 9791 return true; 9792 } 9793 9794 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 9795 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 9796 bool *Fast) const { 9797 if (!VT.isVector()) 9798 return false; 9799 9800 EVT ElemVT = VT.getVectorElementType(); 9801 if (Alignment >= ElemVT.getStoreSize()) { 9802 if (Fast) 9803 *Fast = true; 9804 return true; 9805 } 9806 9807 return false; 9808 } 9809 9810 bool RISCVTargetLowering::splitValueIntoRegisterParts( 9811 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 9812 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 9813 bool IsABIRegCopy = CC.hasValue(); 9814 EVT ValueVT = Val.getValueType(); 9815 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9816 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 9817 // and cast to f32. 9818 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 9819 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 9820 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 9821 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 9822 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 9823 Parts[0] = Val; 9824 return true; 9825 } 9826 9827 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9828 LLVMContext &Context = *DAG.getContext(); 9829 EVT ValueEltVT = ValueVT.getVectorElementType(); 9830 EVT PartEltVT = PartVT.getVectorElementType(); 9831 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9832 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9833 if (PartVTBitSize % ValueVTBitSize == 0) { 9834 // If the element types are different, bitcast to the same element type of 9835 // PartVT first. 9836 if (ValueEltVT != PartEltVT) { 9837 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9838 assert(Count != 0 && "The number of element should not be zero."); 9839 EVT SameEltTypeVT = 9840 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9841 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 9842 } 9843 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 9844 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9845 Parts[0] = Val; 9846 return true; 9847 } 9848 } 9849 return false; 9850 } 9851 9852 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 9853 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 9854 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 9855 bool IsABIRegCopy = CC.hasValue(); 9856 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 9857 SDValue Val = Parts[0]; 9858 9859 // Cast the f32 to i32, truncate to i16, and cast back to f16. 9860 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 9861 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 9862 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 9863 return Val; 9864 } 9865 9866 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 9867 LLVMContext &Context = *DAG.getContext(); 9868 SDValue Val = Parts[0]; 9869 EVT ValueEltVT = ValueVT.getVectorElementType(); 9870 EVT PartEltVT = PartVT.getVectorElementType(); 9871 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 9872 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 9873 if (PartVTBitSize % ValueVTBitSize == 0) { 9874 EVT SameEltTypeVT = ValueVT; 9875 // If the element types are different, convert it to the same element type 9876 // of PartVT. 9877 if (ValueEltVT != PartEltVT) { 9878 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 9879 assert(Count != 0 && "The number of element should not be zero."); 9880 SameEltTypeVT = 9881 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 9882 } 9883 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 9884 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 9885 if (ValueEltVT != PartEltVT) 9886 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 9887 return Val; 9888 } 9889 } 9890 return SDValue(); 9891 } 9892 9893 #define GET_REGISTER_MATCHER 9894 #include "RISCVGenAsmMatcher.inc" 9895 9896 Register 9897 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 9898 const MachineFunction &MF) const { 9899 Register Reg = MatchRegisterAltName(RegName); 9900 if (Reg == RISCV::NoRegister) 9901 Reg = MatchRegisterName(RegName); 9902 if (Reg == RISCV::NoRegister) 9903 report_fatal_error( 9904 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 9905 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 9906 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 9907 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 9908 StringRef(RegName) + "\".")); 9909 return Reg; 9910 } 9911 9912 namespace llvm { 9913 namespace RISCVVIntrinsicsTable { 9914 9915 #define GET_RISCVVIntrinsicsTable_IMPL 9916 #include "RISCVGenSearchableTables.inc" 9917 9918 } // namespace RISCVVIntrinsicsTable 9919 9920 } // namespace llvm 9921