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