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