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