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