1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 29 #include "llvm/CodeGen/ValueTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/IntrinsicsRISCV.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/KnownBits.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Support/raw_ostream.h" 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "riscv-lower" 44 45 STATISTIC(NumTailCalls, "Number of tail calls"); 46 47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 48 const RISCVSubtarget &STI) 49 : TargetLowering(TM), Subtarget(STI) { 50 51 if (Subtarget.isRV32E()) 52 report_fatal_error("Codegen not yet implemented for RV32E"); 53 54 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 55 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 56 57 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 58 !Subtarget.hasStdExtF()) { 59 errs() << "Hard-float 'f' ABI can't be used for a target that " 60 "doesn't support the F instruction set extension (ignoring " 61 "target-abi)\n"; 62 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 63 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 64 !Subtarget.hasStdExtD()) { 65 errs() << "Hard-float 'd' ABI can't be used for a target that " 66 "doesn't support the D instruction set extension (ignoring " 67 "target-abi)\n"; 68 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 69 } 70 71 switch (ABI) { 72 default: 73 report_fatal_error("Don't know how to lower this ABI"); 74 case RISCVABI::ABI_ILP32: 75 case RISCVABI::ABI_ILP32F: 76 case RISCVABI::ABI_ILP32D: 77 case RISCVABI::ABI_LP64: 78 case RISCVABI::ABI_LP64F: 79 case RISCVABI::ABI_LP64D: 80 break; 81 } 82 83 MVT XLenVT = Subtarget.getXLenVT(); 84 85 // Set up the register classes. 86 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 87 88 if (Subtarget.hasStdExtZfh()) 89 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 90 if (Subtarget.hasStdExtF()) 91 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 92 if (Subtarget.hasStdExtD()) 93 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 94 95 static const MVT::SimpleValueType BoolVecVTs[] = { 96 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 97 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 98 static const MVT::SimpleValueType IntVecVTs[] = { 99 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 100 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 101 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 102 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 103 MVT::nxv4i64, MVT::nxv8i64}; 104 static const MVT::SimpleValueType F16VecVTs[] = { 105 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 106 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 107 static const MVT::SimpleValueType F32VecVTs[] = { 108 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 109 static const MVT::SimpleValueType F64VecVTs[] = { 110 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 111 112 if (Subtarget.hasVInstructions()) { 113 auto addRegClassForRVV = [this](MVT VT) { 114 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 115 assert(Size <= 512 && isPowerOf2_32(Size)); 116 const TargetRegisterClass *RC; 117 if (Size <= 64) 118 RC = &RISCV::VRRegClass; 119 else if (Size == 128) 120 RC = &RISCV::VRM2RegClass; 121 else if (Size == 256) 122 RC = &RISCV::VRM4RegClass; 123 else 124 RC = &RISCV::VRM8RegClass; 125 126 addRegisterClass(VT, RC); 127 }; 128 129 for (MVT VT : BoolVecVTs) 130 addRegClassForRVV(VT); 131 for (MVT VT : IntVecVTs) { 132 if (VT.getVectorElementType() == MVT::i64 && 133 !Subtarget.hasVInstructionsI64()) 134 continue; 135 addRegClassForRVV(VT); 136 } 137 138 if (Subtarget.hasVInstructionsF16()) 139 for (MVT VT : F16VecVTs) 140 addRegClassForRVV(VT); 141 142 if (Subtarget.hasVInstructionsF32()) 143 for (MVT VT : F32VecVTs) 144 addRegClassForRVV(VT); 145 146 if (Subtarget.hasVInstructionsF64()) 147 for (MVT VT : F64VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.useRVVForFixedLengthVectors()) { 151 auto addRegClassForFixedVectors = [this](MVT VT) { 152 MVT ContainerVT = getContainerForFixedLengthVector(VT); 153 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 154 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 155 addRegisterClass(VT, TRI.getRegClass(RCID)); 156 }; 157 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 158 if (useRVVForFixedLengthVectorVT(VT)) 159 addRegClassForFixedVectors(VT); 160 161 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 162 if (useRVVForFixedLengthVectorVT(VT)) 163 addRegClassForFixedVectors(VT); 164 } 165 } 166 167 // Compute derived properties from the register classes. 168 computeRegisterProperties(STI.getRegisterInfo()); 169 170 setStackPointerRegisterToSaveRestore(RISCV::X2); 171 172 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 173 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 174 175 // TODO: add all necessary setOperationAction calls. 176 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 177 178 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 179 setOperationAction(ISD::BR_CC, XLenVT, Expand); 180 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 181 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 182 183 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 184 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction(ISD::VAARG, MVT::Other, Expand); 188 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 189 setOperationAction(ISD::VAEND, MVT::Other, Expand); 190 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 192 if (!Subtarget.hasStdExtZbb()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 195 } 196 197 if (Subtarget.is64Bit()) { 198 setOperationAction(ISD::ADD, MVT::i32, Custom); 199 setOperationAction(ISD::SUB, MVT::i32, Custom); 200 setOperationAction(ISD::SHL, MVT::i32, Custom); 201 setOperationAction(ISD::SRA, MVT::i32, Custom); 202 setOperationAction(ISD::SRL, MVT::i32, Custom); 203 204 setOperationAction(ISD::UADDO, MVT::i32, Custom); 205 setOperationAction(ISD::USUBO, MVT::i32, Custom); 206 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 207 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 208 } else { 209 setLibcallName(RTLIB::SHL_I128, nullptr); 210 setLibcallName(RTLIB::SRL_I128, nullptr); 211 setLibcallName(RTLIB::SRA_I128, nullptr); 212 setLibcallName(RTLIB::MUL_I128, nullptr); 213 setLibcallName(RTLIB::MULO_I64, nullptr); 214 } 215 216 if (!Subtarget.hasStdExtM()) { 217 setOperationAction(ISD::MUL, XLenVT, Expand); 218 setOperationAction(ISD::MULHS, XLenVT, Expand); 219 setOperationAction(ISD::MULHU, XLenVT, Expand); 220 setOperationAction(ISD::SDIV, XLenVT, Expand); 221 setOperationAction(ISD::UDIV, XLenVT, Expand); 222 setOperationAction(ISD::SREM, XLenVT, Expand); 223 setOperationAction(ISD::UREM, XLenVT, Expand); 224 } else { 225 if (Subtarget.is64Bit()) { 226 setOperationAction(ISD::MUL, MVT::i32, Custom); 227 setOperationAction(ISD::MUL, MVT::i128, Custom); 228 229 setOperationAction(ISD::SDIV, MVT::i8, Custom); 230 setOperationAction(ISD::UDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UREM, MVT::i8, Custom); 232 setOperationAction(ISD::SDIV, MVT::i16, Custom); 233 setOperationAction(ISD::UDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UREM, MVT::i16, Custom); 235 setOperationAction(ISD::SDIV, MVT::i32, Custom); 236 setOperationAction(ISD::UDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UREM, MVT::i32, Custom); 238 } else { 239 setOperationAction(ISD::MUL, MVT::i64, Custom); 240 } 241 } 242 243 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 244 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 246 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 247 248 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 249 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 251 252 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::ROTL, MVT::i32, Custom); 255 setOperationAction(ISD::ROTR, MVT::i32, Custom); 256 } 257 } else { 258 setOperationAction(ISD::ROTL, XLenVT, Expand); 259 setOperationAction(ISD::ROTR, XLenVT, Expand); 260 } 261 262 if (Subtarget.hasStdExtZbp()) { 263 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 264 // more combining. 265 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 266 setOperationAction(ISD::BSWAP, XLenVT, Custom); 267 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 268 // BSWAP i8 doesn't exist. 269 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 270 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 271 272 if (Subtarget.is64Bit()) { 273 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 274 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 275 } 276 } else { 277 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 278 // pattern match it directly in isel. 279 setOperationAction(ISD::BSWAP, XLenVT, 280 Subtarget.hasStdExtZbb() ? Legal : Expand); 281 } 282 283 if (Subtarget.hasStdExtZbb()) { 284 setOperationAction(ISD::SMIN, XLenVT, Legal); 285 setOperationAction(ISD::SMAX, XLenVT, Legal); 286 setOperationAction(ISD::UMIN, XLenVT, Legal); 287 setOperationAction(ISD::UMAX, XLenVT, Legal); 288 289 if (Subtarget.is64Bit()) { 290 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 291 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 292 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 293 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 294 } 295 } else { 296 setOperationAction(ISD::CTTZ, XLenVT, Expand); 297 setOperationAction(ISD::CTLZ, XLenVT, Expand); 298 setOperationAction(ISD::CTPOP, XLenVT, Expand); 299 } 300 301 if (Subtarget.hasStdExtZbt()) { 302 setOperationAction(ISD::FSHL, XLenVT, Custom); 303 setOperationAction(ISD::FSHR, XLenVT, Custom); 304 setOperationAction(ISD::SELECT, XLenVT, Legal); 305 306 if (Subtarget.is64Bit()) { 307 setOperationAction(ISD::FSHL, MVT::i32, Custom); 308 setOperationAction(ISD::FSHR, MVT::i32, Custom); 309 } 310 } else { 311 setOperationAction(ISD::SELECT, XLenVT, Custom); 312 } 313 314 static const ISD::CondCode FPCCToExpand[] = { 315 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 316 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 317 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 318 319 static const ISD::NodeType FPOpToExpand[] = { 320 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 321 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 322 323 if (Subtarget.hasStdExtZfh()) 324 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 325 326 if (Subtarget.hasStdExtZfh()) { 327 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 328 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 329 setOperationAction(ISD::LRINT, MVT::f16, Legal); 330 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 331 setOperationAction(ISD::LROUND, MVT::f16, Legal); 332 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 333 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 334 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 335 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 336 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 337 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 338 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 339 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 340 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 341 for (auto CC : FPCCToExpand) 342 setCondCodeAction(CC, MVT::f16, Expand); 343 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 344 setOperationAction(ISD::SELECT, MVT::f16, Custom); 345 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 346 347 setOperationAction(ISD::FREM, MVT::f16, Promote); 348 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 349 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 350 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 351 setOperationAction(ISD::FRINT, MVT::f16, Promote); 352 setOperationAction(ISD::FROUND, MVT::f16, Promote); 353 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 354 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 355 setOperationAction(ISD::FPOW, MVT::f16, Promote); 356 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 357 setOperationAction(ISD::FCOS, MVT::f16, Promote); 358 setOperationAction(ISD::FSIN, MVT::f16, Promote); 359 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 360 setOperationAction(ISD::FEXP, MVT::f16, Promote); 361 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 362 setOperationAction(ISD::FLOG, MVT::f16, Promote); 363 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 364 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 365 366 // We need to custom promote this. 367 if (Subtarget.is64Bit()) 368 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 369 } 370 371 if (Subtarget.hasStdExtF()) { 372 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 373 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 374 setOperationAction(ISD::LRINT, MVT::f32, Legal); 375 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 376 setOperationAction(ISD::LROUND, MVT::f32, Legal); 377 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 378 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 379 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 380 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 381 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 382 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 383 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 384 for (auto CC : FPCCToExpand) 385 setCondCodeAction(CC, MVT::f32, Expand); 386 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 387 setOperationAction(ISD::SELECT, MVT::f32, Custom); 388 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 389 for (auto Op : FPOpToExpand) 390 setOperationAction(Op, MVT::f32, Expand); 391 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 392 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 393 } 394 395 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 396 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 397 398 if (Subtarget.hasStdExtD()) { 399 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 400 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 401 setOperationAction(ISD::LRINT, MVT::f64, Legal); 402 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 403 setOperationAction(ISD::LROUND, MVT::f64, Legal); 404 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 405 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 406 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 407 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 408 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 409 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 410 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 411 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 412 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 413 for (auto CC : FPCCToExpand) 414 setCondCodeAction(CC, MVT::f64, Expand); 415 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 416 setOperationAction(ISD::SELECT, MVT::f64, Custom); 417 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 418 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 419 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 420 for (auto Op : FPOpToExpand) 421 setOperationAction(Op, MVT::f64, Expand); 422 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 423 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 424 } 425 426 if (Subtarget.is64Bit()) { 427 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 428 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 429 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 430 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 431 } 432 433 if (Subtarget.hasStdExtF()) { 434 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 435 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 436 437 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 438 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 439 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 440 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 441 442 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 443 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 444 } 445 446 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 447 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 448 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 449 setOperationAction(ISD::JumpTable, XLenVT, Custom); 450 451 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 452 453 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 454 // Unfortunately this can't be determined just from the ISA naming string. 455 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 456 Subtarget.is64Bit() ? Legal : Custom); 457 458 setOperationAction(ISD::TRAP, MVT::Other, Legal); 459 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 460 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 461 if (Subtarget.is64Bit()) 462 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 463 464 if (Subtarget.hasStdExtA()) { 465 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 466 setMinCmpXchgSizeInBits(32); 467 } else { 468 setMaxAtomicSizeInBitsSupported(0); 469 } 470 471 setBooleanContents(ZeroOrOneBooleanContent); 472 473 if (Subtarget.hasVInstructions()) { 474 setBooleanVectorContents(ZeroOrOneBooleanContent); 475 476 setOperationAction(ISD::VSCALE, XLenVT, Custom); 477 478 // RVV intrinsics may have illegal operands. 479 // We also need to custom legalize vmv.x.s. 480 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 481 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 482 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 483 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 484 if (Subtarget.is64Bit()) { 485 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 486 } else { 487 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 488 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 489 } 490 491 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 492 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 493 494 static const unsigned IntegerVPOps[] = { 495 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 496 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 497 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 498 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 499 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 500 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 501 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 502 ISD::VP_SELECT}; 503 504 static const unsigned FloatingPointVPOps[] = { 505 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 506 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 507 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT}; 508 509 if (!Subtarget.is64Bit()) { 510 // We must custom-lower certain vXi64 operations on RV32 due to the vector 511 // element type being illegal. 512 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 513 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 514 515 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 516 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 517 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 518 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 519 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 520 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 521 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 522 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 523 524 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 525 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 526 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 527 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 528 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 529 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 530 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 531 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 532 } 533 534 for (MVT VT : BoolVecVTs) { 535 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 536 537 // Mask VTs are custom-expanded into a series of standard nodes 538 setOperationAction(ISD::TRUNCATE, VT, Custom); 539 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 540 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 541 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 542 543 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 544 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 545 546 setOperationAction(ISD::SELECT, VT, Custom); 547 setOperationAction(ISD::SELECT_CC, VT, Expand); 548 setOperationAction(ISD::VSELECT, VT, Expand); 549 550 setOperationAction(ISD::VP_AND, VT, Custom); 551 setOperationAction(ISD::VP_OR, VT, Custom); 552 setOperationAction(ISD::VP_XOR, VT, Custom); 553 554 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 555 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 556 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 557 558 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 559 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 560 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 561 562 // RVV has native int->float & float->int conversions where the 563 // element type sizes are within one power-of-two of each other. Any 564 // wider distances between type sizes have to be lowered as sequences 565 // which progressively narrow the gap in stages. 566 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 567 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 568 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 569 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 570 571 // Expand all extending loads to types larger than this, and truncating 572 // stores from types larger than this. 573 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 574 setTruncStoreAction(OtherVT, VT, Expand); 575 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 576 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 577 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 578 } 579 } 580 581 for (MVT VT : IntVecVTs) { 582 if (VT.getVectorElementType() == MVT::i64 && 583 !Subtarget.hasVInstructionsI64()) 584 continue; 585 586 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 587 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 588 589 // Vectors implement MULHS/MULHU. 590 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 591 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 592 593 setOperationAction(ISD::SMIN, VT, Legal); 594 setOperationAction(ISD::SMAX, VT, Legal); 595 setOperationAction(ISD::UMIN, VT, Legal); 596 setOperationAction(ISD::UMAX, VT, Legal); 597 598 setOperationAction(ISD::ROTL, VT, Expand); 599 setOperationAction(ISD::ROTR, VT, Expand); 600 601 setOperationAction(ISD::CTTZ, VT, Expand); 602 setOperationAction(ISD::CTLZ, VT, Expand); 603 setOperationAction(ISD::CTPOP, VT, Expand); 604 605 setOperationAction(ISD::BSWAP, VT, Expand); 606 607 // Custom-lower extensions and truncations from/to mask types. 608 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 609 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 610 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 611 612 // RVV has native int->float & float->int conversions where the 613 // element type sizes are within one power-of-two of each other. Any 614 // wider distances between type sizes have to be lowered as sequences 615 // which progressively narrow the gap in stages. 616 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 617 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 618 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 619 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 620 621 setOperationAction(ISD::SADDSAT, VT, Legal); 622 setOperationAction(ISD::UADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::USUBSAT, VT, Legal); 625 626 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 627 // nodes which truncate by one power of two at a time. 628 setOperationAction(ISD::TRUNCATE, VT, Custom); 629 630 // Custom-lower insert/extract operations to simplify patterns. 631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 633 634 // Custom-lower reduction operations to set up the corresponding custom 635 // nodes' operands. 636 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 637 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 638 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 639 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 640 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 641 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 642 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 643 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 644 645 for (unsigned VPOpc : IntegerVPOps) 646 setOperationAction(VPOpc, VT, Custom); 647 648 setOperationAction(ISD::LOAD, VT, Custom); 649 setOperationAction(ISD::STORE, VT, Custom); 650 651 setOperationAction(ISD::MLOAD, VT, Custom); 652 setOperationAction(ISD::MSTORE, VT, Custom); 653 setOperationAction(ISD::MGATHER, VT, Custom); 654 setOperationAction(ISD::MSCATTER, VT, Custom); 655 656 setOperationAction(ISD::VP_LOAD, VT, Custom); 657 setOperationAction(ISD::VP_STORE, VT, Custom); 658 setOperationAction(ISD::VP_GATHER, VT, Custom); 659 setOperationAction(ISD::VP_SCATTER, VT, Custom); 660 661 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 662 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 663 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 664 665 setOperationAction(ISD::SELECT, VT, Custom); 666 setOperationAction(ISD::SELECT_CC, VT, Expand); 667 668 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 669 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 670 671 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 672 setTruncStoreAction(VT, OtherVT, Expand); 673 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 674 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 675 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 676 } 677 678 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 679 // type that can represent the value exactly. 680 if (VT.getVectorElementType() != MVT::i64) { 681 MVT FloatEltVT = 682 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 683 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 684 if (isTypeLegal(FloatVT)) { 685 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 686 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 687 } 688 } 689 } 690 691 // Expand various CCs to best match the RVV ISA, which natively supports UNE 692 // but no other unordered comparisons, and supports all ordered comparisons 693 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 694 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 695 // and we pattern-match those back to the "original", swapping operands once 696 // more. This way we catch both operations and both "vf" and "fv" forms with 697 // fewer patterns. 698 static const ISD::CondCode VFPCCToExpand[] = { 699 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 700 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 701 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 702 }; 703 704 // Sets common operation actions on RVV floating-point vector types. 705 const auto SetCommonVFPActions = [&](MVT VT) { 706 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 707 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 708 // sizes are within one power-of-two of each other. Therefore conversions 709 // between vXf16 and vXf64 must be lowered as sequences which convert via 710 // vXf32. 711 setOperationAction(ISD::FP_ROUND, VT, Custom); 712 setOperationAction(ISD::FP_EXTEND, VT, Custom); 713 // Custom-lower insert/extract operations to simplify patterns. 714 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 716 // Expand various condition codes (explained above). 717 for (auto CC : VFPCCToExpand) 718 setCondCodeAction(CC, VT, Expand); 719 720 setOperationAction(ISD::FMINNUM, VT, Legal); 721 setOperationAction(ISD::FMAXNUM, VT, Legal); 722 723 setOperationAction(ISD::FTRUNC, VT, Custom); 724 setOperationAction(ISD::FCEIL, VT, Custom); 725 setOperationAction(ISD::FFLOOR, VT, Custom); 726 727 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 728 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 729 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 730 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 731 732 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 733 734 setOperationAction(ISD::LOAD, VT, Custom); 735 setOperationAction(ISD::STORE, VT, Custom); 736 737 setOperationAction(ISD::MLOAD, VT, Custom); 738 setOperationAction(ISD::MSTORE, VT, Custom); 739 setOperationAction(ISD::MGATHER, VT, Custom); 740 setOperationAction(ISD::MSCATTER, VT, Custom); 741 742 setOperationAction(ISD::VP_LOAD, VT, Custom); 743 setOperationAction(ISD::VP_STORE, VT, Custom); 744 setOperationAction(ISD::VP_GATHER, VT, Custom); 745 setOperationAction(ISD::VP_SCATTER, VT, Custom); 746 747 setOperationAction(ISD::SELECT, VT, Custom); 748 setOperationAction(ISD::SELECT_CC, VT, Expand); 749 750 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 751 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 752 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 753 754 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 755 756 for (unsigned VPOpc : FloatingPointVPOps) 757 setOperationAction(VPOpc, VT, Custom); 758 }; 759 760 // Sets common extload/truncstore actions on RVV floating-point vector 761 // types. 762 const auto SetCommonVFPExtLoadTruncStoreActions = 763 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 764 for (auto SmallVT : SmallerVTs) { 765 setTruncStoreAction(VT, SmallVT, Expand); 766 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 767 } 768 }; 769 770 if (Subtarget.hasVInstructionsF16()) 771 for (MVT VT : F16VecVTs) 772 SetCommonVFPActions(VT); 773 774 for (MVT VT : F32VecVTs) { 775 if (Subtarget.hasVInstructionsF32()) 776 SetCommonVFPActions(VT); 777 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 778 } 779 780 for (MVT VT : F64VecVTs) { 781 if (Subtarget.hasVInstructionsF64()) 782 SetCommonVFPActions(VT); 783 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 784 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 785 } 786 787 if (Subtarget.useRVVForFixedLengthVectors()) { 788 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 789 if (!useRVVForFixedLengthVectorVT(VT)) 790 continue; 791 792 // By default everything must be expanded. 793 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 794 setOperationAction(Op, VT, Expand); 795 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 796 setTruncStoreAction(VT, OtherVT, Expand); 797 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 798 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 799 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 800 } 801 802 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 803 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 804 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 805 806 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 807 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 808 809 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 811 812 setOperationAction(ISD::LOAD, VT, Custom); 813 setOperationAction(ISD::STORE, VT, Custom); 814 815 setOperationAction(ISD::SETCC, VT, Custom); 816 817 setOperationAction(ISD::SELECT, VT, Custom); 818 819 setOperationAction(ISD::TRUNCATE, VT, Custom); 820 821 setOperationAction(ISD::BITCAST, VT, Custom); 822 823 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 824 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 825 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 826 827 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 828 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 829 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 830 831 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 832 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 833 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 834 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 835 836 // Operations below are different for between masks and other vectors. 837 if (VT.getVectorElementType() == MVT::i1) { 838 setOperationAction(ISD::VP_AND, VT, Custom); 839 setOperationAction(ISD::VP_OR, VT, Custom); 840 setOperationAction(ISD::VP_XOR, VT, Custom); 841 setOperationAction(ISD::AND, VT, Custom); 842 setOperationAction(ISD::OR, VT, Custom); 843 setOperationAction(ISD::XOR, VT, Custom); 844 continue; 845 } 846 847 // Use SPLAT_VECTOR to prevent type legalization from destroying the 848 // splats when type legalizing i64 scalar on RV32. 849 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 850 // improvements first. 851 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 852 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 853 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 854 } 855 856 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 857 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 858 859 setOperationAction(ISD::MLOAD, VT, Custom); 860 setOperationAction(ISD::MSTORE, VT, Custom); 861 setOperationAction(ISD::MGATHER, VT, Custom); 862 setOperationAction(ISD::MSCATTER, VT, Custom); 863 864 setOperationAction(ISD::VP_LOAD, VT, Custom); 865 setOperationAction(ISD::VP_STORE, VT, Custom); 866 setOperationAction(ISD::VP_GATHER, VT, Custom); 867 setOperationAction(ISD::VP_SCATTER, VT, Custom); 868 869 setOperationAction(ISD::ADD, VT, Custom); 870 setOperationAction(ISD::MUL, VT, Custom); 871 setOperationAction(ISD::SUB, VT, Custom); 872 setOperationAction(ISD::AND, VT, Custom); 873 setOperationAction(ISD::OR, VT, Custom); 874 setOperationAction(ISD::XOR, VT, Custom); 875 setOperationAction(ISD::SDIV, VT, Custom); 876 setOperationAction(ISD::SREM, VT, Custom); 877 setOperationAction(ISD::UDIV, VT, Custom); 878 setOperationAction(ISD::UREM, VT, Custom); 879 setOperationAction(ISD::SHL, VT, Custom); 880 setOperationAction(ISD::SRA, VT, Custom); 881 setOperationAction(ISD::SRL, VT, Custom); 882 883 setOperationAction(ISD::SMIN, VT, Custom); 884 setOperationAction(ISD::SMAX, VT, Custom); 885 setOperationAction(ISD::UMIN, VT, Custom); 886 setOperationAction(ISD::UMAX, VT, Custom); 887 setOperationAction(ISD::ABS, VT, Custom); 888 889 setOperationAction(ISD::MULHS, VT, Custom); 890 setOperationAction(ISD::MULHU, VT, Custom); 891 892 setOperationAction(ISD::SADDSAT, VT, Custom); 893 setOperationAction(ISD::UADDSAT, VT, Custom); 894 setOperationAction(ISD::SSUBSAT, VT, Custom); 895 setOperationAction(ISD::USUBSAT, VT, Custom); 896 897 setOperationAction(ISD::VSELECT, VT, Custom); 898 setOperationAction(ISD::SELECT_CC, VT, Expand); 899 900 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 901 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 902 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 903 904 // Custom-lower reduction operations to set up the corresponding custom 905 // nodes' operands. 906 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 907 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 908 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 909 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 910 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 911 912 for (unsigned VPOpc : IntegerVPOps) 913 setOperationAction(VPOpc, VT, Custom); 914 915 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 916 // type that can represent the value exactly. 917 if (VT.getVectorElementType() != MVT::i64) { 918 MVT FloatEltVT = 919 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 920 EVT FloatVT = 921 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 922 if (isTypeLegal(FloatVT)) { 923 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 924 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 925 } 926 } 927 } 928 929 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 930 if (!useRVVForFixedLengthVectorVT(VT)) 931 continue; 932 933 // By default everything must be expanded. 934 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 935 setOperationAction(Op, VT, Expand); 936 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 937 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 938 setTruncStoreAction(VT, OtherVT, Expand); 939 } 940 941 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 942 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 943 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 944 945 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 946 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 947 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 948 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 949 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 950 951 setOperationAction(ISD::LOAD, VT, Custom); 952 setOperationAction(ISD::STORE, VT, Custom); 953 setOperationAction(ISD::MLOAD, VT, Custom); 954 setOperationAction(ISD::MSTORE, VT, Custom); 955 setOperationAction(ISD::MGATHER, VT, Custom); 956 setOperationAction(ISD::MSCATTER, VT, Custom); 957 958 setOperationAction(ISD::VP_LOAD, VT, Custom); 959 setOperationAction(ISD::VP_STORE, VT, Custom); 960 setOperationAction(ISD::VP_GATHER, VT, Custom); 961 setOperationAction(ISD::VP_SCATTER, VT, Custom); 962 963 setOperationAction(ISD::FADD, VT, Custom); 964 setOperationAction(ISD::FSUB, VT, Custom); 965 setOperationAction(ISD::FMUL, VT, Custom); 966 setOperationAction(ISD::FDIV, VT, Custom); 967 setOperationAction(ISD::FNEG, VT, Custom); 968 setOperationAction(ISD::FABS, VT, Custom); 969 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 970 setOperationAction(ISD::FSQRT, VT, Custom); 971 setOperationAction(ISD::FMA, VT, Custom); 972 setOperationAction(ISD::FMINNUM, VT, Custom); 973 setOperationAction(ISD::FMAXNUM, VT, Custom); 974 975 setOperationAction(ISD::FP_ROUND, VT, Custom); 976 setOperationAction(ISD::FP_EXTEND, VT, Custom); 977 978 setOperationAction(ISD::FTRUNC, VT, Custom); 979 setOperationAction(ISD::FCEIL, VT, Custom); 980 setOperationAction(ISD::FFLOOR, VT, Custom); 981 982 for (auto CC : VFPCCToExpand) 983 setCondCodeAction(CC, VT, Expand); 984 985 setOperationAction(ISD::VSELECT, VT, Custom); 986 setOperationAction(ISD::SELECT, VT, Custom); 987 setOperationAction(ISD::SELECT_CC, VT, Expand); 988 989 setOperationAction(ISD::BITCAST, VT, Custom); 990 991 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 992 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 993 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 994 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 995 996 for (unsigned VPOpc : FloatingPointVPOps) 997 setOperationAction(VPOpc, VT, Custom); 998 } 999 1000 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1001 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1002 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1003 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1004 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1005 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1006 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1007 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1008 } 1009 } 1010 1011 // Function alignments. 1012 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1013 setMinFunctionAlignment(FunctionAlignment); 1014 setPrefFunctionAlignment(FunctionAlignment); 1015 1016 setMinimumJumpTableEntries(5); 1017 1018 // Jumps are expensive, compared to logic 1019 setJumpIsExpensive(); 1020 1021 setTargetDAGCombine(ISD::ADD); 1022 setTargetDAGCombine(ISD::SUB); 1023 setTargetDAGCombine(ISD::AND); 1024 setTargetDAGCombine(ISD::OR); 1025 setTargetDAGCombine(ISD::XOR); 1026 setTargetDAGCombine(ISD::ANY_EXTEND); 1027 setTargetDAGCombine(ISD::ZERO_EXTEND); 1028 if (Subtarget.hasVInstructions()) { 1029 setTargetDAGCombine(ISD::FCOPYSIGN); 1030 setTargetDAGCombine(ISD::MGATHER); 1031 setTargetDAGCombine(ISD::MSCATTER); 1032 setTargetDAGCombine(ISD::VP_GATHER); 1033 setTargetDAGCombine(ISD::VP_SCATTER); 1034 setTargetDAGCombine(ISD::SRA); 1035 setTargetDAGCombine(ISD::SRL); 1036 setTargetDAGCombine(ISD::SHL); 1037 setTargetDAGCombine(ISD::STORE); 1038 } 1039 } 1040 1041 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1042 LLVMContext &Context, 1043 EVT VT) const { 1044 if (!VT.isVector()) 1045 return getPointerTy(DL); 1046 if (Subtarget.hasVInstructions() && 1047 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1048 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1049 return VT.changeVectorElementTypeToInteger(); 1050 } 1051 1052 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1053 return Subtarget.getXLenVT(); 1054 } 1055 1056 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1057 const CallInst &I, 1058 MachineFunction &MF, 1059 unsigned Intrinsic) const { 1060 auto &DL = I.getModule()->getDataLayout(); 1061 switch (Intrinsic) { 1062 default: 1063 return false; 1064 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1065 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1066 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1067 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1068 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1069 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1070 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1071 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1072 case Intrinsic::riscv_masked_cmpxchg_i32: { 1073 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 1074 Info.opc = ISD::INTRINSIC_W_CHAIN; 1075 Info.memVT = MVT::getVT(PtrTy->getElementType()); 1076 Info.ptrVal = I.getArgOperand(0); 1077 Info.offset = 0; 1078 Info.align = Align(4); 1079 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1080 MachineMemOperand::MOVolatile; 1081 return true; 1082 } 1083 case Intrinsic::riscv_masked_strided_load: 1084 Info.opc = ISD::INTRINSIC_W_CHAIN; 1085 Info.ptrVal = I.getArgOperand(1); 1086 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1087 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1088 Info.size = MemoryLocation::UnknownSize; 1089 Info.flags |= MachineMemOperand::MOLoad; 1090 return true; 1091 case Intrinsic::riscv_masked_strided_store: 1092 Info.opc = ISD::INTRINSIC_VOID; 1093 Info.ptrVal = I.getArgOperand(1); 1094 Info.memVT = 1095 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1096 Info.align = Align( 1097 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1098 8); 1099 Info.size = MemoryLocation::UnknownSize; 1100 Info.flags |= MachineMemOperand::MOStore; 1101 return true; 1102 } 1103 } 1104 1105 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1106 const AddrMode &AM, Type *Ty, 1107 unsigned AS, 1108 Instruction *I) const { 1109 // No global is ever allowed as a base. 1110 if (AM.BaseGV) 1111 return false; 1112 1113 // Require a 12-bit signed offset. 1114 if (!isInt<12>(AM.BaseOffs)) 1115 return false; 1116 1117 switch (AM.Scale) { 1118 case 0: // "r+i" or just "i", depending on HasBaseReg. 1119 break; 1120 case 1: 1121 if (!AM.HasBaseReg) // allow "r+i". 1122 break; 1123 return false; // disallow "r+r" or "r+r+i". 1124 default: 1125 return false; 1126 } 1127 1128 return true; 1129 } 1130 1131 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1132 return isInt<12>(Imm); 1133 } 1134 1135 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1136 return isInt<12>(Imm); 1137 } 1138 1139 // On RV32, 64-bit integers are split into their high and low parts and held 1140 // in two different registers, so the trunc is free since the low register can 1141 // just be used. 1142 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1143 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1144 return false; 1145 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1146 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1147 return (SrcBits == 64 && DestBits == 32); 1148 } 1149 1150 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1151 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1152 !SrcVT.isInteger() || !DstVT.isInteger()) 1153 return false; 1154 unsigned SrcBits = SrcVT.getSizeInBits(); 1155 unsigned DestBits = DstVT.getSizeInBits(); 1156 return (SrcBits == 64 && DestBits == 32); 1157 } 1158 1159 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1160 // Zexts are free if they can be combined with a load. 1161 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1162 EVT MemVT = LD->getMemoryVT(); 1163 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1164 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1165 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1166 LD->getExtensionType() == ISD::ZEXTLOAD)) 1167 return true; 1168 } 1169 1170 return TargetLowering::isZExtFree(Val, VT2); 1171 } 1172 1173 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1174 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1175 } 1176 1177 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1178 return Subtarget.hasStdExtZbb(); 1179 } 1180 1181 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1182 return Subtarget.hasStdExtZbb(); 1183 } 1184 1185 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1186 EVT VT = Y.getValueType(); 1187 1188 // FIXME: Support vectors once we have tests. 1189 if (VT.isVector()) 1190 return false; 1191 1192 return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y); 1193 } 1194 1195 /// Check if sinking \p I's operands to I's basic block is profitable, because 1196 /// the operands can be folded into a target instruction, e.g. 1197 /// splats of scalars can fold into vector instructions. 1198 bool RISCVTargetLowering::shouldSinkOperands( 1199 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1200 using namespace llvm::PatternMatch; 1201 1202 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1203 return false; 1204 1205 auto IsSinker = [&](Instruction *I, int Operand) { 1206 switch (I->getOpcode()) { 1207 case Instruction::Add: 1208 case Instruction::Sub: 1209 case Instruction::Mul: 1210 case Instruction::And: 1211 case Instruction::Or: 1212 case Instruction::Xor: 1213 case Instruction::FAdd: 1214 case Instruction::FSub: 1215 case Instruction::FMul: 1216 case Instruction::FDiv: 1217 case Instruction::ICmp: 1218 case Instruction::FCmp: 1219 return true; 1220 case Instruction::Shl: 1221 case Instruction::LShr: 1222 case Instruction::AShr: 1223 case Instruction::UDiv: 1224 case Instruction::SDiv: 1225 case Instruction::URem: 1226 case Instruction::SRem: 1227 return Operand == 1; 1228 case Instruction::Call: 1229 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1230 switch (II->getIntrinsicID()) { 1231 case Intrinsic::fma: 1232 return Operand == 0 || Operand == 1; 1233 default: 1234 return false; 1235 } 1236 } 1237 return false; 1238 default: 1239 return false; 1240 } 1241 }; 1242 1243 for (auto OpIdx : enumerate(I->operands())) { 1244 if (!IsSinker(I, OpIdx.index())) 1245 continue; 1246 1247 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1248 // Make sure we are not already sinking this operand 1249 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1250 continue; 1251 1252 // We are looking for a splat that can be sunk. 1253 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1254 m_Undef(), m_ZeroMask()))) 1255 continue; 1256 1257 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1258 // and vector registers 1259 for (Use &U : Op->uses()) { 1260 Instruction *Insn = cast<Instruction>(U.getUser()); 1261 if (!IsSinker(Insn, U.getOperandNo())) 1262 return false; 1263 } 1264 1265 Ops.push_back(&Op->getOperandUse(0)); 1266 Ops.push_back(&OpIdx.value()); 1267 } 1268 return true; 1269 } 1270 1271 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1272 bool ForCodeSize) const { 1273 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1274 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1275 return false; 1276 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1277 return false; 1278 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1279 return false; 1280 if (Imm.isNegZero()) 1281 return false; 1282 return Imm.isZero(); 1283 } 1284 1285 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1286 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1287 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1288 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1289 } 1290 1291 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1292 CallingConv::ID CC, 1293 EVT VT) const { 1294 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1295 // We might still end up using a GPR but that will be decided based on ABI. 1296 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1297 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1298 return MVT::f32; 1299 1300 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1301 } 1302 1303 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1304 CallingConv::ID CC, 1305 EVT VT) const { 1306 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1307 // We might still end up using a GPR but that will be decided based on ABI. 1308 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1309 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1310 return 1; 1311 1312 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1313 } 1314 1315 // Changes the condition code and swaps operands if necessary, so the SetCC 1316 // operation matches one of the comparisons supported directly by branches 1317 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1318 // with 1/-1. 1319 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1320 ISD::CondCode &CC, SelectionDAG &DAG) { 1321 // Convert X > -1 to X >= 0. 1322 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1323 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1324 CC = ISD::SETGE; 1325 return; 1326 } 1327 // Convert X < 1 to 0 >= X. 1328 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1329 RHS = LHS; 1330 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1331 CC = ISD::SETGE; 1332 return; 1333 } 1334 1335 switch (CC) { 1336 default: 1337 break; 1338 case ISD::SETGT: 1339 case ISD::SETLE: 1340 case ISD::SETUGT: 1341 case ISD::SETULE: 1342 CC = ISD::getSetCCSwappedOperands(CC); 1343 std::swap(LHS, RHS); 1344 break; 1345 } 1346 } 1347 1348 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1349 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1350 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1351 if (VT.getVectorElementType() == MVT::i1) 1352 KnownSize *= 8; 1353 1354 switch (KnownSize) { 1355 default: 1356 llvm_unreachable("Invalid LMUL."); 1357 case 8: 1358 return RISCVII::VLMUL::LMUL_F8; 1359 case 16: 1360 return RISCVII::VLMUL::LMUL_F4; 1361 case 32: 1362 return RISCVII::VLMUL::LMUL_F2; 1363 case 64: 1364 return RISCVII::VLMUL::LMUL_1; 1365 case 128: 1366 return RISCVII::VLMUL::LMUL_2; 1367 case 256: 1368 return RISCVII::VLMUL::LMUL_4; 1369 case 512: 1370 return RISCVII::VLMUL::LMUL_8; 1371 } 1372 } 1373 1374 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1375 switch (LMul) { 1376 default: 1377 llvm_unreachable("Invalid LMUL."); 1378 case RISCVII::VLMUL::LMUL_F8: 1379 case RISCVII::VLMUL::LMUL_F4: 1380 case RISCVII::VLMUL::LMUL_F2: 1381 case RISCVII::VLMUL::LMUL_1: 1382 return RISCV::VRRegClassID; 1383 case RISCVII::VLMUL::LMUL_2: 1384 return RISCV::VRM2RegClassID; 1385 case RISCVII::VLMUL::LMUL_4: 1386 return RISCV::VRM4RegClassID; 1387 case RISCVII::VLMUL::LMUL_8: 1388 return RISCV::VRM8RegClassID; 1389 } 1390 } 1391 1392 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1393 RISCVII::VLMUL LMUL = getLMUL(VT); 1394 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1395 LMUL == RISCVII::VLMUL::LMUL_F4 || 1396 LMUL == RISCVII::VLMUL::LMUL_F2 || 1397 LMUL == RISCVII::VLMUL::LMUL_1) { 1398 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1399 "Unexpected subreg numbering"); 1400 return RISCV::sub_vrm1_0 + Index; 1401 } 1402 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1403 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1404 "Unexpected subreg numbering"); 1405 return RISCV::sub_vrm2_0 + Index; 1406 } 1407 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1408 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1409 "Unexpected subreg numbering"); 1410 return RISCV::sub_vrm4_0 + Index; 1411 } 1412 llvm_unreachable("Invalid vector type."); 1413 } 1414 1415 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1416 if (VT.getVectorElementType() == MVT::i1) 1417 return RISCV::VRRegClassID; 1418 return getRegClassIDForLMUL(getLMUL(VT)); 1419 } 1420 1421 // Attempt to decompose a subvector insert/extract between VecVT and 1422 // SubVecVT via subregister indices. Returns the subregister index that 1423 // can perform the subvector insert/extract with the given element index, as 1424 // well as the index corresponding to any leftover subvectors that must be 1425 // further inserted/extracted within the register class for SubVecVT. 1426 std::pair<unsigned, unsigned> 1427 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1428 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1429 const RISCVRegisterInfo *TRI) { 1430 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1431 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1432 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1433 "Register classes not ordered"); 1434 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1435 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1436 // Try to compose a subregister index that takes us from the incoming 1437 // LMUL>1 register class down to the outgoing one. At each step we half 1438 // the LMUL: 1439 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1440 // Note that this is not guaranteed to find a subregister index, such as 1441 // when we are extracting from one VR type to another. 1442 unsigned SubRegIdx = RISCV::NoSubRegister; 1443 for (const unsigned RCID : 1444 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1445 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1446 VecVT = VecVT.getHalfNumVectorElementsVT(); 1447 bool IsHi = 1448 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1449 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1450 getSubregIndexByMVT(VecVT, IsHi)); 1451 if (IsHi) 1452 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1453 } 1454 return {SubRegIdx, InsertExtractIdx}; 1455 } 1456 1457 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1458 // stores for those types. 1459 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1460 return !Subtarget.useRVVForFixedLengthVectors() || 1461 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1462 } 1463 1464 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1465 if (ScalarTy->isPointerTy()) 1466 return true; 1467 1468 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1469 ScalarTy->isIntegerTy(32)) 1470 return true; 1471 1472 if (ScalarTy->isIntegerTy(64)) 1473 return Subtarget.hasVInstructionsI64(); 1474 1475 if (ScalarTy->isHalfTy()) 1476 return Subtarget.hasVInstructionsF16(); 1477 if (ScalarTy->isFloatTy()) 1478 return Subtarget.hasVInstructionsF32(); 1479 if (ScalarTy->isDoubleTy()) 1480 return Subtarget.hasVInstructionsF64(); 1481 1482 return false; 1483 } 1484 1485 static bool useRVVForFixedLengthVectorVT(MVT VT, 1486 const RISCVSubtarget &Subtarget) { 1487 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1488 if (!Subtarget.useRVVForFixedLengthVectors()) 1489 return false; 1490 1491 // We only support a set of vector types with a consistent maximum fixed size 1492 // across all supported vector element types to avoid legalization issues. 1493 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1494 // fixed-length vector type we support is 1024 bytes. 1495 if (VT.getFixedSizeInBits() > 1024 * 8) 1496 return false; 1497 1498 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1499 1500 MVT EltVT = VT.getVectorElementType(); 1501 1502 // Don't use RVV for vectors we cannot scalarize if required. 1503 switch (EltVT.SimpleTy) { 1504 // i1 is supported but has different rules. 1505 default: 1506 return false; 1507 case MVT::i1: 1508 // Masks can only use a single register. 1509 if (VT.getVectorNumElements() > MinVLen) 1510 return false; 1511 MinVLen /= 8; 1512 break; 1513 case MVT::i8: 1514 case MVT::i16: 1515 case MVT::i32: 1516 break; 1517 case MVT::i64: 1518 if (!Subtarget.hasVInstructionsI64()) 1519 return false; 1520 break; 1521 case MVT::f16: 1522 if (!Subtarget.hasVInstructionsF16()) 1523 return false; 1524 break; 1525 case MVT::f32: 1526 if (!Subtarget.hasVInstructionsF32()) 1527 return false; 1528 break; 1529 case MVT::f64: 1530 if (!Subtarget.hasVInstructionsF64()) 1531 return false; 1532 break; 1533 } 1534 1535 // Reject elements larger than ELEN. 1536 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1537 return false; 1538 1539 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1540 // Don't use RVV for types that don't fit. 1541 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1542 return false; 1543 1544 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1545 // the base fixed length RVV support in place. 1546 if (!VT.isPow2VectorType()) 1547 return false; 1548 1549 return true; 1550 } 1551 1552 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1553 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1554 } 1555 1556 // Return the largest legal scalable vector type that matches VT's element type. 1557 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1558 const RISCVSubtarget &Subtarget) { 1559 // This may be called before legal types are setup. 1560 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1561 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1562 "Expected legal fixed length vector!"); 1563 1564 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1565 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1566 1567 MVT EltVT = VT.getVectorElementType(); 1568 switch (EltVT.SimpleTy) { 1569 default: 1570 llvm_unreachable("unexpected element type for RVV container"); 1571 case MVT::i1: 1572 case MVT::i8: 1573 case MVT::i16: 1574 case MVT::i32: 1575 case MVT::i64: 1576 case MVT::f16: 1577 case MVT::f32: 1578 case MVT::f64: { 1579 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1580 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1581 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1582 unsigned NumElts = 1583 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1584 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1585 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1586 return MVT::getScalableVectorVT(EltVT, NumElts); 1587 } 1588 } 1589 } 1590 1591 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1592 const RISCVSubtarget &Subtarget) { 1593 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1594 Subtarget); 1595 } 1596 1597 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1598 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1599 } 1600 1601 // Grow V to consume an entire RVV register. 1602 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1603 const RISCVSubtarget &Subtarget) { 1604 assert(VT.isScalableVector() && 1605 "Expected to convert into a scalable vector!"); 1606 assert(V.getValueType().isFixedLengthVector() && 1607 "Expected a fixed length vector operand!"); 1608 SDLoc DL(V); 1609 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1610 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1611 } 1612 1613 // Shrink V so it's just big enough to maintain a VT's worth of data. 1614 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1615 const RISCVSubtarget &Subtarget) { 1616 assert(VT.isFixedLengthVector() && 1617 "Expected to convert into a fixed length vector!"); 1618 assert(V.getValueType().isScalableVector() && 1619 "Expected a scalable vector operand!"); 1620 SDLoc DL(V); 1621 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1622 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1623 } 1624 1625 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1626 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1627 // the vector type that it is contained in. 1628 static std::pair<SDValue, SDValue> 1629 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1630 const RISCVSubtarget &Subtarget) { 1631 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1632 MVT XLenVT = Subtarget.getXLenVT(); 1633 SDValue VL = VecVT.isFixedLengthVector() 1634 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1635 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1636 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1637 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1638 return {Mask, VL}; 1639 } 1640 1641 // As above but assuming the given type is a scalable vector type. 1642 static std::pair<SDValue, SDValue> 1643 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1644 const RISCVSubtarget &Subtarget) { 1645 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1646 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1647 } 1648 1649 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1650 // of either is (currently) supported. This can get us into an infinite loop 1651 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1652 // as a ..., etc. 1653 // Until either (or both) of these can reliably lower any node, reporting that 1654 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1655 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1656 // which is not desirable. 1657 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1658 EVT VT, unsigned DefinedValues) const { 1659 return false; 1660 } 1661 1662 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1663 // Only splats are currently supported. 1664 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1665 return true; 1666 1667 return false; 1668 } 1669 1670 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1671 // RISCV FP-to-int conversions saturate to the destination register size, but 1672 // don't produce 0 for nan. We can use a conversion instruction and fix the 1673 // nan case with a compare and a select. 1674 SDValue Src = Op.getOperand(0); 1675 1676 EVT DstVT = Op.getValueType(); 1677 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1678 1679 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1680 unsigned Opc; 1681 if (SatVT == DstVT) 1682 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1683 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1684 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1685 else 1686 return SDValue(); 1687 // FIXME: Support other SatVTs by clamping before or after the conversion. 1688 1689 SDLoc DL(Op); 1690 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1691 1692 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1693 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1694 } 1695 1696 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1697 // and back. Taking care to avoid converting values that are nan or already 1698 // correct. 1699 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1700 // have FRM dependencies modeled yet. 1701 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1702 MVT VT = Op.getSimpleValueType(); 1703 assert(VT.isVector() && "Unexpected type"); 1704 1705 SDLoc DL(Op); 1706 1707 // Freeze the source since we are increasing the number of uses. 1708 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1709 1710 // Truncate to integer and convert back to FP. 1711 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1712 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1713 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1714 1715 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1716 1717 if (Op.getOpcode() == ISD::FCEIL) { 1718 // If the truncated value is the greater than or equal to the original 1719 // value, we've computed the ceil. Otherwise, we went the wrong way and 1720 // need to increase by 1. 1721 // FIXME: This should use a masked operation. Handle here or in isel? 1722 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1723 DAG.getConstantFP(1.0, DL, VT)); 1724 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1725 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1726 } else if (Op.getOpcode() == ISD::FFLOOR) { 1727 // If the truncated value is the less than or equal to the original value, 1728 // we've computed the floor. Otherwise, we went the wrong way and need to 1729 // decrease by 1. 1730 // FIXME: This should use a masked operation. Handle here or in isel? 1731 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1732 DAG.getConstantFP(1.0, DL, VT)); 1733 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1734 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1735 } 1736 1737 // Restore the original sign so that -0.0 is preserved. 1738 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1739 1740 // Determine the largest integer that can be represented exactly. This and 1741 // values larger than it don't have any fractional bits so don't need to 1742 // be converted. 1743 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1744 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1745 APFloat MaxVal = APFloat(FltSem); 1746 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1747 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1748 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1749 1750 // If abs(Src) was larger than MaxVal or nan, keep it. 1751 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1752 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1753 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1754 } 1755 1756 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1757 const RISCVSubtarget &Subtarget) { 1758 MVT VT = Op.getSimpleValueType(); 1759 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1760 1761 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1762 1763 SDLoc DL(Op); 1764 SDValue Mask, VL; 1765 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1766 1767 unsigned Opc = 1768 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1769 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1770 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1771 } 1772 1773 struct VIDSequence { 1774 int64_t StepNumerator; 1775 unsigned StepDenominator; 1776 int64_t Addend; 1777 }; 1778 1779 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1780 // to the (non-zero) step S and start value X. This can be then lowered as the 1781 // RVV sequence (VID * S) + X, for example. 1782 // The step S is represented as an integer numerator divided by a positive 1783 // denominator. Note that the implementation currently only identifies 1784 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1785 // cannot detect 2/3, for example. 1786 // Note that this method will also match potentially unappealing index 1787 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1788 // determine whether this is worth generating code for. 1789 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1790 unsigned NumElts = Op.getNumOperands(); 1791 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1792 if (!Op.getValueType().isInteger()) 1793 return None; 1794 1795 Optional<unsigned> SeqStepDenom; 1796 Optional<int64_t> SeqStepNum, SeqAddend; 1797 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1798 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1799 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1800 // Assume undef elements match the sequence; we just have to be careful 1801 // when interpolating across them. 1802 if (Op.getOperand(Idx).isUndef()) 1803 continue; 1804 // The BUILD_VECTOR must be all constants. 1805 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1806 return None; 1807 1808 uint64_t Val = Op.getConstantOperandVal(Idx) & 1809 maskTrailingOnes<uint64_t>(EltSizeInBits); 1810 1811 if (PrevElt) { 1812 // Calculate the step since the last non-undef element, and ensure 1813 // it's consistent across the entire sequence. 1814 unsigned IdxDiff = Idx - PrevElt->second; 1815 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1816 1817 // A zero-value value difference means that we're somewhere in the middle 1818 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1819 // step change before evaluating the sequence. 1820 if (ValDiff != 0) { 1821 int64_t Remainder = ValDiff % IdxDiff; 1822 // Normalize the step if it's greater than 1. 1823 if (Remainder != ValDiff) { 1824 // The difference must cleanly divide the element span. 1825 if (Remainder != 0) 1826 return None; 1827 ValDiff /= IdxDiff; 1828 IdxDiff = 1; 1829 } 1830 1831 if (!SeqStepNum) 1832 SeqStepNum = ValDiff; 1833 else if (ValDiff != SeqStepNum) 1834 return None; 1835 1836 if (!SeqStepDenom) 1837 SeqStepDenom = IdxDiff; 1838 else if (IdxDiff != *SeqStepDenom) 1839 return None; 1840 } 1841 } 1842 1843 // Record and/or check any addend. 1844 if (SeqStepNum && SeqStepDenom) { 1845 uint64_t ExpectedVal = 1846 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1847 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1848 if (!SeqAddend) 1849 SeqAddend = Addend; 1850 else if (SeqAddend != Addend) 1851 return None; 1852 } 1853 1854 // Record this non-undef element for later. 1855 if (!PrevElt || PrevElt->first != Val) 1856 PrevElt = std::make_pair(Val, Idx); 1857 } 1858 // We need to have logged both a step and an addend for this to count as 1859 // a legal index sequence. 1860 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1861 return None; 1862 1863 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1864 } 1865 1866 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1867 const RISCVSubtarget &Subtarget) { 1868 MVT VT = Op.getSimpleValueType(); 1869 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1870 1871 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1872 1873 SDLoc DL(Op); 1874 SDValue Mask, VL; 1875 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1876 1877 MVT XLenVT = Subtarget.getXLenVT(); 1878 unsigned NumElts = Op.getNumOperands(); 1879 1880 if (VT.getVectorElementType() == MVT::i1) { 1881 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1882 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1883 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1884 } 1885 1886 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1887 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1888 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1889 } 1890 1891 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1892 // scalar integer chunks whose bit-width depends on the number of mask 1893 // bits and XLEN. 1894 // First, determine the most appropriate scalar integer type to use. This 1895 // is at most XLenVT, but may be shrunk to a smaller vector element type 1896 // according to the size of the final vector - use i8 chunks rather than 1897 // XLenVT if we're producing a v8i1. This results in more consistent 1898 // codegen across RV32 and RV64. 1899 unsigned NumViaIntegerBits = 1900 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1901 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1902 // If we have to use more than one INSERT_VECTOR_ELT then this 1903 // optimization is likely to increase code size; avoid peforming it in 1904 // such a case. We can use a load from a constant pool in this case. 1905 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1906 return SDValue(); 1907 // Now we can create our integer vector type. Note that it may be larger 1908 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1909 MVT IntegerViaVecVT = 1910 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1911 divideCeil(NumElts, NumViaIntegerBits)); 1912 1913 uint64_t Bits = 0; 1914 unsigned BitPos = 0, IntegerEltIdx = 0; 1915 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1916 1917 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1918 // Once we accumulate enough bits to fill our scalar type, insert into 1919 // our vector and clear our accumulated data. 1920 if (I != 0 && I % NumViaIntegerBits == 0) { 1921 if (NumViaIntegerBits <= 32) 1922 Bits = SignExtend64(Bits, 32); 1923 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1924 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1925 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1926 Bits = 0; 1927 BitPos = 0; 1928 IntegerEltIdx++; 1929 } 1930 SDValue V = Op.getOperand(I); 1931 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1932 Bits |= ((uint64_t)BitValue << BitPos); 1933 } 1934 1935 // Insert the (remaining) scalar value into position in our integer 1936 // vector type. 1937 if (NumViaIntegerBits <= 32) 1938 Bits = SignExtend64(Bits, 32); 1939 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1940 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1941 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1942 1943 if (NumElts < NumViaIntegerBits) { 1944 // If we're producing a smaller vector than our minimum legal integer 1945 // type, bitcast to the equivalent (known-legal) mask type, and extract 1946 // our final mask. 1947 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1948 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1949 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1950 DAG.getConstant(0, DL, XLenVT)); 1951 } else { 1952 // Else we must have produced an integer type with the same size as the 1953 // mask type; bitcast for the final result. 1954 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1955 Vec = DAG.getBitcast(VT, Vec); 1956 } 1957 1958 return Vec; 1959 } 1960 1961 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1962 // vector type, we have a legal equivalently-sized i8 type, so we can use 1963 // that. 1964 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1965 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1966 1967 SDValue WideVec; 1968 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1969 // For a splat, perform a scalar truncate before creating the wider 1970 // vector. 1971 assert(Splat.getValueType() == XLenVT && 1972 "Unexpected type for i1 splat value"); 1973 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1974 DAG.getConstant(1, DL, XLenVT)); 1975 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1976 } else { 1977 SmallVector<SDValue, 8> Ops(Op->op_values()); 1978 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1979 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1980 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1981 } 1982 1983 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1984 } 1985 1986 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1987 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1988 : RISCVISD::VMV_V_X_VL; 1989 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1990 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1991 } 1992 1993 // Try and match index sequences, which we can lower to the vid instruction 1994 // with optional modifications. An all-undef vector is matched by 1995 // getSplatValue, above. 1996 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 1997 int64_t StepNumerator = SimpleVID->StepNumerator; 1998 unsigned StepDenominator = SimpleVID->StepDenominator; 1999 int64_t Addend = SimpleVID->Addend; 2000 2001 assert(StepNumerator != 0 && "Invalid step"); 2002 bool Negate = false; 2003 int64_t SplatStepVal = StepNumerator; 2004 unsigned StepOpcode = ISD::MUL; 2005 if (StepNumerator != 1) { 2006 if (isPowerOf2_64(std::abs(StepNumerator))) { 2007 Negate = StepNumerator < 0; 2008 StepOpcode = ISD::SHL; 2009 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2010 } 2011 } 2012 2013 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2014 // threshold since it's the immediate value many RVV instructions accept. 2015 // There is no vmul.vi instruction so ensure multiply constant can fit in 2016 // a single addi instruction. 2017 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2018 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2019 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2020 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2021 // Convert right out of the scalable type so we can use standard ISD 2022 // nodes for the rest of the computation. If we used scalable types with 2023 // these, we'd lose the fixed-length vector info and generate worse 2024 // vsetvli code. 2025 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2026 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2027 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2028 SDValue SplatStep = DAG.getSplatVector( 2029 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2030 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2031 } 2032 if (StepDenominator != 1) { 2033 SDValue SplatStep = DAG.getSplatVector( 2034 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2035 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2036 } 2037 if (Addend != 0 || Negate) { 2038 SDValue SplatAddend = 2039 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2040 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2041 } 2042 return VID; 2043 } 2044 } 2045 2046 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2047 // when re-interpreted as a vector with a larger element type. For example, 2048 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2049 // could be instead splat as 2050 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2051 // TODO: This optimization could also work on non-constant splats, but it 2052 // would require bit-manipulation instructions to construct the splat value. 2053 SmallVector<SDValue> Sequence; 2054 unsigned EltBitSize = VT.getScalarSizeInBits(); 2055 const auto *BV = cast<BuildVectorSDNode>(Op); 2056 if (VT.isInteger() && EltBitSize < 64 && 2057 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2058 BV->getRepeatedSequence(Sequence) && 2059 (Sequence.size() * EltBitSize) <= 64) { 2060 unsigned SeqLen = Sequence.size(); 2061 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2062 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2063 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2064 ViaIntVT == MVT::i64) && 2065 "Unexpected sequence type"); 2066 2067 unsigned EltIdx = 0; 2068 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2069 uint64_t SplatValue = 0; 2070 // Construct the amalgamated value which can be splatted as this larger 2071 // vector type. 2072 for (const auto &SeqV : Sequence) { 2073 if (!SeqV.isUndef()) 2074 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2075 << (EltIdx * EltBitSize)); 2076 EltIdx++; 2077 } 2078 2079 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2080 // achieve better constant materializion. 2081 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2082 SplatValue = SignExtend64(SplatValue, 32); 2083 2084 // Since we can't introduce illegal i64 types at this stage, we can only 2085 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2086 // way we can use RVV instructions to splat. 2087 assert((ViaIntVT.bitsLE(XLenVT) || 2088 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2089 "Unexpected bitcast sequence"); 2090 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2091 SDValue ViaVL = 2092 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2093 MVT ViaContainerVT = 2094 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2095 SDValue Splat = 2096 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2097 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2098 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2099 return DAG.getBitcast(VT, Splat); 2100 } 2101 } 2102 2103 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2104 // which constitute a large proportion of the elements. In such cases we can 2105 // splat a vector with the dominant element and make up the shortfall with 2106 // INSERT_VECTOR_ELTs. 2107 // Note that this includes vectors of 2 elements by association. The 2108 // upper-most element is the "dominant" one, allowing us to use a splat to 2109 // "insert" the upper element, and an insert of the lower element at position 2110 // 0, which improves codegen. 2111 SDValue DominantValue; 2112 unsigned MostCommonCount = 0; 2113 DenseMap<SDValue, unsigned> ValueCounts; 2114 unsigned NumUndefElts = 2115 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2116 2117 // Track the number of scalar loads we know we'd be inserting, estimated as 2118 // any non-zero floating-point constant. Other kinds of element are either 2119 // already in registers or are materialized on demand. The threshold at which 2120 // a vector load is more desirable than several scalar materializion and 2121 // vector-insertion instructions is not known. 2122 unsigned NumScalarLoads = 0; 2123 2124 for (SDValue V : Op->op_values()) { 2125 if (V.isUndef()) 2126 continue; 2127 2128 ValueCounts.insert(std::make_pair(V, 0)); 2129 unsigned &Count = ValueCounts[V]; 2130 2131 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2132 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2133 2134 // Is this value dominant? In case of a tie, prefer the highest element as 2135 // it's cheaper to insert near the beginning of a vector than it is at the 2136 // end. 2137 if (++Count >= MostCommonCount) { 2138 DominantValue = V; 2139 MostCommonCount = Count; 2140 } 2141 } 2142 2143 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2144 unsigned NumDefElts = NumElts - NumUndefElts; 2145 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2146 2147 // Don't perform this optimization when optimizing for size, since 2148 // materializing elements and inserting them tends to cause code bloat. 2149 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2150 ((MostCommonCount > DominantValueCountThreshold) || 2151 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2152 // Start by splatting the most common element. 2153 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2154 2155 DenseSet<SDValue> Processed{DominantValue}; 2156 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2157 for (const auto &OpIdx : enumerate(Op->ops())) { 2158 const SDValue &V = OpIdx.value(); 2159 if (V.isUndef() || !Processed.insert(V).second) 2160 continue; 2161 if (ValueCounts[V] == 1) { 2162 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2163 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2164 } else { 2165 // Blend in all instances of this value using a VSELECT, using a 2166 // mask where each bit signals whether that element is the one 2167 // we're after. 2168 SmallVector<SDValue> Ops; 2169 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2170 return DAG.getConstant(V == V1, DL, XLenVT); 2171 }); 2172 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2173 DAG.getBuildVector(SelMaskTy, DL, Ops), 2174 DAG.getSplatBuildVector(VT, DL, V), Vec); 2175 } 2176 } 2177 2178 return Vec; 2179 } 2180 2181 return SDValue(); 2182 } 2183 2184 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2185 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2186 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2187 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2188 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2189 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2190 // node in order to try and match RVV vector/scalar instructions. 2191 if ((LoC >> 31) == HiC) 2192 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2193 } 2194 2195 // Fall back to a stack store and stride x0 vector load. 2196 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2197 } 2198 2199 // Called by type legalization to handle splat of i64 on RV32. 2200 // FIXME: We can optimize this when the type has sign or zero bits in one 2201 // of the halves. 2202 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2203 SDValue VL, SelectionDAG &DAG) { 2204 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2205 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2206 DAG.getConstant(0, DL, MVT::i32)); 2207 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2208 DAG.getConstant(1, DL, MVT::i32)); 2209 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2210 } 2211 2212 // This function lowers a splat of a scalar operand Splat with the vector 2213 // length VL. It ensures the final sequence is type legal, which is useful when 2214 // lowering a splat after type legalization. 2215 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2216 SelectionDAG &DAG, 2217 const RISCVSubtarget &Subtarget) { 2218 if (VT.isFloatingPoint()) 2219 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2220 2221 MVT XLenVT = Subtarget.getXLenVT(); 2222 2223 // Simplest case is that the operand needs to be promoted to XLenVT. 2224 if (Scalar.getValueType().bitsLE(XLenVT)) { 2225 // If the operand is a constant, sign extend to increase our chances 2226 // of being able to use a .vi instruction. ANY_EXTEND would become a 2227 // a zero extend and the simm5 check in isel would fail. 2228 // FIXME: Should we ignore the upper bits in isel instead? 2229 unsigned ExtOpc = 2230 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2231 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2232 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2233 } 2234 2235 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2236 "Unexpected scalar for splat lowering!"); 2237 2238 // Otherwise use the more complicated splatting algorithm. 2239 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2240 } 2241 2242 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2243 const RISCVSubtarget &Subtarget) { 2244 SDValue V1 = Op.getOperand(0); 2245 SDValue V2 = Op.getOperand(1); 2246 SDLoc DL(Op); 2247 MVT XLenVT = Subtarget.getXLenVT(); 2248 MVT VT = Op.getSimpleValueType(); 2249 unsigned NumElts = VT.getVectorNumElements(); 2250 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2251 2252 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2253 2254 SDValue TrueMask, VL; 2255 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2256 2257 if (SVN->isSplat()) { 2258 const int Lane = SVN->getSplatIndex(); 2259 if (Lane >= 0) { 2260 MVT SVT = VT.getVectorElementType(); 2261 2262 // Turn splatted vector load into a strided load with an X0 stride. 2263 SDValue V = V1; 2264 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2265 // with undef. 2266 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2267 int Offset = Lane; 2268 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2269 int OpElements = 2270 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2271 V = V.getOperand(Offset / OpElements); 2272 Offset %= OpElements; 2273 } 2274 2275 // We need to ensure the load isn't atomic or volatile. 2276 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2277 auto *Ld = cast<LoadSDNode>(V); 2278 Offset *= SVT.getStoreSize(); 2279 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2280 TypeSize::Fixed(Offset), DL); 2281 2282 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2283 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2284 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2285 SDValue IntID = 2286 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2287 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2288 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2289 SDValue NewLoad = DAG.getMemIntrinsicNode( 2290 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2291 DAG.getMachineFunction().getMachineMemOperand( 2292 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2293 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2294 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2295 } 2296 2297 // Otherwise use a scalar load and splat. This will give the best 2298 // opportunity to fold a splat into the operation. ISel can turn it into 2299 // the x0 strided load if we aren't able to fold away the select. 2300 if (SVT.isFloatingPoint()) 2301 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2302 Ld->getPointerInfo().getWithOffset(Offset), 2303 Ld->getOriginalAlign(), 2304 Ld->getMemOperand()->getFlags()); 2305 else 2306 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2307 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2308 Ld->getOriginalAlign(), 2309 Ld->getMemOperand()->getFlags()); 2310 DAG.makeEquivalentMemoryOrdering(Ld, V); 2311 2312 unsigned Opc = 2313 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2314 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2315 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2316 } 2317 2318 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2319 assert(Lane < (int)NumElts && "Unexpected lane!"); 2320 SDValue Gather = 2321 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2322 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2323 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2324 } 2325 } 2326 2327 // Detect shuffles which can be re-expressed as vector selects; these are 2328 // shuffles in which each element in the destination is taken from an element 2329 // at the corresponding index in either source vectors. 2330 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2331 int MaskIndex = MaskIdx.value(); 2332 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2333 }); 2334 2335 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2336 2337 SmallVector<SDValue> MaskVals; 2338 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2339 // merged with a second vrgather. 2340 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2341 2342 // By default we preserve the original operand order, and use a mask to 2343 // select LHS as true and RHS as false. However, since RVV vector selects may 2344 // feature splats but only on the LHS, we may choose to invert our mask and 2345 // instead select between RHS and LHS. 2346 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2347 bool InvertMask = IsSelect == SwapOps; 2348 2349 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2350 // half. 2351 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2352 2353 // Now construct the mask that will be used by the vselect or blended 2354 // vrgather operation. For vrgathers, construct the appropriate indices into 2355 // each vector. 2356 for (int MaskIndex : SVN->getMask()) { 2357 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2358 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2359 if (!IsSelect) { 2360 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2361 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2362 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2363 : DAG.getUNDEF(XLenVT)); 2364 GatherIndicesRHS.push_back( 2365 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2366 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2367 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2368 ++LHSIndexCounts[MaskIndex]; 2369 if (!IsLHSOrUndefIndex) 2370 ++RHSIndexCounts[MaskIndex - NumElts]; 2371 } 2372 } 2373 2374 if (SwapOps) { 2375 std::swap(V1, V2); 2376 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2377 } 2378 2379 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2380 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2381 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2382 2383 if (IsSelect) 2384 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2385 2386 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2387 // On such a large vector we're unable to use i8 as the index type. 2388 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2389 // may involve vector splitting if we're already at LMUL=8, or our 2390 // user-supplied maximum fixed-length LMUL. 2391 return SDValue(); 2392 } 2393 2394 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2395 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2396 MVT IndexVT = VT.changeTypeToInteger(); 2397 // Since we can't introduce illegal index types at this stage, use i16 and 2398 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2399 // than XLenVT. 2400 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2401 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2402 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2403 } 2404 2405 MVT IndexContainerVT = 2406 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2407 2408 SDValue Gather; 2409 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2410 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2411 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2412 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2413 } else { 2414 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2415 // If only one index is used, we can use a "splat" vrgather. 2416 // TODO: We can splat the most-common index and fix-up any stragglers, if 2417 // that's beneficial. 2418 if (LHSIndexCounts.size() == 1) { 2419 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2420 Gather = 2421 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2422 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2423 } else { 2424 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2425 LHSIndices = 2426 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2427 2428 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2429 TrueMask, VL); 2430 } 2431 } 2432 2433 // If a second vector operand is used by this shuffle, blend it in with an 2434 // additional vrgather. 2435 if (!V2.isUndef()) { 2436 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2437 // If only one index is used, we can use a "splat" vrgather. 2438 // TODO: We can splat the most-common index and fix-up any stragglers, if 2439 // that's beneficial. 2440 if (RHSIndexCounts.size() == 1) { 2441 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2442 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2443 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2444 } else { 2445 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2446 RHSIndices = 2447 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2448 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2449 VL); 2450 } 2451 2452 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2453 SelectMask = 2454 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2455 2456 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2457 Gather, VL); 2458 } 2459 2460 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2461 } 2462 2463 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2464 SDLoc DL, SelectionDAG &DAG, 2465 const RISCVSubtarget &Subtarget) { 2466 if (VT.isScalableVector()) 2467 return DAG.getFPExtendOrRound(Op, DL, VT); 2468 assert(VT.isFixedLengthVector() && 2469 "Unexpected value type for RVV FP extend/round lowering"); 2470 SDValue Mask, VL; 2471 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2472 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2473 ? RISCVISD::FP_EXTEND_VL 2474 : RISCVISD::FP_ROUND_VL; 2475 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2476 } 2477 2478 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2479 // the exponent. 2480 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2481 MVT VT = Op.getSimpleValueType(); 2482 unsigned EltSize = VT.getScalarSizeInBits(); 2483 SDValue Src = Op.getOperand(0); 2484 SDLoc DL(Op); 2485 2486 // We need a FP type that can represent the value. 2487 // TODO: Use f16 for i8 when possible? 2488 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2489 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2490 2491 // Legal types should have been checked in the RISCVTargetLowering 2492 // constructor. 2493 // TODO: Splitting may make sense in some cases. 2494 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2495 "Expected legal float type!"); 2496 2497 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2498 // The trailing zero count is equal to log2 of this single bit value. 2499 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2500 SDValue Neg = 2501 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2502 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2503 } 2504 2505 // We have a legal FP type, convert to it. 2506 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2507 // Bitcast to integer and shift the exponent to the LSB. 2508 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2509 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2510 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2511 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2512 DAG.getConstant(ShiftAmt, DL, IntVT)); 2513 // Truncate back to original type to allow vnsrl. 2514 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2515 // The exponent contains log2 of the value in biased form. 2516 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2517 2518 // For trailing zeros, we just need to subtract the bias. 2519 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2520 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2521 DAG.getConstant(ExponentBias, DL, VT)); 2522 2523 // For leading zeros, we need to remove the bias and convert from log2 to 2524 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2525 unsigned Adjust = ExponentBias + (EltSize - 1); 2526 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2527 } 2528 2529 // While RVV has alignment restrictions, we should always be able to load as a 2530 // legal equivalently-sized byte-typed vector instead. This method is 2531 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2532 // the load is already correctly-aligned, it returns SDValue(). 2533 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2534 SelectionDAG &DAG) const { 2535 auto *Load = cast<LoadSDNode>(Op); 2536 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2537 2538 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2539 Load->getMemoryVT(), 2540 *Load->getMemOperand())) 2541 return SDValue(); 2542 2543 SDLoc DL(Op); 2544 MVT VT = Op.getSimpleValueType(); 2545 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2546 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2547 "Unexpected unaligned RVV load type"); 2548 MVT NewVT = 2549 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2550 assert(NewVT.isValid() && 2551 "Expecting equally-sized RVV vector types to be legal"); 2552 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2553 Load->getPointerInfo(), Load->getOriginalAlign(), 2554 Load->getMemOperand()->getFlags()); 2555 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2556 } 2557 2558 // While RVV has alignment restrictions, we should always be able to store as a 2559 // legal equivalently-sized byte-typed vector instead. This method is 2560 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2561 // returns SDValue() if the store is already correctly aligned. 2562 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2563 SelectionDAG &DAG) const { 2564 auto *Store = cast<StoreSDNode>(Op); 2565 assert(Store && Store->getValue().getValueType().isVector() && 2566 "Expected vector store"); 2567 2568 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2569 Store->getMemoryVT(), 2570 *Store->getMemOperand())) 2571 return SDValue(); 2572 2573 SDLoc DL(Op); 2574 SDValue StoredVal = Store->getValue(); 2575 MVT VT = StoredVal.getSimpleValueType(); 2576 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2577 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2578 "Unexpected unaligned RVV store type"); 2579 MVT NewVT = 2580 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2581 assert(NewVT.isValid() && 2582 "Expecting equally-sized RVV vector types to be legal"); 2583 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2584 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2585 Store->getPointerInfo(), Store->getOriginalAlign(), 2586 Store->getMemOperand()->getFlags()); 2587 } 2588 2589 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2590 SelectionDAG &DAG) const { 2591 switch (Op.getOpcode()) { 2592 default: 2593 report_fatal_error("unimplemented operand"); 2594 case ISD::GlobalAddress: 2595 return lowerGlobalAddress(Op, DAG); 2596 case ISD::BlockAddress: 2597 return lowerBlockAddress(Op, DAG); 2598 case ISD::ConstantPool: 2599 return lowerConstantPool(Op, DAG); 2600 case ISD::JumpTable: 2601 return lowerJumpTable(Op, DAG); 2602 case ISD::GlobalTLSAddress: 2603 return lowerGlobalTLSAddress(Op, DAG); 2604 case ISD::SELECT: 2605 return lowerSELECT(Op, DAG); 2606 case ISD::BRCOND: 2607 return lowerBRCOND(Op, DAG); 2608 case ISD::VASTART: 2609 return lowerVASTART(Op, DAG); 2610 case ISD::FRAMEADDR: 2611 return lowerFRAMEADDR(Op, DAG); 2612 case ISD::RETURNADDR: 2613 return lowerRETURNADDR(Op, DAG); 2614 case ISD::SHL_PARTS: 2615 return lowerShiftLeftParts(Op, DAG); 2616 case ISD::SRA_PARTS: 2617 return lowerShiftRightParts(Op, DAG, true); 2618 case ISD::SRL_PARTS: 2619 return lowerShiftRightParts(Op, DAG, false); 2620 case ISD::BITCAST: { 2621 SDLoc DL(Op); 2622 EVT VT = Op.getValueType(); 2623 SDValue Op0 = Op.getOperand(0); 2624 EVT Op0VT = Op0.getValueType(); 2625 MVT XLenVT = Subtarget.getXLenVT(); 2626 if (VT.isFixedLengthVector()) { 2627 // We can handle fixed length vector bitcasts with a simple replacement 2628 // in isel. 2629 if (Op0VT.isFixedLengthVector()) 2630 return Op; 2631 // When bitcasting from scalar to fixed-length vector, insert the scalar 2632 // into a one-element vector of the result type, and perform a vector 2633 // bitcast. 2634 if (!Op0VT.isVector()) { 2635 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2636 if (!isTypeLegal(BVT)) 2637 return SDValue(); 2638 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2639 DAG.getUNDEF(BVT), Op0, 2640 DAG.getConstant(0, DL, XLenVT))); 2641 } 2642 return SDValue(); 2643 } 2644 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2645 // thus: bitcast the vector to a one-element vector type whose element type 2646 // is the same as the result type, and extract the first element. 2647 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2648 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2649 if (!isTypeLegal(BVT)) 2650 return SDValue(); 2651 SDValue BVec = DAG.getBitcast(BVT, Op0); 2652 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2653 DAG.getConstant(0, DL, XLenVT)); 2654 } 2655 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2656 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2657 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2658 return FPConv; 2659 } 2660 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2661 Subtarget.hasStdExtF()) { 2662 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2663 SDValue FPConv = 2664 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2665 return FPConv; 2666 } 2667 return SDValue(); 2668 } 2669 case ISD::INTRINSIC_WO_CHAIN: 2670 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2671 case ISD::INTRINSIC_W_CHAIN: 2672 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2673 case ISD::INTRINSIC_VOID: 2674 return LowerINTRINSIC_VOID(Op, DAG); 2675 case ISD::BSWAP: 2676 case ISD::BITREVERSE: { 2677 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2678 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2679 MVT VT = Op.getSimpleValueType(); 2680 SDLoc DL(Op); 2681 // Start with the maximum immediate value which is the bitwidth - 1. 2682 unsigned Imm = VT.getSizeInBits() - 1; 2683 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2684 if (Op.getOpcode() == ISD::BSWAP) 2685 Imm &= ~0x7U; 2686 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2687 DAG.getConstant(Imm, DL, VT)); 2688 } 2689 case ISD::FSHL: 2690 case ISD::FSHR: { 2691 MVT VT = Op.getSimpleValueType(); 2692 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2693 SDLoc DL(Op); 2694 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2695 return Op; 2696 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2697 // use log(XLen) bits. Mask the shift amount accordingly. 2698 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2699 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2700 DAG.getConstant(ShAmtWidth, DL, VT)); 2701 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2702 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2703 } 2704 case ISD::TRUNCATE: { 2705 SDLoc DL(Op); 2706 MVT VT = Op.getSimpleValueType(); 2707 // Only custom-lower vector truncates 2708 if (!VT.isVector()) 2709 return Op; 2710 2711 // Truncates to mask types are handled differently 2712 if (VT.getVectorElementType() == MVT::i1) 2713 return lowerVectorMaskTrunc(Op, DAG); 2714 2715 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2716 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2717 // truncate by one power of two at a time. 2718 MVT DstEltVT = VT.getVectorElementType(); 2719 2720 SDValue Src = Op.getOperand(0); 2721 MVT SrcVT = Src.getSimpleValueType(); 2722 MVT SrcEltVT = SrcVT.getVectorElementType(); 2723 2724 assert(DstEltVT.bitsLT(SrcEltVT) && 2725 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2726 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2727 "Unexpected vector truncate lowering"); 2728 2729 MVT ContainerVT = SrcVT; 2730 if (SrcVT.isFixedLengthVector()) { 2731 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2732 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2733 } 2734 2735 SDValue Result = Src; 2736 SDValue Mask, VL; 2737 std::tie(Mask, VL) = 2738 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2739 LLVMContext &Context = *DAG.getContext(); 2740 const ElementCount Count = ContainerVT.getVectorElementCount(); 2741 do { 2742 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2743 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2744 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2745 Mask, VL); 2746 } while (SrcEltVT != DstEltVT); 2747 2748 if (SrcVT.isFixedLengthVector()) 2749 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2750 2751 return Result; 2752 } 2753 case ISD::ANY_EXTEND: 2754 case ISD::ZERO_EXTEND: 2755 if (Op.getOperand(0).getValueType().isVector() && 2756 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2757 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2758 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2759 case ISD::SIGN_EXTEND: 2760 if (Op.getOperand(0).getValueType().isVector() && 2761 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2762 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2763 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2764 case ISD::SPLAT_VECTOR_PARTS: 2765 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2766 case ISD::INSERT_VECTOR_ELT: 2767 return lowerINSERT_VECTOR_ELT(Op, DAG); 2768 case ISD::EXTRACT_VECTOR_ELT: 2769 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2770 case ISD::VSCALE: { 2771 MVT VT = Op.getSimpleValueType(); 2772 SDLoc DL(Op); 2773 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2774 // We define our scalable vector types for lmul=1 to use a 64 bit known 2775 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2776 // vscale as VLENB / 8. 2777 assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!"); 2778 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2779 // We assume VLENB is a multiple of 8. We manually choose the best shift 2780 // here because SimplifyDemandedBits isn't always able to simplify it. 2781 uint64_t Val = Op.getConstantOperandVal(0); 2782 if (isPowerOf2_64(Val)) { 2783 uint64_t Log2 = Log2_64(Val); 2784 if (Log2 < 3) 2785 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2786 DAG.getConstant(3 - Log2, DL, VT)); 2787 if (Log2 > 3) 2788 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2789 DAG.getConstant(Log2 - 3, DL, VT)); 2790 return VLENB; 2791 } 2792 // If the multiplier is a multiple of 8, scale it down to avoid needing 2793 // to shift the VLENB value. 2794 if ((Val % 8) == 0) 2795 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2796 DAG.getConstant(Val / 8, DL, VT)); 2797 } 2798 2799 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2800 DAG.getConstant(3, DL, VT)); 2801 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2802 } 2803 case ISD::FPOWI: { 2804 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 2805 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 2806 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 2807 Op.getOperand(1).getValueType() == MVT::i32) { 2808 SDLoc DL(Op); 2809 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 2810 SDValue Powi = 2811 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 2812 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 2813 DAG.getIntPtrConstant(0, DL)); 2814 } 2815 return SDValue(); 2816 } 2817 case ISD::FP_EXTEND: { 2818 // RVV can only do fp_extend to types double the size as the source. We 2819 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2820 // via f32. 2821 SDLoc DL(Op); 2822 MVT VT = Op.getSimpleValueType(); 2823 SDValue Src = Op.getOperand(0); 2824 MVT SrcVT = Src.getSimpleValueType(); 2825 2826 // Prepare any fixed-length vector operands. 2827 MVT ContainerVT = VT; 2828 if (SrcVT.isFixedLengthVector()) { 2829 ContainerVT = getContainerForFixedLengthVector(VT); 2830 MVT SrcContainerVT = 2831 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2832 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2833 } 2834 2835 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2836 SrcVT.getVectorElementType() != MVT::f16) { 2837 // For scalable vectors, we only need to close the gap between 2838 // vXf16->vXf64. 2839 if (!VT.isFixedLengthVector()) 2840 return Op; 2841 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2842 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2843 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2844 } 2845 2846 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2847 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2848 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2849 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2850 2851 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2852 DL, DAG, Subtarget); 2853 if (VT.isFixedLengthVector()) 2854 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2855 return Extend; 2856 } 2857 case ISD::FP_ROUND: { 2858 // RVV can only do fp_round to types half the size as the source. We 2859 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2860 // conversion instruction. 2861 SDLoc DL(Op); 2862 MVT VT = Op.getSimpleValueType(); 2863 SDValue Src = Op.getOperand(0); 2864 MVT SrcVT = Src.getSimpleValueType(); 2865 2866 // Prepare any fixed-length vector operands. 2867 MVT ContainerVT = VT; 2868 if (VT.isFixedLengthVector()) { 2869 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2870 ContainerVT = 2871 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2872 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2873 } 2874 2875 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2876 SrcVT.getVectorElementType() != MVT::f64) { 2877 // For scalable vectors, we only need to close the gap between 2878 // vXf64<->vXf16. 2879 if (!VT.isFixedLengthVector()) 2880 return Op; 2881 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2882 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2883 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2884 } 2885 2886 SDValue Mask, VL; 2887 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2888 2889 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2890 SDValue IntermediateRound = 2891 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2892 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2893 DL, DAG, Subtarget); 2894 2895 if (VT.isFixedLengthVector()) 2896 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2897 return Round; 2898 } 2899 case ISD::FP_TO_SINT: 2900 case ISD::FP_TO_UINT: 2901 case ISD::SINT_TO_FP: 2902 case ISD::UINT_TO_FP: { 2903 // RVV can only do fp<->int conversions to types half/double the size as 2904 // the source. We custom-lower any conversions that do two hops into 2905 // sequences. 2906 MVT VT = Op.getSimpleValueType(); 2907 if (!VT.isVector()) 2908 return Op; 2909 SDLoc DL(Op); 2910 SDValue Src = Op.getOperand(0); 2911 MVT EltVT = VT.getVectorElementType(); 2912 MVT SrcVT = Src.getSimpleValueType(); 2913 MVT SrcEltVT = SrcVT.getVectorElementType(); 2914 unsigned EltSize = EltVT.getSizeInBits(); 2915 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2916 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2917 "Unexpected vector element types"); 2918 2919 bool IsInt2FP = SrcEltVT.isInteger(); 2920 // Widening conversions 2921 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2922 if (IsInt2FP) { 2923 // Do a regular integer sign/zero extension then convert to float. 2924 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2925 VT.getVectorElementCount()); 2926 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2927 ? ISD::ZERO_EXTEND 2928 : ISD::SIGN_EXTEND; 2929 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2930 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2931 } 2932 // FP2Int 2933 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2934 // Do one doubling fp_extend then complete the operation by converting 2935 // to int. 2936 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2937 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2938 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2939 } 2940 2941 // Narrowing conversions 2942 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2943 if (IsInt2FP) { 2944 // One narrowing int_to_fp, then an fp_round. 2945 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2946 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2947 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2948 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2949 } 2950 // FP2Int 2951 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2952 // representable by the integer, the result is poison. 2953 MVT IVecVT = 2954 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2955 VT.getVectorElementCount()); 2956 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2957 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2958 } 2959 2960 // Scalable vectors can exit here. Patterns will handle equally-sized 2961 // conversions halving/doubling ones. 2962 if (!VT.isFixedLengthVector()) 2963 return Op; 2964 2965 // For fixed-length vectors we lower to a custom "VL" node. 2966 unsigned RVVOpc = 0; 2967 switch (Op.getOpcode()) { 2968 default: 2969 llvm_unreachable("Impossible opcode"); 2970 case ISD::FP_TO_SINT: 2971 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2972 break; 2973 case ISD::FP_TO_UINT: 2974 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2975 break; 2976 case ISD::SINT_TO_FP: 2977 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2978 break; 2979 case ISD::UINT_TO_FP: 2980 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2981 break; 2982 } 2983 2984 MVT ContainerVT, SrcContainerVT; 2985 // Derive the reference container type from the larger vector type. 2986 if (SrcEltSize > EltSize) { 2987 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2988 ContainerVT = 2989 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2990 } else { 2991 ContainerVT = getContainerForFixedLengthVector(VT); 2992 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 2993 } 2994 2995 SDValue Mask, VL; 2996 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2997 2998 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2999 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3000 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3001 } 3002 case ISD::FP_TO_SINT_SAT: 3003 case ISD::FP_TO_UINT_SAT: 3004 return lowerFP_TO_INT_SAT(Op, DAG); 3005 case ISD::FTRUNC: 3006 case ISD::FCEIL: 3007 case ISD::FFLOOR: 3008 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3009 case ISD::VECREDUCE_ADD: 3010 case ISD::VECREDUCE_UMAX: 3011 case ISD::VECREDUCE_SMAX: 3012 case ISD::VECREDUCE_UMIN: 3013 case ISD::VECREDUCE_SMIN: 3014 return lowerVECREDUCE(Op, DAG); 3015 case ISD::VECREDUCE_AND: 3016 case ISD::VECREDUCE_OR: 3017 case ISD::VECREDUCE_XOR: 3018 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3019 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3020 return lowerVECREDUCE(Op, DAG); 3021 case ISD::VECREDUCE_FADD: 3022 case ISD::VECREDUCE_SEQ_FADD: 3023 case ISD::VECREDUCE_FMIN: 3024 case ISD::VECREDUCE_FMAX: 3025 return lowerFPVECREDUCE(Op, DAG); 3026 case ISD::VP_REDUCE_ADD: 3027 case ISD::VP_REDUCE_UMAX: 3028 case ISD::VP_REDUCE_SMAX: 3029 case ISD::VP_REDUCE_UMIN: 3030 case ISD::VP_REDUCE_SMIN: 3031 case ISD::VP_REDUCE_FADD: 3032 case ISD::VP_REDUCE_SEQ_FADD: 3033 case ISD::VP_REDUCE_FMIN: 3034 case ISD::VP_REDUCE_FMAX: 3035 return lowerVPREDUCE(Op, DAG); 3036 case ISD::VP_REDUCE_AND: 3037 case ISD::VP_REDUCE_OR: 3038 case ISD::VP_REDUCE_XOR: 3039 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3040 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3041 return lowerVPREDUCE(Op, DAG); 3042 case ISD::INSERT_SUBVECTOR: 3043 return lowerINSERT_SUBVECTOR(Op, DAG); 3044 case ISD::EXTRACT_SUBVECTOR: 3045 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3046 case ISD::STEP_VECTOR: 3047 return lowerSTEP_VECTOR(Op, DAG); 3048 case ISD::VECTOR_REVERSE: 3049 return lowerVECTOR_REVERSE(Op, DAG); 3050 case ISD::BUILD_VECTOR: 3051 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3052 case ISD::SPLAT_VECTOR: 3053 if (Op.getValueType().getVectorElementType() == MVT::i1) 3054 return lowerVectorMaskSplat(Op, DAG); 3055 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3056 case ISD::VECTOR_SHUFFLE: 3057 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3058 case ISD::CONCAT_VECTORS: { 3059 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3060 // better than going through the stack, as the default expansion does. 3061 SDLoc DL(Op); 3062 MVT VT = Op.getSimpleValueType(); 3063 unsigned NumOpElts = 3064 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3065 SDValue Vec = DAG.getUNDEF(VT); 3066 for (const auto &OpIdx : enumerate(Op->ops())) 3067 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 3068 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3069 return Vec; 3070 } 3071 case ISD::LOAD: 3072 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3073 return V; 3074 if (Op.getValueType().isFixedLengthVector()) 3075 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3076 return Op; 3077 case ISD::STORE: 3078 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3079 return V; 3080 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3081 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3082 return Op; 3083 case ISD::MLOAD: 3084 case ISD::VP_LOAD: 3085 return lowerMaskedLoad(Op, DAG); 3086 case ISD::MSTORE: 3087 case ISD::VP_STORE: 3088 return lowerMaskedStore(Op, DAG); 3089 case ISD::SETCC: 3090 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3091 case ISD::ADD: 3092 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3093 case ISD::SUB: 3094 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3095 case ISD::MUL: 3096 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3097 case ISD::MULHS: 3098 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3099 case ISD::MULHU: 3100 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3101 case ISD::AND: 3102 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3103 RISCVISD::AND_VL); 3104 case ISD::OR: 3105 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3106 RISCVISD::OR_VL); 3107 case ISD::XOR: 3108 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3109 RISCVISD::XOR_VL); 3110 case ISD::SDIV: 3111 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3112 case ISD::SREM: 3113 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3114 case ISD::UDIV: 3115 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3116 case ISD::UREM: 3117 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3118 case ISD::SHL: 3119 case ISD::SRA: 3120 case ISD::SRL: 3121 if (Op.getSimpleValueType().isFixedLengthVector()) 3122 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3123 // This can be called for an i32 shift amount that needs to be promoted. 3124 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3125 "Unexpected custom legalisation"); 3126 return SDValue(); 3127 case ISD::SADDSAT: 3128 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3129 case ISD::UADDSAT: 3130 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3131 case ISD::SSUBSAT: 3132 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3133 case ISD::USUBSAT: 3134 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3135 case ISD::FADD: 3136 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3137 case ISD::FSUB: 3138 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3139 case ISD::FMUL: 3140 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3141 case ISD::FDIV: 3142 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3143 case ISD::FNEG: 3144 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3145 case ISD::FABS: 3146 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3147 case ISD::FSQRT: 3148 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3149 case ISD::FMA: 3150 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3151 case ISD::SMIN: 3152 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3153 case ISD::SMAX: 3154 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3155 case ISD::UMIN: 3156 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3157 case ISD::UMAX: 3158 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3159 case ISD::FMINNUM: 3160 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3161 case ISD::FMAXNUM: 3162 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3163 case ISD::ABS: 3164 return lowerABS(Op, DAG); 3165 case ISD::CTLZ_ZERO_UNDEF: 3166 case ISD::CTTZ_ZERO_UNDEF: 3167 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3168 case ISD::VSELECT: 3169 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3170 case ISD::FCOPYSIGN: 3171 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3172 case ISD::MGATHER: 3173 case ISD::VP_GATHER: 3174 return lowerMaskedGather(Op, DAG); 3175 case ISD::MSCATTER: 3176 case ISD::VP_SCATTER: 3177 return lowerMaskedScatter(Op, DAG); 3178 case ISD::FLT_ROUNDS_: 3179 return lowerGET_ROUNDING(Op, DAG); 3180 case ISD::SET_ROUNDING: 3181 return lowerSET_ROUNDING(Op, DAG); 3182 case ISD::VP_SELECT: 3183 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3184 case ISD::VP_ADD: 3185 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3186 case ISD::VP_SUB: 3187 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3188 case ISD::VP_MUL: 3189 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3190 case ISD::VP_SDIV: 3191 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3192 case ISD::VP_UDIV: 3193 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3194 case ISD::VP_SREM: 3195 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3196 case ISD::VP_UREM: 3197 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3198 case ISD::VP_AND: 3199 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3200 case ISD::VP_OR: 3201 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3202 case ISD::VP_XOR: 3203 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3204 case ISD::VP_ASHR: 3205 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3206 case ISD::VP_LSHR: 3207 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3208 case ISD::VP_SHL: 3209 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3210 case ISD::VP_FADD: 3211 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3212 case ISD::VP_FSUB: 3213 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3214 case ISD::VP_FMUL: 3215 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3216 case ISD::VP_FDIV: 3217 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3218 } 3219 } 3220 3221 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3222 SelectionDAG &DAG, unsigned Flags) { 3223 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3224 } 3225 3226 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3227 SelectionDAG &DAG, unsigned Flags) { 3228 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3229 Flags); 3230 } 3231 3232 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3233 SelectionDAG &DAG, unsigned Flags) { 3234 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3235 N->getOffset(), Flags); 3236 } 3237 3238 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3239 SelectionDAG &DAG, unsigned Flags) { 3240 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3241 } 3242 3243 template <class NodeTy> 3244 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3245 bool IsLocal) const { 3246 SDLoc DL(N); 3247 EVT Ty = getPointerTy(DAG.getDataLayout()); 3248 3249 if (isPositionIndependent()) { 3250 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3251 if (IsLocal) 3252 // Use PC-relative addressing to access the symbol. This generates the 3253 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3254 // %pcrel_lo(auipc)). 3255 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3256 3257 // Use PC-relative addressing to access the GOT for this symbol, then load 3258 // the address from the GOT. This generates the pattern (PseudoLA sym), 3259 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3260 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3261 } 3262 3263 switch (getTargetMachine().getCodeModel()) { 3264 default: 3265 report_fatal_error("Unsupported code model for lowering"); 3266 case CodeModel::Small: { 3267 // Generate a sequence for accessing addresses within the first 2 GiB of 3268 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3269 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3270 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3271 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3272 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3273 } 3274 case CodeModel::Medium: { 3275 // Generate a sequence for accessing addresses within any 2GiB range within 3276 // the address space. This generates the pattern (PseudoLLA sym), which 3277 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3278 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3279 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3280 } 3281 } 3282 } 3283 3284 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3285 SelectionDAG &DAG) const { 3286 SDLoc DL(Op); 3287 EVT Ty = Op.getValueType(); 3288 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3289 int64_t Offset = N->getOffset(); 3290 MVT XLenVT = Subtarget.getXLenVT(); 3291 3292 const GlobalValue *GV = N->getGlobal(); 3293 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3294 SDValue Addr = getAddr(N, DAG, IsLocal); 3295 3296 // In order to maximise the opportunity for common subexpression elimination, 3297 // emit a separate ADD node for the global address offset instead of folding 3298 // it in the global address node. Later peephole optimisations may choose to 3299 // fold it back in when profitable. 3300 if (Offset != 0) 3301 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3302 DAG.getConstant(Offset, DL, XLenVT)); 3303 return Addr; 3304 } 3305 3306 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3307 SelectionDAG &DAG) const { 3308 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3309 3310 return getAddr(N, DAG); 3311 } 3312 3313 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3314 SelectionDAG &DAG) const { 3315 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3316 3317 return getAddr(N, DAG); 3318 } 3319 3320 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3321 SelectionDAG &DAG) const { 3322 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3323 3324 return getAddr(N, DAG); 3325 } 3326 3327 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3328 SelectionDAG &DAG, 3329 bool UseGOT) const { 3330 SDLoc DL(N); 3331 EVT Ty = getPointerTy(DAG.getDataLayout()); 3332 const GlobalValue *GV = N->getGlobal(); 3333 MVT XLenVT = Subtarget.getXLenVT(); 3334 3335 if (UseGOT) { 3336 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3337 // load the address from the GOT and add the thread pointer. This generates 3338 // the pattern (PseudoLA_TLS_IE sym), which expands to 3339 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3340 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3341 SDValue Load = 3342 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3343 3344 // Add the thread pointer. 3345 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3346 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3347 } 3348 3349 // Generate a sequence for accessing the address relative to the thread 3350 // pointer, with the appropriate adjustment for the thread pointer offset. 3351 // This generates the pattern 3352 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3353 SDValue AddrHi = 3354 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3355 SDValue AddrAdd = 3356 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3357 SDValue AddrLo = 3358 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3359 3360 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3361 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3362 SDValue MNAdd = SDValue( 3363 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3364 0); 3365 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3366 } 3367 3368 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3369 SelectionDAG &DAG) const { 3370 SDLoc DL(N); 3371 EVT Ty = getPointerTy(DAG.getDataLayout()); 3372 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3373 const GlobalValue *GV = N->getGlobal(); 3374 3375 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3376 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3377 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3378 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3379 SDValue Load = 3380 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3381 3382 // Prepare argument list to generate call. 3383 ArgListTy Args; 3384 ArgListEntry Entry; 3385 Entry.Node = Load; 3386 Entry.Ty = CallTy; 3387 Args.push_back(Entry); 3388 3389 // Setup call to __tls_get_addr. 3390 TargetLowering::CallLoweringInfo CLI(DAG); 3391 CLI.setDebugLoc(DL) 3392 .setChain(DAG.getEntryNode()) 3393 .setLibCallee(CallingConv::C, CallTy, 3394 DAG.getExternalSymbol("__tls_get_addr", Ty), 3395 std::move(Args)); 3396 3397 return LowerCallTo(CLI).first; 3398 } 3399 3400 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3401 SelectionDAG &DAG) const { 3402 SDLoc DL(Op); 3403 EVT Ty = Op.getValueType(); 3404 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3405 int64_t Offset = N->getOffset(); 3406 MVT XLenVT = Subtarget.getXLenVT(); 3407 3408 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3409 3410 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3411 CallingConv::GHC) 3412 report_fatal_error("In GHC calling convention TLS is not supported"); 3413 3414 SDValue Addr; 3415 switch (Model) { 3416 case TLSModel::LocalExec: 3417 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3418 break; 3419 case TLSModel::InitialExec: 3420 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3421 break; 3422 case TLSModel::LocalDynamic: 3423 case TLSModel::GeneralDynamic: 3424 Addr = getDynamicTLSAddr(N, DAG); 3425 break; 3426 } 3427 3428 // In order to maximise the opportunity for common subexpression elimination, 3429 // emit a separate ADD node for the global address offset instead of folding 3430 // it in the global address node. Later peephole optimisations may choose to 3431 // fold it back in when profitable. 3432 if (Offset != 0) 3433 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3434 DAG.getConstant(Offset, DL, XLenVT)); 3435 return Addr; 3436 } 3437 3438 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3439 SDValue CondV = Op.getOperand(0); 3440 SDValue TrueV = Op.getOperand(1); 3441 SDValue FalseV = Op.getOperand(2); 3442 SDLoc DL(Op); 3443 MVT VT = Op.getSimpleValueType(); 3444 MVT XLenVT = Subtarget.getXLenVT(); 3445 3446 // Lower vector SELECTs to VSELECTs by splatting the condition. 3447 if (VT.isVector()) { 3448 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3449 SDValue CondSplat = VT.isScalableVector() 3450 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3451 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3452 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3453 } 3454 3455 // If the result type is XLenVT and CondV is the output of a SETCC node 3456 // which also operated on XLenVT inputs, then merge the SETCC node into the 3457 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3458 // compare+branch instructions. i.e.: 3459 // (select (setcc lhs, rhs, cc), truev, falsev) 3460 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3461 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3462 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3463 SDValue LHS = CondV.getOperand(0); 3464 SDValue RHS = CondV.getOperand(1); 3465 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3466 ISD::CondCode CCVal = CC->get(); 3467 3468 // Special case for a select of 2 constants that have a diffence of 1. 3469 // Normally this is done by DAGCombine, but if the select is introduced by 3470 // type legalization or op legalization, we miss it. Restricting to SETLT 3471 // case for now because that is what signed saturating add/sub need. 3472 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3473 // but we would probably want to swap the true/false values if the condition 3474 // is SETGE/SETLE to avoid an XORI. 3475 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3476 CCVal == ISD::SETLT) { 3477 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3478 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3479 if (TrueVal - 1 == FalseVal) 3480 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3481 if (TrueVal + 1 == FalseVal) 3482 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3483 } 3484 3485 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3486 3487 SDValue TargetCC = DAG.getCondCode(CCVal); 3488 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3489 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3490 } 3491 3492 // Otherwise: 3493 // (select condv, truev, falsev) 3494 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3495 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3496 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3497 3498 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3499 3500 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3501 } 3502 3503 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3504 SDValue CondV = Op.getOperand(1); 3505 SDLoc DL(Op); 3506 MVT XLenVT = Subtarget.getXLenVT(); 3507 3508 if (CondV.getOpcode() == ISD::SETCC && 3509 CondV.getOperand(0).getValueType() == XLenVT) { 3510 SDValue LHS = CondV.getOperand(0); 3511 SDValue RHS = CondV.getOperand(1); 3512 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3513 3514 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3515 3516 SDValue TargetCC = DAG.getCondCode(CCVal); 3517 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3518 LHS, RHS, TargetCC, Op.getOperand(2)); 3519 } 3520 3521 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3522 CondV, DAG.getConstant(0, DL, XLenVT), 3523 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3524 } 3525 3526 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3527 MachineFunction &MF = DAG.getMachineFunction(); 3528 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3529 3530 SDLoc DL(Op); 3531 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3532 getPointerTy(MF.getDataLayout())); 3533 3534 // vastart just stores the address of the VarArgsFrameIndex slot into the 3535 // memory location argument. 3536 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3537 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3538 MachinePointerInfo(SV)); 3539 } 3540 3541 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3542 SelectionDAG &DAG) const { 3543 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3544 MachineFunction &MF = DAG.getMachineFunction(); 3545 MachineFrameInfo &MFI = MF.getFrameInfo(); 3546 MFI.setFrameAddressIsTaken(true); 3547 Register FrameReg = RI.getFrameRegister(MF); 3548 int XLenInBytes = Subtarget.getXLen() / 8; 3549 3550 EVT VT = Op.getValueType(); 3551 SDLoc DL(Op); 3552 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3553 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3554 while (Depth--) { 3555 int Offset = -(XLenInBytes * 2); 3556 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3557 DAG.getIntPtrConstant(Offset, DL)); 3558 FrameAddr = 3559 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3560 } 3561 return FrameAddr; 3562 } 3563 3564 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3565 SelectionDAG &DAG) const { 3566 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3567 MachineFunction &MF = DAG.getMachineFunction(); 3568 MachineFrameInfo &MFI = MF.getFrameInfo(); 3569 MFI.setReturnAddressIsTaken(true); 3570 MVT XLenVT = Subtarget.getXLenVT(); 3571 int XLenInBytes = Subtarget.getXLen() / 8; 3572 3573 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3574 return SDValue(); 3575 3576 EVT VT = Op.getValueType(); 3577 SDLoc DL(Op); 3578 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3579 if (Depth) { 3580 int Off = -XLenInBytes; 3581 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3582 SDValue Offset = DAG.getConstant(Off, DL, VT); 3583 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3584 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3585 MachinePointerInfo()); 3586 } 3587 3588 // Return the value of the return address register, marking it an implicit 3589 // live-in. 3590 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3591 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3592 } 3593 3594 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3595 SelectionDAG &DAG) const { 3596 SDLoc DL(Op); 3597 SDValue Lo = Op.getOperand(0); 3598 SDValue Hi = Op.getOperand(1); 3599 SDValue Shamt = Op.getOperand(2); 3600 EVT VT = Lo.getValueType(); 3601 3602 // if Shamt-XLEN < 0: // Shamt < XLEN 3603 // Lo = Lo << Shamt 3604 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3605 // else: 3606 // Lo = 0 3607 // Hi = Lo << (Shamt-XLEN) 3608 3609 SDValue Zero = DAG.getConstant(0, DL, VT); 3610 SDValue One = DAG.getConstant(1, DL, VT); 3611 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3612 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3613 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3614 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3615 3616 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3617 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3618 SDValue ShiftRightLo = 3619 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3620 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3621 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3622 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3623 3624 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3625 3626 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3627 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3628 3629 SDValue Parts[2] = {Lo, Hi}; 3630 return DAG.getMergeValues(Parts, DL); 3631 } 3632 3633 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3634 bool IsSRA) const { 3635 SDLoc DL(Op); 3636 SDValue Lo = Op.getOperand(0); 3637 SDValue Hi = Op.getOperand(1); 3638 SDValue Shamt = Op.getOperand(2); 3639 EVT VT = Lo.getValueType(); 3640 3641 // SRA expansion: 3642 // if Shamt-XLEN < 0: // Shamt < XLEN 3643 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3644 // Hi = Hi >>s Shamt 3645 // else: 3646 // Lo = Hi >>s (Shamt-XLEN); 3647 // Hi = Hi >>s (XLEN-1) 3648 // 3649 // SRL expansion: 3650 // if Shamt-XLEN < 0: // Shamt < XLEN 3651 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3652 // Hi = Hi >>u Shamt 3653 // else: 3654 // Lo = Hi >>u (Shamt-XLEN); 3655 // Hi = 0; 3656 3657 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3658 3659 SDValue Zero = DAG.getConstant(0, DL, VT); 3660 SDValue One = DAG.getConstant(1, DL, VT); 3661 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3662 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3663 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3664 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3665 3666 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3667 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3668 SDValue ShiftLeftHi = 3669 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3670 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3671 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3672 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3673 SDValue HiFalse = 3674 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3675 3676 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3677 3678 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3679 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3680 3681 SDValue Parts[2] = {Lo, Hi}; 3682 return DAG.getMergeValues(Parts, DL); 3683 } 3684 3685 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3686 // legal equivalently-sized i8 type, so we can use that as a go-between. 3687 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3688 SelectionDAG &DAG) const { 3689 SDLoc DL(Op); 3690 MVT VT = Op.getSimpleValueType(); 3691 SDValue SplatVal = Op.getOperand(0); 3692 // All-zeros or all-ones splats are handled specially. 3693 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3694 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3695 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3696 } 3697 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3698 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3699 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3700 } 3701 MVT XLenVT = Subtarget.getXLenVT(); 3702 assert(SplatVal.getValueType() == XLenVT && 3703 "Unexpected type for i1 splat value"); 3704 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3705 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3706 DAG.getConstant(1, DL, XLenVT)); 3707 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3708 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3709 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3710 } 3711 3712 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3713 // illegal (currently only vXi64 RV32). 3714 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3715 // them to SPLAT_VECTOR_I64 3716 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3717 SelectionDAG &DAG) const { 3718 SDLoc DL(Op); 3719 MVT VecVT = Op.getSimpleValueType(); 3720 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3721 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3722 3723 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3724 SDValue Lo = Op.getOperand(0); 3725 SDValue Hi = Op.getOperand(1); 3726 3727 if (VecVT.isFixedLengthVector()) { 3728 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3729 SDLoc DL(Op); 3730 SDValue Mask, VL; 3731 std::tie(Mask, VL) = 3732 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3733 3734 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3735 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3736 } 3737 3738 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3739 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3740 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3741 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3742 // node in order to try and match RVV vector/scalar instructions. 3743 if ((LoC >> 31) == HiC) 3744 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3745 } 3746 3747 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3748 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3749 isa<ConstantSDNode>(Hi.getOperand(1)) && 3750 Hi.getConstantOperandVal(1) == 31) 3751 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3752 3753 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3754 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3755 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3756 } 3757 3758 // Custom-lower extensions from mask vectors by using a vselect either with 1 3759 // for zero/any-extension or -1 for sign-extension: 3760 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3761 // Note that any-extension is lowered identically to zero-extension. 3762 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3763 int64_t ExtTrueVal) const { 3764 SDLoc DL(Op); 3765 MVT VecVT = Op.getSimpleValueType(); 3766 SDValue Src = Op.getOperand(0); 3767 // Only custom-lower extensions from mask types 3768 assert(Src.getValueType().isVector() && 3769 Src.getValueType().getVectorElementType() == MVT::i1); 3770 3771 MVT XLenVT = Subtarget.getXLenVT(); 3772 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3773 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3774 3775 if (VecVT.isScalableVector()) { 3776 // Be careful not to introduce illegal scalar types at this stage, and be 3777 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3778 // illegal and must be expanded. Since we know that the constants are 3779 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3780 bool IsRV32E64 = 3781 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3782 3783 if (!IsRV32E64) { 3784 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3785 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3786 } else { 3787 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3788 SplatTrueVal = 3789 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3790 } 3791 3792 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3793 } 3794 3795 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3796 MVT I1ContainerVT = 3797 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3798 3799 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3800 3801 SDValue Mask, VL; 3802 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3803 3804 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3805 SplatTrueVal = 3806 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3807 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3808 SplatTrueVal, SplatZero, VL); 3809 3810 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3811 } 3812 3813 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3814 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3815 MVT ExtVT = Op.getSimpleValueType(); 3816 // Only custom-lower extensions from fixed-length vector types. 3817 if (!ExtVT.isFixedLengthVector()) 3818 return Op; 3819 MVT VT = Op.getOperand(0).getSimpleValueType(); 3820 // Grab the canonical container type for the extended type. Infer the smaller 3821 // type from that to ensure the same number of vector elements, as we know 3822 // the LMUL will be sufficient to hold the smaller type. 3823 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3824 // Get the extended container type manually to ensure the same number of 3825 // vector elements between source and dest. 3826 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3827 ContainerExtVT.getVectorElementCount()); 3828 3829 SDValue Op1 = 3830 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3831 3832 SDLoc DL(Op); 3833 SDValue Mask, VL; 3834 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3835 3836 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3837 3838 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3839 } 3840 3841 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3842 // setcc operation: 3843 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3844 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3845 SelectionDAG &DAG) const { 3846 SDLoc DL(Op); 3847 EVT MaskVT = Op.getValueType(); 3848 // Only expect to custom-lower truncations to mask types 3849 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3850 "Unexpected type for vector mask lowering"); 3851 SDValue Src = Op.getOperand(0); 3852 MVT VecVT = Src.getSimpleValueType(); 3853 3854 // If this is a fixed vector, we need to convert it to a scalable vector. 3855 MVT ContainerVT = VecVT; 3856 if (VecVT.isFixedLengthVector()) { 3857 ContainerVT = getContainerForFixedLengthVector(VecVT); 3858 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3859 } 3860 3861 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3862 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3863 3864 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3865 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3866 3867 if (VecVT.isScalableVector()) { 3868 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3869 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3870 } 3871 3872 SDValue Mask, VL; 3873 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3874 3875 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3876 SDValue Trunc = 3877 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3878 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3879 DAG.getCondCode(ISD::SETNE), Mask, VL); 3880 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3881 } 3882 3883 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3884 // first position of a vector, and that vector is slid up to the insert index. 3885 // By limiting the active vector length to index+1 and merging with the 3886 // original vector (with an undisturbed tail policy for elements >= VL), we 3887 // achieve the desired result of leaving all elements untouched except the one 3888 // at VL-1, which is replaced with the desired value. 3889 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3890 SelectionDAG &DAG) const { 3891 SDLoc DL(Op); 3892 MVT VecVT = Op.getSimpleValueType(); 3893 SDValue Vec = Op.getOperand(0); 3894 SDValue Val = Op.getOperand(1); 3895 SDValue Idx = Op.getOperand(2); 3896 3897 if (VecVT.getVectorElementType() == MVT::i1) { 3898 // FIXME: For now we just promote to an i8 vector and insert into that, 3899 // but this is probably not optimal. 3900 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3901 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3902 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3903 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3904 } 3905 3906 MVT ContainerVT = VecVT; 3907 // If the operand is a fixed-length vector, convert to a scalable one. 3908 if (VecVT.isFixedLengthVector()) { 3909 ContainerVT = getContainerForFixedLengthVector(VecVT); 3910 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3911 } 3912 3913 MVT XLenVT = Subtarget.getXLenVT(); 3914 3915 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3916 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3917 // Even i64-element vectors on RV32 can be lowered without scalar 3918 // legalization if the most-significant 32 bits of the value are not affected 3919 // by the sign-extension of the lower 32 bits. 3920 // TODO: We could also catch sign extensions of a 32-bit value. 3921 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3922 const auto *CVal = cast<ConstantSDNode>(Val); 3923 if (isInt<32>(CVal->getSExtValue())) { 3924 IsLegalInsert = true; 3925 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3926 } 3927 } 3928 3929 SDValue Mask, VL; 3930 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3931 3932 SDValue ValInVec; 3933 3934 if (IsLegalInsert) { 3935 unsigned Opc = 3936 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3937 if (isNullConstant(Idx)) { 3938 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3939 if (!VecVT.isFixedLengthVector()) 3940 return Vec; 3941 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3942 } 3943 ValInVec = 3944 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3945 } else { 3946 // On RV32, i64-element vectors must be specially handled to place the 3947 // value at element 0, by using two vslide1up instructions in sequence on 3948 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3949 // this. 3950 SDValue One = DAG.getConstant(1, DL, XLenVT); 3951 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3952 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3953 MVT I32ContainerVT = 3954 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3955 SDValue I32Mask = 3956 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3957 // Limit the active VL to two. 3958 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3959 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3960 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3961 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3962 InsertI64VL); 3963 // First slide in the hi value, then the lo in underneath it. 3964 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3965 ValHi, I32Mask, InsertI64VL); 3966 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3967 ValLo, I32Mask, InsertI64VL); 3968 // Bitcast back to the right container type. 3969 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3970 } 3971 3972 // Now that the value is in a vector, slide it into position. 3973 SDValue InsertVL = 3974 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3975 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3976 ValInVec, Idx, Mask, InsertVL); 3977 if (!VecVT.isFixedLengthVector()) 3978 return Slideup; 3979 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3980 } 3981 3982 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3983 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3984 // types this is done using VMV_X_S to allow us to glean information about the 3985 // sign bits of the result. 3986 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3987 SelectionDAG &DAG) const { 3988 SDLoc DL(Op); 3989 SDValue Idx = Op.getOperand(1); 3990 SDValue Vec = Op.getOperand(0); 3991 EVT EltVT = Op.getValueType(); 3992 MVT VecVT = Vec.getSimpleValueType(); 3993 MVT XLenVT = Subtarget.getXLenVT(); 3994 3995 if (VecVT.getVectorElementType() == MVT::i1) { 3996 // FIXME: For now we just promote to an i8 vector and extract from that, 3997 // but this is probably not optimal. 3998 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3999 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4000 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4001 } 4002 4003 // If this is a fixed vector, we need to convert it to a scalable vector. 4004 MVT ContainerVT = VecVT; 4005 if (VecVT.isFixedLengthVector()) { 4006 ContainerVT = getContainerForFixedLengthVector(VecVT); 4007 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4008 } 4009 4010 // If the index is 0, the vector is already in the right position. 4011 if (!isNullConstant(Idx)) { 4012 // Use a VL of 1 to avoid processing more elements than we need. 4013 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4014 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4015 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4016 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4017 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4018 } 4019 4020 if (!EltVT.isInteger()) { 4021 // Floating-point extracts are handled in TableGen. 4022 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4023 DAG.getConstant(0, DL, XLenVT)); 4024 } 4025 4026 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4027 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4028 } 4029 4030 // Some RVV intrinsics may claim that they want an integer operand to be 4031 // promoted or expanded. 4032 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4033 const RISCVSubtarget &Subtarget) { 4034 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4035 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4036 "Unexpected opcode"); 4037 4038 if (!Subtarget.hasVInstructions()) 4039 return SDValue(); 4040 4041 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4042 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4043 SDLoc DL(Op); 4044 4045 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4046 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4047 if (!II || !II->SplatOperand) 4048 return SDValue(); 4049 4050 unsigned SplatOp = II->SplatOperand + HasChain; 4051 assert(SplatOp < Op.getNumOperands()); 4052 4053 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4054 SDValue &ScalarOp = Operands[SplatOp]; 4055 MVT OpVT = ScalarOp.getSimpleValueType(); 4056 MVT XLenVT = Subtarget.getXLenVT(); 4057 4058 // If this isn't a scalar, or its type is XLenVT we're done. 4059 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4060 return SDValue(); 4061 4062 // Simplest case is that the operand needs to be promoted to XLenVT. 4063 if (OpVT.bitsLT(XLenVT)) { 4064 // If the operand is a constant, sign extend to increase our chances 4065 // of being able to use a .vi instruction. ANY_EXTEND would become a 4066 // a zero extend and the simm5 check in isel would fail. 4067 // FIXME: Should we ignore the upper bits in isel instead? 4068 unsigned ExtOpc = 4069 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4070 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4071 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4072 } 4073 4074 // Use the previous operand to get the vXi64 VT. The result might be a mask 4075 // VT for compares. Using the previous operand assumes that the previous 4076 // operand will never have a smaller element size than a scalar operand and 4077 // that a widening operation never uses SEW=64. 4078 // NOTE: If this fails the below assert, we can probably just find the 4079 // element count from any operand or result and use it to construct the VT. 4080 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 4081 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4082 4083 // The more complex case is when the scalar is larger than XLenVT. 4084 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4085 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4086 4087 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4088 // on the instruction to sign-extend since SEW>XLEN. 4089 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4090 if (isInt<32>(CVal->getSExtValue())) { 4091 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4092 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4093 } 4094 } 4095 4096 // We need to convert the scalar to a splat vector. 4097 // FIXME: Can we implicitly truncate the scalar if it is known to 4098 // be sign extended? 4099 // VL should be the last operand. 4100 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 4101 assert(VL.getValueType() == XLenVT); 4102 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4103 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4104 } 4105 4106 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4107 SelectionDAG &DAG) const { 4108 unsigned IntNo = Op.getConstantOperandVal(0); 4109 SDLoc DL(Op); 4110 MVT XLenVT = Subtarget.getXLenVT(); 4111 4112 switch (IntNo) { 4113 default: 4114 break; // Don't custom lower most intrinsics. 4115 case Intrinsic::thread_pointer: { 4116 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4117 return DAG.getRegister(RISCV::X4, PtrVT); 4118 } 4119 case Intrinsic::riscv_orc_b: 4120 // Lower to the GORCI encoding for orc.b. 4121 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 4122 DAG.getConstant(7, DL, XLenVT)); 4123 case Intrinsic::riscv_grev: 4124 case Intrinsic::riscv_gorc: { 4125 unsigned Opc = 4126 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4127 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4128 } 4129 case Intrinsic::riscv_shfl: 4130 case Intrinsic::riscv_unshfl: { 4131 unsigned Opc = 4132 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4133 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4134 } 4135 case Intrinsic::riscv_bcompress: 4136 case Intrinsic::riscv_bdecompress: { 4137 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4138 : RISCVISD::BDECOMPRESS; 4139 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4140 } 4141 case Intrinsic::riscv_vmv_x_s: 4142 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4143 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4144 Op.getOperand(1)); 4145 case Intrinsic::riscv_vmv_v_x: 4146 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4147 Op.getSimpleValueType(), DL, DAG, Subtarget); 4148 case Intrinsic::riscv_vfmv_v_f: 4149 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4150 Op.getOperand(1), Op.getOperand(2)); 4151 case Intrinsic::riscv_vmv_s_x: { 4152 SDValue Scalar = Op.getOperand(2); 4153 4154 if (Scalar.getValueType().bitsLE(XLenVT)) { 4155 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4156 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4157 Op.getOperand(1), Scalar, Op.getOperand(3)); 4158 } 4159 4160 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4161 4162 // This is an i64 value that lives in two scalar registers. We have to 4163 // insert this in a convoluted way. First we build vXi64 splat containing 4164 // the/ two values that we assemble using some bit math. Next we'll use 4165 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4166 // to merge element 0 from our splat into the source vector. 4167 // FIXME: This is probably not the best way to do this, but it is 4168 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4169 // point. 4170 // sw lo, (a0) 4171 // sw hi, 4(a0) 4172 // vlse vX, (a0) 4173 // 4174 // vid.v vVid 4175 // vmseq.vx mMask, vVid, 0 4176 // vmerge.vvm vDest, vSrc, vVal, mMask 4177 MVT VT = Op.getSimpleValueType(); 4178 SDValue Vec = Op.getOperand(1); 4179 SDValue VL = Op.getOperand(3); 4180 4181 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4182 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4183 DAG.getConstant(0, DL, MVT::i32), VL); 4184 4185 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4186 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4187 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4188 SDValue SelectCond = 4189 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4190 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4191 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4192 Vec, VL); 4193 } 4194 case Intrinsic::riscv_vslide1up: 4195 case Intrinsic::riscv_vslide1down: 4196 case Intrinsic::riscv_vslide1up_mask: 4197 case Intrinsic::riscv_vslide1down_mask: { 4198 // We need to special case these when the scalar is larger than XLen. 4199 unsigned NumOps = Op.getNumOperands(); 4200 bool IsMasked = NumOps == 7; 4201 unsigned OpOffset = IsMasked ? 1 : 0; 4202 SDValue Scalar = Op.getOperand(2 + OpOffset); 4203 if (Scalar.getValueType().bitsLE(XLenVT)) 4204 break; 4205 4206 // Splatting a sign extended constant is fine. 4207 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4208 if (isInt<32>(CVal->getSExtValue())) 4209 break; 4210 4211 MVT VT = Op.getSimpleValueType(); 4212 assert(VT.getVectorElementType() == MVT::i64 && 4213 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4214 4215 // Convert the vector source to the equivalent nxvXi32 vector. 4216 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4217 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4218 4219 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4220 DAG.getConstant(0, DL, XLenVT)); 4221 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4222 DAG.getConstant(1, DL, XLenVT)); 4223 4224 // Double the VL since we halved SEW. 4225 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 4226 SDValue I32VL = 4227 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4228 4229 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4230 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4231 4232 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4233 // instructions. 4234 if (IntNo == Intrinsic::riscv_vslide1up || 4235 IntNo == Intrinsic::riscv_vslide1up_mask) { 4236 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4237 I32Mask, I32VL); 4238 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4239 I32Mask, I32VL); 4240 } else { 4241 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4242 I32Mask, I32VL); 4243 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4244 I32Mask, I32VL); 4245 } 4246 4247 // Convert back to nxvXi64. 4248 Vec = DAG.getBitcast(VT, Vec); 4249 4250 if (!IsMasked) 4251 return Vec; 4252 4253 // Apply mask after the operation. 4254 SDValue Mask = Op.getOperand(NumOps - 3); 4255 SDValue MaskedOff = Op.getOperand(1); 4256 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4257 } 4258 } 4259 4260 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4261 } 4262 4263 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4264 SelectionDAG &DAG) const { 4265 unsigned IntNo = Op.getConstantOperandVal(1); 4266 switch (IntNo) { 4267 default: 4268 break; 4269 case Intrinsic::riscv_masked_strided_load: { 4270 SDLoc DL(Op); 4271 MVT XLenVT = Subtarget.getXLenVT(); 4272 4273 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4274 // the selection of the masked intrinsics doesn't do this for us. 4275 SDValue Mask = Op.getOperand(5); 4276 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4277 4278 MVT VT = Op->getSimpleValueType(0); 4279 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4280 4281 SDValue PassThru = Op.getOperand(2); 4282 if (!IsUnmasked) { 4283 MVT MaskVT = 4284 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4285 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4286 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4287 } 4288 4289 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4290 4291 SDValue IntID = DAG.getTargetConstant( 4292 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4293 XLenVT); 4294 4295 auto *Load = cast<MemIntrinsicSDNode>(Op); 4296 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4297 if (!IsUnmasked) 4298 Ops.push_back(PassThru); 4299 Ops.push_back(Op.getOperand(3)); // Ptr 4300 Ops.push_back(Op.getOperand(4)); // Stride 4301 if (!IsUnmasked) 4302 Ops.push_back(Mask); 4303 Ops.push_back(VL); 4304 if (!IsUnmasked) { 4305 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4306 Ops.push_back(Policy); 4307 } 4308 4309 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4310 SDValue Result = 4311 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4312 Load->getMemoryVT(), Load->getMemOperand()); 4313 SDValue Chain = Result.getValue(1); 4314 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4315 return DAG.getMergeValues({Result, Chain}, DL); 4316 } 4317 } 4318 4319 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4320 } 4321 4322 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4323 SelectionDAG &DAG) const { 4324 unsigned IntNo = Op.getConstantOperandVal(1); 4325 switch (IntNo) { 4326 default: 4327 break; 4328 case Intrinsic::riscv_masked_strided_store: { 4329 SDLoc DL(Op); 4330 MVT XLenVT = Subtarget.getXLenVT(); 4331 4332 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4333 // the selection of the masked intrinsics doesn't do this for us. 4334 SDValue Mask = Op.getOperand(5); 4335 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4336 4337 SDValue Val = Op.getOperand(2); 4338 MVT VT = Val.getSimpleValueType(); 4339 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4340 4341 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4342 if (!IsUnmasked) { 4343 MVT MaskVT = 4344 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4345 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4346 } 4347 4348 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4349 4350 SDValue IntID = DAG.getTargetConstant( 4351 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4352 XLenVT); 4353 4354 auto *Store = cast<MemIntrinsicSDNode>(Op); 4355 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4356 Ops.push_back(Val); 4357 Ops.push_back(Op.getOperand(3)); // Ptr 4358 Ops.push_back(Op.getOperand(4)); // Stride 4359 if (!IsUnmasked) 4360 Ops.push_back(Mask); 4361 Ops.push_back(VL); 4362 4363 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4364 Ops, Store->getMemoryVT(), 4365 Store->getMemOperand()); 4366 } 4367 } 4368 4369 return SDValue(); 4370 } 4371 4372 static MVT getLMUL1VT(MVT VT) { 4373 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4374 "Unexpected vector MVT"); 4375 return MVT::getScalableVectorVT( 4376 VT.getVectorElementType(), 4377 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4378 } 4379 4380 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4381 switch (ISDOpcode) { 4382 default: 4383 llvm_unreachable("Unhandled reduction"); 4384 case ISD::VECREDUCE_ADD: 4385 return RISCVISD::VECREDUCE_ADD_VL; 4386 case ISD::VECREDUCE_UMAX: 4387 return RISCVISD::VECREDUCE_UMAX_VL; 4388 case ISD::VECREDUCE_SMAX: 4389 return RISCVISD::VECREDUCE_SMAX_VL; 4390 case ISD::VECREDUCE_UMIN: 4391 return RISCVISD::VECREDUCE_UMIN_VL; 4392 case ISD::VECREDUCE_SMIN: 4393 return RISCVISD::VECREDUCE_SMIN_VL; 4394 case ISD::VECREDUCE_AND: 4395 return RISCVISD::VECREDUCE_AND_VL; 4396 case ISD::VECREDUCE_OR: 4397 return RISCVISD::VECREDUCE_OR_VL; 4398 case ISD::VECREDUCE_XOR: 4399 return RISCVISD::VECREDUCE_XOR_VL; 4400 } 4401 } 4402 4403 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4404 SelectionDAG &DAG, 4405 bool IsVP) const { 4406 SDLoc DL(Op); 4407 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4408 MVT VecVT = Vec.getSimpleValueType(); 4409 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4410 Op.getOpcode() == ISD::VECREDUCE_OR || 4411 Op.getOpcode() == ISD::VECREDUCE_XOR || 4412 Op.getOpcode() == ISD::VP_REDUCE_AND || 4413 Op.getOpcode() == ISD::VP_REDUCE_OR || 4414 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4415 "Unexpected reduction lowering"); 4416 4417 MVT XLenVT = Subtarget.getXLenVT(); 4418 assert(Op.getValueType() == XLenVT && 4419 "Expected reduction output to be legalized to XLenVT"); 4420 4421 MVT ContainerVT = VecVT; 4422 if (VecVT.isFixedLengthVector()) { 4423 ContainerVT = getContainerForFixedLengthVector(VecVT); 4424 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4425 } 4426 4427 SDValue Mask, VL; 4428 if (IsVP) { 4429 Mask = Op.getOperand(2); 4430 VL = Op.getOperand(3); 4431 } else { 4432 std::tie(Mask, VL) = 4433 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4434 } 4435 4436 unsigned BaseOpc; 4437 ISD::CondCode CC; 4438 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4439 4440 switch (Op.getOpcode()) { 4441 default: 4442 llvm_unreachable("Unhandled reduction"); 4443 case ISD::VECREDUCE_AND: 4444 case ISD::VP_REDUCE_AND: { 4445 // vcpop ~x == 0 4446 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4447 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4448 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4449 CC = ISD::SETEQ; 4450 BaseOpc = ISD::AND; 4451 break; 4452 } 4453 case ISD::VECREDUCE_OR: 4454 case ISD::VP_REDUCE_OR: 4455 // vcpop x != 0 4456 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4457 CC = ISD::SETNE; 4458 BaseOpc = ISD::OR; 4459 break; 4460 case ISD::VECREDUCE_XOR: 4461 case ISD::VP_REDUCE_XOR: { 4462 // ((vcpop x) & 1) != 0 4463 SDValue One = DAG.getConstant(1, DL, XLenVT); 4464 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4465 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4466 CC = ISD::SETNE; 4467 BaseOpc = ISD::XOR; 4468 break; 4469 } 4470 } 4471 4472 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4473 4474 if (!IsVP) 4475 return SetCC; 4476 4477 // Now include the start value in the operation. 4478 // Note that we must return the start value when no elements are operated 4479 // upon. The vcpop instructions we've emitted in each case above will return 4480 // 0 for an inactive vector, and so we've already received the neutral value: 4481 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4482 // can simply include the start value. 4483 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4484 } 4485 4486 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4487 SelectionDAG &DAG) const { 4488 SDLoc DL(Op); 4489 SDValue Vec = Op.getOperand(0); 4490 EVT VecEVT = Vec.getValueType(); 4491 4492 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4493 4494 // Due to ordering in legalize types we may have a vector type that needs to 4495 // be split. Do that manually so we can get down to a legal type. 4496 while (getTypeAction(*DAG.getContext(), VecEVT) == 4497 TargetLowering::TypeSplitVector) { 4498 SDValue Lo, Hi; 4499 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4500 VecEVT = Lo.getValueType(); 4501 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4502 } 4503 4504 // TODO: The type may need to be widened rather than split. Or widened before 4505 // it can be split. 4506 if (!isTypeLegal(VecEVT)) 4507 return SDValue(); 4508 4509 MVT VecVT = VecEVT.getSimpleVT(); 4510 MVT VecEltVT = VecVT.getVectorElementType(); 4511 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4512 4513 MVT ContainerVT = VecVT; 4514 if (VecVT.isFixedLengthVector()) { 4515 ContainerVT = getContainerForFixedLengthVector(VecVT); 4516 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4517 } 4518 4519 MVT M1VT = getLMUL1VT(ContainerVT); 4520 MVT XLenVT = Subtarget.getXLenVT(); 4521 4522 SDValue Mask, VL; 4523 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4524 4525 SDValue NeutralElem = 4526 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4527 SDValue IdentitySplat = lowerScalarSplat( 4528 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4529 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4530 IdentitySplat, Mask, VL); 4531 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4532 DAG.getConstant(0, DL, XLenVT)); 4533 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4534 } 4535 4536 // Given a reduction op, this function returns the matching reduction opcode, 4537 // the vector SDValue and the scalar SDValue required to lower this to a 4538 // RISCVISD node. 4539 static std::tuple<unsigned, SDValue, SDValue> 4540 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4541 SDLoc DL(Op); 4542 auto Flags = Op->getFlags(); 4543 unsigned Opcode = Op.getOpcode(); 4544 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4545 switch (Opcode) { 4546 default: 4547 llvm_unreachable("Unhandled reduction"); 4548 case ISD::VECREDUCE_FADD: { 4549 // Use positive zero if we can. It is cheaper to materialize. 4550 SDValue Zero = 4551 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4552 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4553 } 4554 case ISD::VECREDUCE_SEQ_FADD: 4555 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4556 Op.getOperand(0)); 4557 case ISD::VECREDUCE_FMIN: 4558 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4559 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4560 case ISD::VECREDUCE_FMAX: 4561 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4562 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4563 } 4564 } 4565 4566 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4567 SelectionDAG &DAG) const { 4568 SDLoc DL(Op); 4569 MVT VecEltVT = Op.getSimpleValueType(); 4570 4571 unsigned RVVOpcode; 4572 SDValue VectorVal, ScalarVal; 4573 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4574 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4575 MVT VecVT = VectorVal.getSimpleValueType(); 4576 4577 MVT ContainerVT = VecVT; 4578 if (VecVT.isFixedLengthVector()) { 4579 ContainerVT = getContainerForFixedLengthVector(VecVT); 4580 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4581 } 4582 4583 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4584 MVT XLenVT = Subtarget.getXLenVT(); 4585 4586 SDValue Mask, VL; 4587 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4588 4589 SDValue ScalarSplat = lowerScalarSplat( 4590 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4591 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4592 VectorVal, ScalarSplat, Mask, VL); 4593 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4594 DAG.getConstant(0, DL, XLenVT)); 4595 } 4596 4597 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4598 switch (ISDOpcode) { 4599 default: 4600 llvm_unreachable("Unhandled reduction"); 4601 case ISD::VP_REDUCE_ADD: 4602 return RISCVISD::VECREDUCE_ADD_VL; 4603 case ISD::VP_REDUCE_UMAX: 4604 return RISCVISD::VECREDUCE_UMAX_VL; 4605 case ISD::VP_REDUCE_SMAX: 4606 return RISCVISD::VECREDUCE_SMAX_VL; 4607 case ISD::VP_REDUCE_UMIN: 4608 return RISCVISD::VECREDUCE_UMIN_VL; 4609 case ISD::VP_REDUCE_SMIN: 4610 return RISCVISD::VECREDUCE_SMIN_VL; 4611 case ISD::VP_REDUCE_AND: 4612 return RISCVISD::VECREDUCE_AND_VL; 4613 case ISD::VP_REDUCE_OR: 4614 return RISCVISD::VECREDUCE_OR_VL; 4615 case ISD::VP_REDUCE_XOR: 4616 return RISCVISD::VECREDUCE_XOR_VL; 4617 case ISD::VP_REDUCE_FADD: 4618 return RISCVISD::VECREDUCE_FADD_VL; 4619 case ISD::VP_REDUCE_SEQ_FADD: 4620 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4621 case ISD::VP_REDUCE_FMAX: 4622 return RISCVISD::VECREDUCE_FMAX_VL; 4623 case ISD::VP_REDUCE_FMIN: 4624 return RISCVISD::VECREDUCE_FMIN_VL; 4625 } 4626 } 4627 4628 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4629 SelectionDAG &DAG) const { 4630 SDLoc DL(Op); 4631 SDValue Vec = Op.getOperand(1); 4632 EVT VecEVT = Vec.getValueType(); 4633 4634 // TODO: The type may need to be widened rather than split. Or widened before 4635 // it can be split. 4636 if (!isTypeLegal(VecEVT)) 4637 return SDValue(); 4638 4639 MVT VecVT = VecEVT.getSimpleVT(); 4640 MVT VecEltVT = VecVT.getVectorElementType(); 4641 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4642 4643 MVT ContainerVT = VecVT; 4644 if (VecVT.isFixedLengthVector()) { 4645 ContainerVT = getContainerForFixedLengthVector(VecVT); 4646 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4647 } 4648 4649 SDValue VL = Op.getOperand(3); 4650 SDValue Mask = Op.getOperand(2); 4651 4652 MVT M1VT = getLMUL1VT(ContainerVT); 4653 MVT XLenVT = Subtarget.getXLenVT(); 4654 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4655 4656 SDValue StartSplat = 4657 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 4658 DL, DAG, Subtarget); 4659 SDValue Reduction = 4660 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4661 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4662 DAG.getConstant(0, DL, XLenVT)); 4663 if (!VecVT.isInteger()) 4664 return Elt0; 4665 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4666 } 4667 4668 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4669 SelectionDAG &DAG) const { 4670 SDValue Vec = Op.getOperand(0); 4671 SDValue SubVec = Op.getOperand(1); 4672 MVT VecVT = Vec.getSimpleValueType(); 4673 MVT SubVecVT = SubVec.getSimpleValueType(); 4674 4675 SDLoc DL(Op); 4676 MVT XLenVT = Subtarget.getXLenVT(); 4677 unsigned OrigIdx = Op.getConstantOperandVal(2); 4678 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4679 4680 // We don't have the ability to slide mask vectors up indexed by their i1 4681 // elements; the smallest we can do is i8. Often we are able to bitcast to 4682 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4683 // into a scalable one, we might not necessarily have enough scalable 4684 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4685 if (SubVecVT.getVectorElementType() == MVT::i1 && 4686 (OrigIdx != 0 || !Vec.isUndef())) { 4687 if (VecVT.getVectorMinNumElements() >= 8 && 4688 SubVecVT.getVectorMinNumElements() >= 8) { 4689 assert(OrigIdx % 8 == 0 && "Invalid index"); 4690 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4691 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4692 "Unexpected mask vector lowering"); 4693 OrigIdx /= 8; 4694 SubVecVT = 4695 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4696 SubVecVT.isScalableVector()); 4697 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4698 VecVT.isScalableVector()); 4699 Vec = DAG.getBitcast(VecVT, Vec); 4700 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4701 } else { 4702 // We can't slide this mask vector up indexed by its i1 elements. 4703 // This poses a problem when we wish to insert a scalable vector which 4704 // can't be re-expressed as a larger type. Just choose the slow path and 4705 // extend to a larger type, then truncate back down. 4706 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4707 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4708 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4709 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4710 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4711 Op.getOperand(2)); 4712 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4713 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4714 } 4715 } 4716 4717 // If the subvector vector is a fixed-length type, we cannot use subregister 4718 // manipulation to simplify the codegen; we don't know which register of a 4719 // LMUL group contains the specific subvector as we only know the minimum 4720 // register size. Therefore we must slide the vector group up the full 4721 // amount. 4722 if (SubVecVT.isFixedLengthVector()) { 4723 if (OrigIdx == 0 && Vec.isUndef()) 4724 return Op; 4725 MVT ContainerVT = VecVT; 4726 if (VecVT.isFixedLengthVector()) { 4727 ContainerVT = getContainerForFixedLengthVector(VecVT); 4728 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4729 } 4730 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4731 DAG.getUNDEF(ContainerVT), SubVec, 4732 DAG.getConstant(0, DL, XLenVT)); 4733 SDValue Mask = 4734 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4735 // Set the vector length to only the number of elements we care about. Note 4736 // that for slideup this includes the offset. 4737 SDValue VL = 4738 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4739 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4740 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4741 SubVec, SlideupAmt, Mask, VL); 4742 if (VecVT.isFixedLengthVector()) 4743 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4744 return DAG.getBitcast(Op.getValueType(), Slideup); 4745 } 4746 4747 unsigned SubRegIdx, RemIdx; 4748 std::tie(SubRegIdx, RemIdx) = 4749 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4750 VecVT, SubVecVT, OrigIdx, TRI); 4751 4752 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4753 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4754 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4755 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4756 4757 // 1. If the Idx has been completely eliminated and this subvector's size is 4758 // a vector register or a multiple thereof, or the surrounding elements are 4759 // undef, then this is a subvector insert which naturally aligns to a vector 4760 // register. These can easily be handled using subregister manipulation. 4761 // 2. If the subvector is smaller than a vector register, then the insertion 4762 // must preserve the undisturbed elements of the register. We do this by 4763 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4764 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4765 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4766 // LMUL=1 type back into the larger vector (resolving to another subregister 4767 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4768 // to avoid allocating a large register group to hold our subvector. 4769 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4770 return Op; 4771 4772 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4773 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4774 // (in our case undisturbed). This means we can set up a subvector insertion 4775 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4776 // size of the subvector. 4777 MVT InterSubVT = VecVT; 4778 SDValue AlignedExtract = Vec; 4779 unsigned AlignedIdx = OrigIdx - RemIdx; 4780 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4781 InterSubVT = getLMUL1VT(VecVT); 4782 // Extract a subvector equal to the nearest full vector register type. This 4783 // should resolve to a EXTRACT_SUBREG instruction. 4784 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4785 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4786 } 4787 4788 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4789 // For scalable vectors this must be further multiplied by vscale. 4790 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4791 4792 SDValue Mask, VL; 4793 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4794 4795 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4796 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4797 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4798 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4799 4800 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4801 DAG.getUNDEF(InterSubVT), SubVec, 4802 DAG.getConstant(0, DL, XLenVT)); 4803 4804 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4805 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4806 4807 // If required, insert this subvector back into the correct vector register. 4808 // This should resolve to an INSERT_SUBREG instruction. 4809 if (VecVT.bitsGT(InterSubVT)) 4810 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4811 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4812 4813 // We might have bitcast from a mask type: cast back to the original type if 4814 // required. 4815 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4816 } 4817 4818 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4819 SelectionDAG &DAG) const { 4820 SDValue Vec = Op.getOperand(0); 4821 MVT SubVecVT = Op.getSimpleValueType(); 4822 MVT VecVT = Vec.getSimpleValueType(); 4823 4824 SDLoc DL(Op); 4825 MVT XLenVT = Subtarget.getXLenVT(); 4826 unsigned OrigIdx = Op.getConstantOperandVal(1); 4827 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4828 4829 // We don't have the ability to slide mask vectors down indexed by their i1 4830 // elements; the smallest we can do is i8. Often we are able to bitcast to 4831 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4832 // from a scalable one, we might not necessarily have enough scalable 4833 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4834 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4835 if (VecVT.getVectorMinNumElements() >= 8 && 4836 SubVecVT.getVectorMinNumElements() >= 8) { 4837 assert(OrigIdx % 8 == 0 && "Invalid index"); 4838 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4839 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4840 "Unexpected mask vector lowering"); 4841 OrigIdx /= 8; 4842 SubVecVT = 4843 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4844 SubVecVT.isScalableVector()); 4845 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4846 VecVT.isScalableVector()); 4847 Vec = DAG.getBitcast(VecVT, Vec); 4848 } else { 4849 // We can't slide this mask vector down, indexed by its i1 elements. 4850 // This poses a problem when we wish to extract a scalable vector which 4851 // can't be re-expressed as a larger type. Just choose the slow path and 4852 // extend to a larger type, then truncate back down. 4853 // TODO: We could probably improve this when extracting certain fixed 4854 // from fixed, where we can extract as i8 and shift the correct element 4855 // right to reach the desired subvector? 4856 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4857 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4858 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4859 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4860 Op.getOperand(1)); 4861 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4862 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4863 } 4864 } 4865 4866 // If the subvector vector is a fixed-length type, we cannot use subregister 4867 // manipulation to simplify the codegen; we don't know which register of a 4868 // LMUL group contains the specific subvector as we only know the minimum 4869 // register size. Therefore we must slide the vector group down the full 4870 // amount. 4871 if (SubVecVT.isFixedLengthVector()) { 4872 // With an index of 0 this is a cast-like subvector, which can be performed 4873 // with subregister operations. 4874 if (OrigIdx == 0) 4875 return Op; 4876 MVT ContainerVT = VecVT; 4877 if (VecVT.isFixedLengthVector()) { 4878 ContainerVT = getContainerForFixedLengthVector(VecVT); 4879 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4880 } 4881 SDValue Mask = 4882 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4883 // Set the vector length to only the number of elements we care about. This 4884 // avoids sliding down elements we're going to discard straight away. 4885 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4886 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4887 SDValue Slidedown = 4888 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4889 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4890 // Now we can use a cast-like subvector extract to get the result. 4891 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4892 DAG.getConstant(0, DL, XLenVT)); 4893 return DAG.getBitcast(Op.getValueType(), Slidedown); 4894 } 4895 4896 unsigned SubRegIdx, RemIdx; 4897 std::tie(SubRegIdx, RemIdx) = 4898 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4899 VecVT, SubVecVT, OrigIdx, TRI); 4900 4901 // If the Idx has been completely eliminated then this is a subvector extract 4902 // which naturally aligns to a vector register. These can easily be handled 4903 // using subregister manipulation. 4904 if (RemIdx == 0) 4905 return Op; 4906 4907 // Else we must shift our vector register directly to extract the subvector. 4908 // Do this using VSLIDEDOWN. 4909 4910 // If the vector type is an LMUL-group type, extract a subvector equal to the 4911 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4912 // instruction. 4913 MVT InterSubVT = VecVT; 4914 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4915 InterSubVT = getLMUL1VT(VecVT); 4916 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4917 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4918 } 4919 4920 // Slide this vector register down by the desired number of elements in order 4921 // to place the desired subvector starting at element 0. 4922 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4923 // For scalable vectors this must be further multiplied by vscale. 4924 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4925 4926 SDValue Mask, VL; 4927 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4928 SDValue Slidedown = 4929 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4930 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4931 4932 // Now the vector is in the right position, extract our final subvector. This 4933 // should resolve to a COPY. 4934 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4935 DAG.getConstant(0, DL, XLenVT)); 4936 4937 // We might have bitcast from a mask type: cast back to the original type if 4938 // required. 4939 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4940 } 4941 4942 // Lower step_vector to the vid instruction. Any non-identity step value must 4943 // be accounted for my manual expansion. 4944 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4945 SelectionDAG &DAG) const { 4946 SDLoc DL(Op); 4947 MVT VT = Op.getSimpleValueType(); 4948 MVT XLenVT = Subtarget.getXLenVT(); 4949 SDValue Mask, VL; 4950 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4951 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4952 uint64_t StepValImm = Op.getConstantOperandVal(0); 4953 if (StepValImm != 1) { 4954 if (isPowerOf2_64(StepValImm)) { 4955 SDValue StepVal = 4956 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4957 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4958 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4959 } else { 4960 SDValue StepVal = lowerScalarSplat( 4961 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4962 DL, DAG, Subtarget); 4963 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4964 } 4965 } 4966 return StepVec; 4967 } 4968 4969 // Implement vector_reverse using vrgather.vv with indices determined by 4970 // subtracting the id of each element from (VLMAX-1). This will convert 4971 // the indices like so: 4972 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4973 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4974 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4975 SelectionDAG &DAG) const { 4976 SDLoc DL(Op); 4977 MVT VecVT = Op.getSimpleValueType(); 4978 unsigned EltSize = VecVT.getScalarSizeInBits(); 4979 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4980 4981 unsigned MaxVLMAX = 0; 4982 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4983 if (VectorBitsMax != 0) 4984 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 4985 4986 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 4987 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 4988 4989 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 4990 // to use vrgatherei16.vv. 4991 // TODO: It's also possible to use vrgatherei16.vv for other types to 4992 // decrease register width for the index calculation. 4993 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 4994 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 4995 // Reverse each half, then reassemble them in reverse order. 4996 // NOTE: It's also possible that after splitting that VLMAX no longer 4997 // requires vrgatherei16.vv. 4998 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 4999 SDValue Lo, Hi; 5000 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5001 EVT LoVT, HiVT; 5002 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5003 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5004 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5005 // Reassemble the low and high pieces reversed. 5006 // FIXME: This is a CONCAT_VECTORS. 5007 SDValue Res = 5008 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5009 DAG.getIntPtrConstant(0, DL)); 5010 return DAG.getNode( 5011 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5012 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5013 } 5014 5015 // Just promote the int type to i16 which will double the LMUL. 5016 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5017 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5018 } 5019 5020 MVT XLenVT = Subtarget.getXLenVT(); 5021 SDValue Mask, VL; 5022 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5023 5024 // Calculate VLMAX-1 for the desired SEW. 5025 unsigned MinElts = VecVT.getVectorMinNumElements(); 5026 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5027 DAG.getConstant(MinElts, DL, XLenVT)); 5028 SDValue VLMinus1 = 5029 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5030 5031 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5032 bool IsRV32E64 = 5033 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5034 SDValue SplatVL; 5035 if (!IsRV32E64) 5036 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5037 else 5038 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5039 5040 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5041 SDValue Indices = 5042 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5043 5044 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5045 } 5046 5047 SDValue 5048 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5049 SelectionDAG &DAG) const { 5050 SDLoc DL(Op); 5051 auto *Load = cast<LoadSDNode>(Op); 5052 5053 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5054 Load->getMemoryVT(), 5055 *Load->getMemOperand()) && 5056 "Expecting a correctly-aligned load"); 5057 5058 MVT VT = Op.getSimpleValueType(); 5059 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5060 5061 SDValue VL = 5062 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5063 5064 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5065 SDValue NewLoad = DAG.getMemIntrinsicNode( 5066 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5067 Load->getMemoryVT(), Load->getMemOperand()); 5068 5069 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5070 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5071 } 5072 5073 SDValue 5074 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5075 SelectionDAG &DAG) const { 5076 SDLoc DL(Op); 5077 auto *Store = cast<StoreSDNode>(Op); 5078 5079 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5080 Store->getMemoryVT(), 5081 *Store->getMemOperand()) && 5082 "Expecting a correctly-aligned store"); 5083 5084 SDValue StoreVal = Store->getValue(); 5085 MVT VT = StoreVal.getSimpleValueType(); 5086 5087 // If the size less than a byte, we need to pad with zeros to make a byte. 5088 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5089 VT = MVT::v8i1; 5090 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5091 DAG.getConstant(0, DL, VT), StoreVal, 5092 DAG.getIntPtrConstant(0, DL)); 5093 } 5094 5095 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5096 5097 SDValue VL = 5098 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5099 5100 SDValue NewValue = 5101 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5102 return DAG.getMemIntrinsicNode( 5103 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5104 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5105 Store->getMemoryVT(), Store->getMemOperand()); 5106 } 5107 5108 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5109 SelectionDAG &DAG) const { 5110 SDLoc DL(Op); 5111 MVT VT = Op.getSimpleValueType(); 5112 5113 const auto *MemSD = cast<MemSDNode>(Op); 5114 EVT MemVT = MemSD->getMemoryVT(); 5115 MachineMemOperand *MMO = MemSD->getMemOperand(); 5116 SDValue Chain = MemSD->getChain(); 5117 SDValue BasePtr = MemSD->getBasePtr(); 5118 5119 SDValue Mask, PassThru, VL; 5120 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5121 Mask = VPLoad->getMask(); 5122 PassThru = DAG.getUNDEF(VT); 5123 VL = VPLoad->getVectorLength(); 5124 } else { 5125 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5126 Mask = MLoad->getMask(); 5127 PassThru = MLoad->getPassThru(); 5128 } 5129 5130 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5131 5132 MVT XLenVT = Subtarget.getXLenVT(); 5133 5134 MVT ContainerVT = VT; 5135 if (VT.isFixedLengthVector()) { 5136 ContainerVT = getContainerForFixedLengthVector(VT); 5137 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5138 if (!IsUnmasked) { 5139 MVT MaskVT = 5140 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5141 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5142 } 5143 } 5144 5145 if (!VL) 5146 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5147 5148 unsigned IntID = 5149 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5150 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5151 if (!IsUnmasked) 5152 Ops.push_back(PassThru); 5153 Ops.push_back(BasePtr); 5154 if (!IsUnmasked) 5155 Ops.push_back(Mask); 5156 Ops.push_back(VL); 5157 if (!IsUnmasked) 5158 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5159 5160 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5161 5162 SDValue Result = 5163 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5164 Chain = Result.getValue(1); 5165 5166 if (VT.isFixedLengthVector()) 5167 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5168 5169 return DAG.getMergeValues({Result, Chain}, DL); 5170 } 5171 5172 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5173 SelectionDAG &DAG) const { 5174 SDLoc DL(Op); 5175 5176 const auto *MemSD = cast<MemSDNode>(Op); 5177 EVT MemVT = MemSD->getMemoryVT(); 5178 MachineMemOperand *MMO = MemSD->getMemOperand(); 5179 SDValue Chain = MemSD->getChain(); 5180 SDValue BasePtr = MemSD->getBasePtr(); 5181 SDValue Val, Mask, VL; 5182 5183 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5184 Val = VPStore->getValue(); 5185 Mask = VPStore->getMask(); 5186 VL = VPStore->getVectorLength(); 5187 } else { 5188 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5189 Val = MStore->getValue(); 5190 Mask = MStore->getMask(); 5191 } 5192 5193 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5194 5195 MVT VT = Val.getSimpleValueType(); 5196 MVT XLenVT = Subtarget.getXLenVT(); 5197 5198 MVT ContainerVT = VT; 5199 if (VT.isFixedLengthVector()) { 5200 ContainerVT = getContainerForFixedLengthVector(VT); 5201 5202 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5203 if (!IsUnmasked) { 5204 MVT MaskVT = 5205 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5206 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5207 } 5208 } 5209 5210 if (!VL) 5211 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5212 5213 unsigned IntID = 5214 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5215 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5216 Ops.push_back(Val); 5217 Ops.push_back(BasePtr); 5218 if (!IsUnmasked) 5219 Ops.push_back(Mask); 5220 Ops.push_back(VL); 5221 5222 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5223 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5224 } 5225 5226 SDValue 5227 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5228 SelectionDAG &DAG) const { 5229 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5230 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5231 5232 MVT VT = Op.getSimpleValueType(); 5233 5234 SDValue Op1 = 5235 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5236 SDValue Op2 = 5237 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5238 5239 SDLoc DL(Op); 5240 SDValue VL = 5241 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5242 5243 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5244 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5245 5246 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5247 Op.getOperand(2), Mask, VL); 5248 5249 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5250 } 5251 5252 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5253 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5254 MVT VT = Op.getSimpleValueType(); 5255 5256 if (VT.getVectorElementType() == MVT::i1) 5257 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5258 5259 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5260 } 5261 5262 SDValue 5263 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5264 SelectionDAG &DAG) const { 5265 unsigned Opc; 5266 switch (Op.getOpcode()) { 5267 default: llvm_unreachable("Unexpected opcode!"); 5268 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5269 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5270 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5271 } 5272 5273 return lowerToScalableOp(Op, DAG, Opc); 5274 } 5275 5276 // Lower vector ABS to smax(X, sub(0, X)). 5277 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5278 SDLoc DL(Op); 5279 MVT VT = Op.getSimpleValueType(); 5280 SDValue X = Op.getOperand(0); 5281 5282 assert(VT.isFixedLengthVector() && "Unexpected type"); 5283 5284 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5285 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5286 5287 SDValue Mask, VL; 5288 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5289 5290 SDValue SplatZero = 5291 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5292 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5293 SDValue NegX = 5294 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5295 SDValue Max = 5296 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5297 5298 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5299 } 5300 5301 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5302 SDValue Op, SelectionDAG &DAG) const { 5303 SDLoc DL(Op); 5304 MVT VT = Op.getSimpleValueType(); 5305 SDValue Mag = Op.getOperand(0); 5306 SDValue Sign = Op.getOperand(1); 5307 assert(Mag.getValueType() == Sign.getValueType() && 5308 "Can only handle COPYSIGN with matching types."); 5309 5310 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5311 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5312 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5313 5314 SDValue Mask, VL; 5315 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5316 5317 SDValue CopySign = 5318 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5319 5320 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5321 } 5322 5323 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5324 SDValue Op, SelectionDAG &DAG) const { 5325 MVT VT = Op.getSimpleValueType(); 5326 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5327 5328 MVT I1ContainerVT = 5329 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5330 5331 SDValue CC = 5332 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5333 SDValue Op1 = 5334 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5335 SDValue Op2 = 5336 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5337 5338 SDLoc DL(Op); 5339 SDValue Mask, VL; 5340 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5341 5342 SDValue Select = 5343 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5344 5345 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5346 } 5347 5348 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5349 unsigned NewOpc, 5350 bool HasMask) const { 5351 MVT VT = Op.getSimpleValueType(); 5352 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5353 5354 // Create list of operands by converting existing ones to scalable types. 5355 SmallVector<SDValue, 6> Ops; 5356 for (const SDValue &V : Op->op_values()) { 5357 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5358 5359 // Pass through non-vector operands. 5360 if (!V.getValueType().isVector()) { 5361 Ops.push_back(V); 5362 continue; 5363 } 5364 5365 // "cast" fixed length vector to a scalable vector. 5366 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5367 "Only fixed length vectors are supported!"); 5368 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5369 } 5370 5371 SDLoc DL(Op); 5372 SDValue Mask, VL; 5373 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5374 if (HasMask) 5375 Ops.push_back(Mask); 5376 Ops.push_back(VL); 5377 5378 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5379 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5380 } 5381 5382 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5383 // * Operands of each node are assumed to be in the same order. 5384 // * The EVL operand is promoted from i32 to i64 on RV64. 5385 // * Fixed-length vectors are converted to their scalable-vector container 5386 // types. 5387 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5388 unsigned RISCVISDOpc) const { 5389 SDLoc DL(Op); 5390 MVT VT = Op.getSimpleValueType(); 5391 SmallVector<SDValue, 4> Ops; 5392 5393 for (const auto &OpIdx : enumerate(Op->ops())) { 5394 SDValue V = OpIdx.value(); 5395 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5396 // Pass through operands which aren't fixed-length vectors. 5397 if (!V.getValueType().isFixedLengthVector()) { 5398 Ops.push_back(V); 5399 continue; 5400 } 5401 // "cast" fixed length vector to a scalable vector. 5402 MVT OpVT = V.getSimpleValueType(); 5403 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5404 assert(useRVVForFixedLengthVectorVT(OpVT) && 5405 "Only fixed length vectors are supported!"); 5406 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5407 } 5408 5409 if (!VT.isFixedLengthVector()) 5410 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5411 5412 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5413 5414 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5415 5416 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5417 } 5418 5419 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5420 unsigned MaskOpc, 5421 unsigned VecOpc) const { 5422 MVT VT = Op.getSimpleValueType(); 5423 if (VT.getVectorElementType() != MVT::i1) 5424 return lowerVPOp(Op, DAG, VecOpc); 5425 5426 // It is safe to drop mask parameter as masked-off elements are undef. 5427 SDValue Op1 = Op->getOperand(0); 5428 SDValue Op2 = Op->getOperand(1); 5429 SDValue VL = Op->getOperand(3); 5430 5431 MVT ContainerVT = VT; 5432 const bool IsFixed = VT.isFixedLengthVector(); 5433 if (IsFixed) { 5434 ContainerVT = getContainerForFixedLengthVector(VT); 5435 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5436 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5437 } 5438 5439 SDLoc DL(Op); 5440 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5441 if (!IsFixed) 5442 return Val; 5443 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5444 } 5445 5446 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5447 // matched to a RVV indexed load. The RVV indexed load instructions only 5448 // support the "unsigned unscaled" addressing mode; indices are implicitly 5449 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5450 // signed or scaled indexing is extended to the XLEN value type and scaled 5451 // accordingly. 5452 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5453 SelectionDAG &DAG) const { 5454 SDLoc DL(Op); 5455 MVT VT = Op.getSimpleValueType(); 5456 5457 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5458 EVT MemVT = MemSD->getMemoryVT(); 5459 MachineMemOperand *MMO = MemSD->getMemOperand(); 5460 SDValue Chain = MemSD->getChain(); 5461 SDValue BasePtr = MemSD->getBasePtr(); 5462 5463 ISD::LoadExtType LoadExtType; 5464 SDValue Index, Mask, PassThru, VL; 5465 5466 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5467 Index = VPGN->getIndex(); 5468 Mask = VPGN->getMask(); 5469 PassThru = DAG.getUNDEF(VT); 5470 VL = VPGN->getVectorLength(); 5471 // VP doesn't support extending loads. 5472 LoadExtType = ISD::NON_EXTLOAD; 5473 } else { 5474 // Else it must be a MGATHER. 5475 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5476 Index = MGN->getIndex(); 5477 Mask = MGN->getMask(); 5478 PassThru = MGN->getPassThru(); 5479 LoadExtType = MGN->getExtensionType(); 5480 } 5481 5482 MVT IndexVT = Index.getSimpleValueType(); 5483 MVT XLenVT = Subtarget.getXLenVT(); 5484 5485 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5486 "Unexpected VTs!"); 5487 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5488 // Targets have to explicitly opt-in for extending vector loads. 5489 assert(LoadExtType == ISD::NON_EXTLOAD && 5490 "Unexpected extending MGATHER/VP_GATHER"); 5491 (void)LoadExtType; 5492 5493 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5494 // the selection of the masked intrinsics doesn't do this for us. 5495 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5496 5497 MVT ContainerVT = VT; 5498 if (VT.isFixedLengthVector()) { 5499 // We need to use the larger of the result and index type to determine the 5500 // scalable type to use so we don't increase LMUL for any operand/result. 5501 if (VT.bitsGE(IndexVT)) { 5502 ContainerVT = getContainerForFixedLengthVector(VT); 5503 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5504 ContainerVT.getVectorElementCount()); 5505 } else { 5506 IndexVT = getContainerForFixedLengthVector(IndexVT); 5507 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5508 IndexVT.getVectorElementCount()); 5509 } 5510 5511 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5512 5513 if (!IsUnmasked) { 5514 MVT MaskVT = 5515 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5516 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5517 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5518 } 5519 } 5520 5521 if (!VL) 5522 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5523 5524 unsigned IntID = 5525 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5526 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5527 if (!IsUnmasked) 5528 Ops.push_back(PassThru); 5529 Ops.push_back(BasePtr); 5530 Ops.push_back(Index); 5531 if (!IsUnmasked) 5532 Ops.push_back(Mask); 5533 Ops.push_back(VL); 5534 if (!IsUnmasked) 5535 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5536 5537 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5538 SDValue Result = 5539 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5540 Chain = Result.getValue(1); 5541 5542 if (VT.isFixedLengthVector()) 5543 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5544 5545 return DAG.getMergeValues({Result, Chain}, DL); 5546 } 5547 5548 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5549 // matched to a RVV indexed store. The RVV indexed store instructions only 5550 // support the "unsigned unscaled" addressing mode; indices are implicitly 5551 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5552 // signed or scaled indexing is extended to the XLEN value type and scaled 5553 // accordingly. 5554 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5555 SelectionDAG &DAG) const { 5556 SDLoc DL(Op); 5557 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5558 EVT MemVT = MemSD->getMemoryVT(); 5559 MachineMemOperand *MMO = MemSD->getMemOperand(); 5560 SDValue Chain = MemSD->getChain(); 5561 SDValue BasePtr = MemSD->getBasePtr(); 5562 5563 bool IsTruncatingStore = false; 5564 SDValue Index, Mask, Val, VL; 5565 5566 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5567 Index = VPSN->getIndex(); 5568 Mask = VPSN->getMask(); 5569 Val = VPSN->getValue(); 5570 VL = VPSN->getVectorLength(); 5571 // VP doesn't support truncating stores. 5572 IsTruncatingStore = false; 5573 } else { 5574 // Else it must be a MSCATTER. 5575 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5576 Index = MSN->getIndex(); 5577 Mask = MSN->getMask(); 5578 Val = MSN->getValue(); 5579 IsTruncatingStore = MSN->isTruncatingStore(); 5580 } 5581 5582 MVT VT = Val.getSimpleValueType(); 5583 MVT IndexVT = Index.getSimpleValueType(); 5584 MVT XLenVT = Subtarget.getXLenVT(); 5585 5586 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5587 "Unexpected VTs!"); 5588 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5589 // Targets have to explicitly opt-in for extending vector loads and 5590 // truncating vector stores. 5591 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5592 (void)IsTruncatingStore; 5593 5594 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5595 // the selection of the masked intrinsics doesn't do this for us. 5596 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5597 5598 MVT ContainerVT = VT; 5599 if (VT.isFixedLengthVector()) { 5600 // We need to use the larger of the value and index type to determine the 5601 // scalable type to use so we don't increase LMUL for any operand/result. 5602 if (VT.bitsGE(IndexVT)) { 5603 ContainerVT = getContainerForFixedLengthVector(VT); 5604 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5605 ContainerVT.getVectorElementCount()); 5606 } else { 5607 IndexVT = getContainerForFixedLengthVector(IndexVT); 5608 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5609 IndexVT.getVectorElementCount()); 5610 } 5611 5612 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5613 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5614 5615 if (!IsUnmasked) { 5616 MVT MaskVT = 5617 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5618 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5619 } 5620 } 5621 5622 if (!VL) 5623 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5624 5625 unsigned IntID = 5626 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5627 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5628 Ops.push_back(Val); 5629 Ops.push_back(BasePtr); 5630 Ops.push_back(Index); 5631 if (!IsUnmasked) 5632 Ops.push_back(Mask); 5633 Ops.push_back(VL); 5634 5635 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5636 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5637 } 5638 5639 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5640 SelectionDAG &DAG) const { 5641 const MVT XLenVT = Subtarget.getXLenVT(); 5642 SDLoc DL(Op); 5643 SDValue Chain = Op->getOperand(0); 5644 SDValue SysRegNo = DAG.getTargetConstant( 5645 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5646 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5647 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5648 5649 // Encoding used for rounding mode in RISCV differs from that used in 5650 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5651 // table, which consists of a sequence of 4-bit fields, each representing 5652 // corresponding FLT_ROUNDS mode. 5653 static const int Table = 5654 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5655 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5656 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5657 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5658 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5659 5660 SDValue Shift = 5661 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5662 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5663 DAG.getConstant(Table, DL, XLenVT), Shift); 5664 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5665 DAG.getConstant(7, DL, XLenVT)); 5666 5667 return DAG.getMergeValues({Masked, Chain}, DL); 5668 } 5669 5670 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5671 SelectionDAG &DAG) const { 5672 const MVT XLenVT = Subtarget.getXLenVT(); 5673 SDLoc DL(Op); 5674 SDValue Chain = Op->getOperand(0); 5675 SDValue RMValue = Op->getOperand(1); 5676 SDValue SysRegNo = DAG.getTargetConstant( 5677 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5678 5679 // Encoding used for rounding mode in RISCV differs from that used in 5680 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5681 // a table, which consists of a sequence of 4-bit fields, each representing 5682 // corresponding RISCV mode. 5683 static const unsigned Table = 5684 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5685 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5686 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5687 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5688 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5689 5690 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5691 DAG.getConstant(2, DL, XLenVT)); 5692 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5693 DAG.getConstant(Table, DL, XLenVT), Shift); 5694 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5695 DAG.getConstant(0x7, DL, XLenVT)); 5696 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5697 RMValue); 5698 } 5699 5700 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5701 // form of the given Opcode. 5702 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5703 switch (Opcode) { 5704 default: 5705 llvm_unreachable("Unexpected opcode"); 5706 case ISD::SHL: 5707 return RISCVISD::SLLW; 5708 case ISD::SRA: 5709 return RISCVISD::SRAW; 5710 case ISD::SRL: 5711 return RISCVISD::SRLW; 5712 case ISD::SDIV: 5713 return RISCVISD::DIVW; 5714 case ISD::UDIV: 5715 return RISCVISD::DIVUW; 5716 case ISD::UREM: 5717 return RISCVISD::REMUW; 5718 case ISD::ROTL: 5719 return RISCVISD::ROLW; 5720 case ISD::ROTR: 5721 return RISCVISD::RORW; 5722 case RISCVISD::GREV: 5723 return RISCVISD::GREVW; 5724 case RISCVISD::GORC: 5725 return RISCVISD::GORCW; 5726 } 5727 } 5728 5729 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5730 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5731 // otherwise be promoted to i64, making it difficult to select the 5732 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5733 // type i8/i16/i32 is lost. 5734 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5735 unsigned ExtOpc = ISD::ANY_EXTEND) { 5736 SDLoc DL(N); 5737 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5738 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5739 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5740 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5741 // ReplaceNodeResults requires we maintain the same type for the return value. 5742 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5743 } 5744 5745 // Converts the given 32-bit operation to a i64 operation with signed extension 5746 // semantic to reduce the signed extension instructions. 5747 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5748 SDLoc DL(N); 5749 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5750 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5751 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5752 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5753 DAG.getValueType(MVT::i32)); 5754 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5755 } 5756 5757 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5758 SmallVectorImpl<SDValue> &Results, 5759 SelectionDAG &DAG) const { 5760 SDLoc DL(N); 5761 switch (N->getOpcode()) { 5762 default: 5763 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5764 case ISD::STRICT_FP_TO_SINT: 5765 case ISD::STRICT_FP_TO_UINT: 5766 case ISD::FP_TO_SINT: 5767 case ISD::FP_TO_UINT: { 5768 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5769 "Unexpected custom legalisation"); 5770 bool IsStrict = N->isStrictFPOpcode(); 5771 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5772 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5773 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5774 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5775 TargetLowering::TypeSoftenFloat) { 5776 if (!isTypeLegal(Op0.getValueType())) 5777 return; 5778 if (IsStrict) { 5779 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RTZ_RV64 5780 : RISCVISD::STRICT_FCVT_WU_RTZ_RV64; 5781 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 5782 SDValue Res = DAG.getNode(Opc, DL, VTs, N->getOperand(0), Op0); 5783 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5784 Results.push_back(Res.getValue(1)); 5785 return; 5786 } 5787 unsigned Opc = 5788 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5789 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5790 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5791 return; 5792 } 5793 // If the FP type needs to be softened, emit a library call using the 'si' 5794 // version. If we left it to default legalization we'd end up with 'di'. If 5795 // the FP type doesn't need to be softened just let generic type 5796 // legalization promote the result type. 5797 RTLIB::Libcall LC; 5798 if (IsSigned) 5799 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5800 else 5801 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5802 MakeLibCallOptions CallOptions; 5803 EVT OpVT = Op0.getValueType(); 5804 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5805 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5806 SDValue Result; 5807 std::tie(Result, Chain) = 5808 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5809 Results.push_back(Result); 5810 if (IsStrict) 5811 Results.push_back(Chain); 5812 break; 5813 } 5814 case ISD::READCYCLECOUNTER: { 5815 assert(!Subtarget.is64Bit() && 5816 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5817 5818 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5819 SDValue RCW = 5820 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5821 5822 Results.push_back( 5823 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5824 Results.push_back(RCW.getValue(2)); 5825 break; 5826 } 5827 case ISD::MUL: { 5828 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5829 unsigned XLen = Subtarget.getXLen(); 5830 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5831 if (Size > XLen) { 5832 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5833 SDValue LHS = N->getOperand(0); 5834 SDValue RHS = N->getOperand(1); 5835 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5836 5837 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5838 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5839 // We need exactly one side to be unsigned. 5840 if (LHSIsU == RHSIsU) 5841 return; 5842 5843 auto MakeMULPair = [&](SDValue S, SDValue U) { 5844 MVT XLenVT = Subtarget.getXLenVT(); 5845 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5846 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5847 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5848 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5849 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5850 }; 5851 5852 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5853 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5854 5855 // The other operand should be signed, but still prefer MULH when 5856 // possible. 5857 if (RHSIsU && LHSIsS && !RHSIsS) 5858 Results.push_back(MakeMULPair(LHS, RHS)); 5859 else if (LHSIsU && RHSIsS && !LHSIsS) 5860 Results.push_back(MakeMULPair(RHS, LHS)); 5861 5862 return; 5863 } 5864 LLVM_FALLTHROUGH; 5865 } 5866 case ISD::ADD: 5867 case ISD::SUB: 5868 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5869 "Unexpected custom legalisation"); 5870 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5871 break; 5872 case ISD::SHL: 5873 case ISD::SRA: 5874 case ISD::SRL: 5875 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5876 "Unexpected custom legalisation"); 5877 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5878 Results.push_back(customLegalizeToWOp(N, DAG)); 5879 break; 5880 } 5881 5882 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5883 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5884 // shift amount. 5885 if (N->getOpcode() == ISD::SHL) { 5886 SDLoc DL(N); 5887 SDValue NewOp0 = 5888 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5889 SDValue NewOp1 = 5890 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5891 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5892 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5893 DAG.getValueType(MVT::i32)); 5894 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5895 } 5896 5897 break; 5898 case ISD::ROTL: 5899 case ISD::ROTR: 5900 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5901 "Unexpected custom legalisation"); 5902 Results.push_back(customLegalizeToWOp(N, DAG)); 5903 break; 5904 case ISD::CTTZ: 5905 case ISD::CTTZ_ZERO_UNDEF: 5906 case ISD::CTLZ: 5907 case ISD::CTLZ_ZERO_UNDEF: { 5908 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5909 "Unexpected custom legalisation"); 5910 5911 SDValue NewOp0 = 5912 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5913 bool IsCTZ = 5914 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5915 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5916 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5917 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5918 return; 5919 } 5920 case ISD::SDIV: 5921 case ISD::UDIV: 5922 case ISD::UREM: { 5923 MVT VT = N->getSimpleValueType(0); 5924 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5925 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5926 "Unexpected custom legalisation"); 5927 // Don't promote division/remainder by constant since we should expand those 5928 // to multiply by magic constant. 5929 // FIXME: What if the expansion is disabled for minsize. 5930 if (N->getOperand(1).getOpcode() == ISD::Constant) 5931 return; 5932 5933 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5934 // the upper 32 bits. For other types we need to sign or zero extend 5935 // based on the opcode. 5936 unsigned ExtOpc = ISD::ANY_EXTEND; 5937 if (VT != MVT::i32) 5938 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5939 : ISD::ZERO_EXTEND; 5940 5941 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5942 break; 5943 } 5944 case ISD::UADDO: 5945 case ISD::USUBO: { 5946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5947 "Unexpected custom legalisation"); 5948 bool IsAdd = N->getOpcode() == ISD::UADDO; 5949 // Create an ADDW or SUBW. 5950 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5951 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5952 SDValue Res = 5953 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5954 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5955 DAG.getValueType(MVT::i32)); 5956 5957 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5958 // Since the inputs are sign extended from i32, this is equivalent to 5959 // comparing the lower 32 bits. 5960 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5961 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5962 IsAdd ? ISD::SETULT : ISD::SETUGT); 5963 5964 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5965 Results.push_back(Overflow); 5966 return; 5967 } 5968 case ISD::UADDSAT: 5969 case ISD::USUBSAT: { 5970 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5971 "Unexpected custom legalisation"); 5972 if (Subtarget.hasStdExtZbb()) { 5973 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5974 // sign extend allows overflow of the lower 32 bits to be detected on 5975 // the promoted size. 5976 SDValue LHS = 5977 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5978 SDValue RHS = 5979 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5980 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5981 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5982 return; 5983 } 5984 5985 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 5986 // promotion for UADDO/USUBO. 5987 Results.push_back(expandAddSubSat(N, DAG)); 5988 return; 5989 } 5990 case ISD::BITCAST: { 5991 EVT VT = N->getValueType(0); 5992 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 5993 SDValue Op0 = N->getOperand(0); 5994 EVT Op0VT = Op0.getValueType(); 5995 MVT XLenVT = Subtarget.getXLenVT(); 5996 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 5997 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 5998 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 5999 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6000 Subtarget.hasStdExtF()) { 6001 SDValue FPConv = 6002 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6003 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6004 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6005 isTypeLegal(Op0VT)) { 6006 // Custom-legalize bitcasts from fixed-length vector types to illegal 6007 // scalar types in order to improve codegen. Bitcast the vector to a 6008 // one-element vector type whose element type is the same as the result 6009 // type, and extract the first element. 6010 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6011 if (isTypeLegal(BVT)) { 6012 SDValue BVec = DAG.getBitcast(BVT, Op0); 6013 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6014 DAG.getConstant(0, DL, XLenVT))); 6015 } 6016 } 6017 break; 6018 } 6019 case RISCVISD::GREV: 6020 case RISCVISD::GORC: { 6021 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6022 "Unexpected custom legalisation"); 6023 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6024 // This is similar to customLegalizeToWOp, except that we pass the second 6025 // operand (a TargetConstant) straight through: it is already of type 6026 // XLenVT. 6027 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6028 SDValue NewOp0 = 6029 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6030 SDValue NewOp1 = 6031 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6032 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6033 // ReplaceNodeResults requires we maintain the same type for the return 6034 // value. 6035 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6036 break; 6037 } 6038 case RISCVISD::SHFL: { 6039 // There is no SHFLIW instruction, but we can just promote the operation. 6040 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6041 "Unexpected custom legalisation"); 6042 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6043 SDValue NewOp0 = 6044 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6045 SDValue NewOp1 = 6046 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6047 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6048 // ReplaceNodeResults requires we maintain the same type for the return 6049 // value. 6050 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6051 break; 6052 } 6053 case ISD::BSWAP: 6054 case ISD::BITREVERSE: { 6055 MVT VT = N->getSimpleValueType(0); 6056 MVT XLenVT = Subtarget.getXLenVT(); 6057 assert((VT == MVT::i8 || VT == MVT::i16 || 6058 (VT == MVT::i32 && Subtarget.is64Bit())) && 6059 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6060 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6061 unsigned Imm = VT.getSizeInBits() - 1; 6062 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6063 if (N->getOpcode() == ISD::BSWAP) 6064 Imm &= ~0x7U; 6065 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6066 SDValue GREVI = 6067 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6068 // ReplaceNodeResults requires we maintain the same type for the return 6069 // value. 6070 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6071 break; 6072 } 6073 case ISD::FSHL: 6074 case ISD::FSHR: { 6075 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6076 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6077 SDValue NewOp0 = 6078 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6079 SDValue NewOp1 = 6080 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6081 SDValue NewOp2 = 6082 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6083 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6084 // Mask the shift amount to 5 bits. 6085 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6086 DAG.getConstant(0x1f, DL, MVT::i64)); 6087 unsigned Opc = 6088 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 6089 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 6090 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6091 break; 6092 } 6093 case ISD::EXTRACT_VECTOR_ELT: { 6094 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6095 // type is illegal (currently only vXi64 RV32). 6096 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6097 // transferred to the destination register. We issue two of these from the 6098 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6099 // first element. 6100 SDValue Vec = N->getOperand(0); 6101 SDValue Idx = N->getOperand(1); 6102 6103 // The vector type hasn't been legalized yet so we can't issue target 6104 // specific nodes if it needs legalization. 6105 // FIXME: We would manually legalize if it's important. 6106 if (!isTypeLegal(Vec.getValueType())) 6107 return; 6108 6109 MVT VecVT = Vec.getSimpleValueType(); 6110 6111 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6112 VecVT.getVectorElementType() == MVT::i64 && 6113 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6114 6115 // If this is a fixed vector, we need to convert it to a scalable vector. 6116 MVT ContainerVT = VecVT; 6117 if (VecVT.isFixedLengthVector()) { 6118 ContainerVT = getContainerForFixedLengthVector(VecVT); 6119 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6120 } 6121 6122 MVT XLenVT = Subtarget.getXLenVT(); 6123 6124 // Use a VL of 1 to avoid processing more elements than we need. 6125 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6126 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6127 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6128 6129 // Unless the index is known to be 0, we must slide the vector down to get 6130 // the desired element into index 0. 6131 if (!isNullConstant(Idx)) { 6132 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6133 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6134 } 6135 6136 // Extract the lower XLEN bits of the correct vector element. 6137 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6138 6139 // To extract the upper XLEN bits of the vector element, shift the first 6140 // element right by 32 bits and re-extract the lower XLEN bits. 6141 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6142 DAG.getConstant(32, DL, XLenVT), VL); 6143 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6144 ThirtyTwoV, Mask, VL); 6145 6146 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6147 6148 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6149 break; 6150 } 6151 case ISD::INTRINSIC_WO_CHAIN: { 6152 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6153 switch (IntNo) { 6154 default: 6155 llvm_unreachable( 6156 "Don't know how to custom type legalize this intrinsic!"); 6157 case Intrinsic::riscv_orc_b: { 6158 // Lower to the GORCI encoding for orc.b with the operand extended. 6159 SDValue NewOp = 6160 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6161 // If Zbp is enabled, use GORCIW which will sign extend the result. 6162 unsigned Opc = 6163 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6164 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6165 DAG.getConstant(7, DL, MVT::i64)); 6166 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6167 return; 6168 } 6169 case Intrinsic::riscv_grev: 6170 case Intrinsic::riscv_gorc: { 6171 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6172 "Unexpected custom legalisation"); 6173 SDValue NewOp1 = 6174 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6175 SDValue NewOp2 = 6176 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6177 unsigned Opc = 6178 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 6179 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6180 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6181 break; 6182 } 6183 case Intrinsic::riscv_shfl: 6184 case Intrinsic::riscv_unshfl: { 6185 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6186 "Unexpected custom legalisation"); 6187 SDValue NewOp1 = 6188 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6189 SDValue NewOp2 = 6190 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6191 unsigned Opc = 6192 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6193 if (isa<ConstantSDNode>(N->getOperand(2))) { 6194 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6195 DAG.getConstant(0xf, DL, MVT::i64)); 6196 Opc = 6197 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6198 } 6199 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6200 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6201 break; 6202 } 6203 case Intrinsic::riscv_bcompress: 6204 case Intrinsic::riscv_bdecompress: { 6205 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6206 "Unexpected custom legalisation"); 6207 SDValue NewOp1 = 6208 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6209 SDValue NewOp2 = 6210 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6211 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 6212 ? RISCVISD::BCOMPRESSW 6213 : RISCVISD::BDECOMPRESSW; 6214 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6215 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6216 break; 6217 } 6218 case Intrinsic::riscv_vmv_x_s: { 6219 EVT VT = N->getValueType(0); 6220 MVT XLenVT = Subtarget.getXLenVT(); 6221 if (VT.bitsLT(XLenVT)) { 6222 // Simple case just extract using vmv.x.s and truncate. 6223 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6224 Subtarget.getXLenVT(), N->getOperand(1)); 6225 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6226 return; 6227 } 6228 6229 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6230 "Unexpected custom legalization"); 6231 6232 // We need to do the move in two steps. 6233 SDValue Vec = N->getOperand(1); 6234 MVT VecVT = Vec.getSimpleValueType(); 6235 6236 // First extract the lower XLEN bits of the element. 6237 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6238 6239 // To extract the upper XLEN bits of the vector element, shift the first 6240 // element right by 32 bits and re-extract the lower XLEN bits. 6241 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6242 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6243 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6244 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6245 DAG.getConstant(32, DL, XLenVT), VL); 6246 SDValue LShr32 = 6247 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6248 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6249 6250 Results.push_back( 6251 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6252 break; 6253 } 6254 } 6255 break; 6256 } 6257 case ISD::VECREDUCE_ADD: 6258 case ISD::VECREDUCE_AND: 6259 case ISD::VECREDUCE_OR: 6260 case ISD::VECREDUCE_XOR: 6261 case ISD::VECREDUCE_SMAX: 6262 case ISD::VECREDUCE_UMAX: 6263 case ISD::VECREDUCE_SMIN: 6264 case ISD::VECREDUCE_UMIN: 6265 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6266 Results.push_back(V); 6267 break; 6268 case ISD::VP_REDUCE_ADD: 6269 case ISD::VP_REDUCE_AND: 6270 case ISD::VP_REDUCE_OR: 6271 case ISD::VP_REDUCE_XOR: 6272 case ISD::VP_REDUCE_SMAX: 6273 case ISD::VP_REDUCE_UMAX: 6274 case ISD::VP_REDUCE_SMIN: 6275 case ISD::VP_REDUCE_UMIN: 6276 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6277 Results.push_back(V); 6278 break; 6279 case ISD::FLT_ROUNDS_: { 6280 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6281 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6282 Results.push_back(Res.getValue(0)); 6283 Results.push_back(Res.getValue(1)); 6284 break; 6285 } 6286 } 6287 } 6288 6289 // A structure to hold one of the bit-manipulation patterns below. Together, a 6290 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6291 // (or (and (shl x, 1), 0xAAAAAAAA), 6292 // (and (srl x, 1), 0x55555555)) 6293 struct RISCVBitmanipPat { 6294 SDValue Op; 6295 unsigned ShAmt; 6296 bool IsSHL; 6297 6298 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6299 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6300 } 6301 }; 6302 6303 // Matches patterns of the form 6304 // (and (shl x, C2), (C1 << C2)) 6305 // (and (srl x, C2), C1) 6306 // (shl (and x, C1), C2) 6307 // (srl (and x, (C1 << C2)), C2) 6308 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6309 // The expected masks for each shift amount are specified in BitmanipMasks where 6310 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6311 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6312 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6313 // XLen is 64. 6314 static Optional<RISCVBitmanipPat> 6315 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6316 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6317 "Unexpected number of masks"); 6318 Optional<uint64_t> Mask; 6319 // Optionally consume a mask around the shift operation. 6320 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6321 Mask = Op.getConstantOperandVal(1); 6322 Op = Op.getOperand(0); 6323 } 6324 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6325 return None; 6326 bool IsSHL = Op.getOpcode() == ISD::SHL; 6327 6328 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6329 return None; 6330 uint64_t ShAmt = Op.getConstantOperandVal(1); 6331 6332 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6333 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6334 return None; 6335 // If we don't have enough masks for 64 bit, then we must be trying to 6336 // match SHFL so we're only allowed to shift 1/4 of the width. 6337 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6338 return None; 6339 6340 SDValue Src = Op.getOperand(0); 6341 6342 // The expected mask is shifted left when the AND is found around SHL 6343 // patterns. 6344 // ((x >> 1) & 0x55555555) 6345 // ((x << 1) & 0xAAAAAAAA) 6346 bool SHLExpMask = IsSHL; 6347 6348 if (!Mask) { 6349 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6350 // the mask is all ones: consume that now. 6351 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6352 Mask = Src.getConstantOperandVal(1); 6353 Src = Src.getOperand(0); 6354 // The expected mask is now in fact shifted left for SRL, so reverse the 6355 // decision. 6356 // ((x & 0xAAAAAAAA) >> 1) 6357 // ((x & 0x55555555) << 1) 6358 SHLExpMask = !SHLExpMask; 6359 } else { 6360 // Use a default shifted mask of all-ones if there's no AND, truncated 6361 // down to the expected width. This simplifies the logic later on. 6362 Mask = maskTrailingOnes<uint64_t>(Width); 6363 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6364 } 6365 } 6366 6367 unsigned MaskIdx = Log2_32(ShAmt); 6368 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6369 6370 if (SHLExpMask) 6371 ExpMask <<= ShAmt; 6372 6373 if (Mask != ExpMask) 6374 return None; 6375 6376 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6377 } 6378 6379 // Matches any of the following bit-manipulation patterns: 6380 // (and (shl x, 1), (0x55555555 << 1)) 6381 // (and (srl x, 1), 0x55555555) 6382 // (shl (and x, 0x55555555), 1) 6383 // (srl (and x, (0x55555555 << 1)), 1) 6384 // where the shift amount and mask may vary thus: 6385 // [1] = 0x55555555 / 0xAAAAAAAA 6386 // [2] = 0x33333333 / 0xCCCCCCCC 6387 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6388 // [8] = 0x00FF00FF / 0xFF00FF00 6389 // [16] = 0x0000FFFF / 0xFFFFFFFF 6390 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6391 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6392 // These are the unshifted masks which we use to match bit-manipulation 6393 // patterns. They may be shifted left in certain circumstances. 6394 static const uint64_t BitmanipMasks[] = { 6395 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6396 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6397 6398 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6399 } 6400 6401 // Match the following pattern as a GREVI(W) operation 6402 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6403 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6404 const RISCVSubtarget &Subtarget) { 6405 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6406 EVT VT = Op.getValueType(); 6407 6408 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6409 auto LHS = matchGREVIPat(Op.getOperand(0)); 6410 auto RHS = matchGREVIPat(Op.getOperand(1)); 6411 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6412 SDLoc DL(Op); 6413 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6414 DAG.getConstant(LHS->ShAmt, DL, VT)); 6415 } 6416 } 6417 return SDValue(); 6418 } 6419 6420 // Matches any the following pattern as a GORCI(W) operation 6421 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6422 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6423 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6424 // Note that with the variant of 3., 6425 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6426 // the inner pattern will first be matched as GREVI and then the outer 6427 // pattern will be matched to GORC via the first rule above. 6428 // 4. (or (rotl/rotr x, bitwidth/2), x) 6429 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6430 const RISCVSubtarget &Subtarget) { 6431 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6432 EVT VT = Op.getValueType(); 6433 6434 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6435 SDLoc DL(Op); 6436 SDValue Op0 = Op.getOperand(0); 6437 SDValue Op1 = Op.getOperand(1); 6438 6439 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6440 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6441 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6442 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6443 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6444 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6445 if ((Reverse.getOpcode() == ISD::ROTL || 6446 Reverse.getOpcode() == ISD::ROTR) && 6447 Reverse.getOperand(0) == X && 6448 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6449 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6450 if (RotAmt == (VT.getSizeInBits() / 2)) 6451 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6452 DAG.getConstant(RotAmt, DL, VT)); 6453 } 6454 return SDValue(); 6455 }; 6456 6457 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6458 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6459 return V; 6460 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6461 return V; 6462 6463 // OR is commutable so canonicalize its OR operand to the left 6464 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6465 std::swap(Op0, Op1); 6466 if (Op0.getOpcode() != ISD::OR) 6467 return SDValue(); 6468 SDValue OrOp0 = Op0.getOperand(0); 6469 SDValue OrOp1 = Op0.getOperand(1); 6470 auto LHS = matchGREVIPat(OrOp0); 6471 // OR is commutable so swap the operands and try again: x might have been 6472 // on the left 6473 if (!LHS) { 6474 std::swap(OrOp0, OrOp1); 6475 LHS = matchGREVIPat(OrOp0); 6476 } 6477 auto RHS = matchGREVIPat(Op1); 6478 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6479 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6480 DAG.getConstant(LHS->ShAmt, DL, VT)); 6481 } 6482 } 6483 return SDValue(); 6484 } 6485 6486 // Matches any of the following bit-manipulation patterns: 6487 // (and (shl x, 1), (0x22222222 << 1)) 6488 // (and (srl x, 1), 0x22222222) 6489 // (shl (and x, 0x22222222), 1) 6490 // (srl (and x, (0x22222222 << 1)), 1) 6491 // where the shift amount and mask may vary thus: 6492 // [1] = 0x22222222 / 0x44444444 6493 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6494 // [4] = 0x00F000F0 / 0x0F000F00 6495 // [8] = 0x0000FF00 / 0x00FF0000 6496 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6497 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6498 // These are the unshifted masks which we use to match bit-manipulation 6499 // patterns. They may be shifted left in certain circumstances. 6500 static const uint64_t BitmanipMasks[] = { 6501 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6502 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6503 6504 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6505 } 6506 6507 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6508 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6509 const RISCVSubtarget &Subtarget) { 6510 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6511 EVT VT = Op.getValueType(); 6512 6513 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6514 return SDValue(); 6515 6516 SDValue Op0 = Op.getOperand(0); 6517 SDValue Op1 = Op.getOperand(1); 6518 6519 // Or is commutable so canonicalize the second OR to the LHS. 6520 if (Op0.getOpcode() != ISD::OR) 6521 std::swap(Op0, Op1); 6522 if (Op0.getOpcode() != ISD::OR) 6523 return SDValue(); 6524 6525 // We found an inner OR, so our operands are the operands of the inner OR 6526 // and the other operand of the outer OR. 6527 SDValue A = Op0.getOperand(0); 6528 SDValue B = Op0.getOperand(1); 6529 SDValue C = Op1; 6530 6531 auto Match1 = matchSHFLPat(A); 6532 auto Match2 = matchSHFLPat(B); 6533 6534 // If neither matched, we failed. 6535 if (!Match1 && !Match2) 6536 return SDValue(); 6537 6538 // We had at least one match. if one failed, try the remaining C operand. 6539 if (!Match1) { 6540 std::swap(A, C); 6541 Match1 = matchSHFLPat(A); 6542 if (!Match1) 6543 return SDValue(); 6544 } else if (!Match2) { 6545 std::swap(B, C); 6546 Match2 = matchSHFLPat(B); 6547 if (!Match2) 6548 return SDValue(); 6549 } 6550 assert(Match1 && Match2); 6551 6552 // Make sure our matches pair up. 6553 if (!Match1->formsPairWith(*Match2)) 6554 return SDValue(); 6555 6556 // All the remains is to make sure C is an AND with the same input, that masks 6557 // out the bits that are being shuffled. 6558 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6559 C.getOperand(0) != Match1->Op) 6560 return SDValue(); 6561 6562 uint64_t Mask = C.getConstantOperandVal(1); 6563 6564 static const uint64_t BitmanipMasks[] = { 6565 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6566 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6567 }; 6568 6569 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6570 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6571 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6572 6573 if (Mask != ExpMask) 6574 return SDValue(); 6575 6576 SDLoc DL(Op); 6577 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6578 DAG.getConstant(Match1->ShAmt, DL, VT)); 6579 } 6580 6581 // Optimize (add (shl x, c0), (shl y, c1)) -> 6582 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6583 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6584 const RISCVSubtarget &Subtarget) { 6585 // Perform this optimization only in the zba extension. 6586 if (!Subtarget.hasStdExtZba()) 6587 return SDValue(); 6588 6589 // Skip for vector types and larger types. 6590 EVT VT = N->getValueType(0); 6591 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6592 return SDValue(); 6593 6594 // The two operand nodes must be SHL and have no other use. 6595 SDValue N0 = N->getOperand(0); 6596 SDValue N1 = N->getOperand(1); 6597 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6598 !N0->hasOneUse() || !N1->hasOneUse()) 6599 return SDValue(); 6600 6601 // Check c0 and c1. 6602 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6603 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6604 if (!N0C || !N1C) 6605 return SDValue(); 6606 int64_t C0 = N0C->getSExtValue(); 6607 int64_t C1 = N1C->getSExtValue(); 6608 if (C0 <= 0 || C1 <= 0) 6609 return SDValue(); 6610 6611 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6612 int64_t Bits = std::min(C0, C1); 6613 int64_t Diff = std::abs(C0 - C1); 6614 if (Diff != 1 && Diff != 2 && Diff != 3) 6615 return SDValue(); 6616 6617 // Build nodes. 6618 SDLoc DL(N); 6619 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6620 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6621 SDValue NA0 = 6622 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6623 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6624 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6625 } 6626 6627 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6628 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6629 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6630 // not undo itself, but they are redundant. 6631 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6632 SDValue Src = N->getOperand(0); 6633 6634 if (Src.getOpcode() != N->getOpcode()) 6635 return SDValue(); 6636 6637 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6638 !isa<ConstantSDNode>(Src.getOperand(1))) 6639 return SDValue(); 6640 6641 unsigned ShAmt1 = N->getConstantOperandVal(1); 6642 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6643 Src = Src.getOperand(0); 6644 6645 unsigned CombinedShAmt; 6646 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6647 CombinedShAmt = ShAmt1 | ShAmt2; 6648 else 6649 CombinedShAmt = ShAmt1 ^ ShAmt2; 6650 6651 if (CombinedShAmt == 0) 6652 return Src; 6653 6654 SDLoc DL(N); 6655 return DAG.getNode( 6656 N->getOpcode(), DL, N->getValueType(0), Src, 6657 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6658 } 6659 6660 // Combine a constant select operand into its use: 6661 // 6662 // (and (select cond, -1, c), x) 6663 // -> (select cond, x, (and x, c)) [AllOnes=1] 6664 // (or (select cond, 0, c), x) 6665 // -> (select cond, x, (or x, c)) [AllOnes=0] 6666 // (xor (select cond, 0, c), x) 6667 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6668 // (add (select cond, 0, c), x) 6669 // -> (select cond, x, (add x, c)) [AllOnes=0] 6670 // (sub x, (select cond, 0, c)) 6671 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6672 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6673 SelectionDAG &DAG, bool AllOnes) { 6674 EVT VT = N->getValueType(0); 6675 6676 // Skip vectors. 6677 if (VT.isVector()) 6678 return SDValue(); 6679 6680 if ((Slct.getOpcode() != ISD::SELECT && 6681 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6682 !Slct.hasOneUse()) 6683 return SDValue(); 6684 6685 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6686 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6687 }; 6688 6689 bool SwapSelectOps; 6690 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6691 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6692 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6693 SDValue NonConstantVal; 6694 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6695 SwapSelectOps = false; 6696 NonConstantVal = FalseVal; 6697 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6698 SwapSelectOps = true; 6699 NonConstantVal = TrueVal; 6700 } else 6701 return SDValue(); 6702 6703 // Slct is now know to be the desired identity constant when CC is true. 6704 TrueVal = OtherOp; 6705 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6706 // Unless SwapSelectOps says the condition should be false. 6707 if (SwapSelectOps) 6708 std::swap(TrueVal, FalseVal); 6709 6710 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6711 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6712 {Slct.getOperand(0), Slct.getOperand(1), 6713 Slct.getOperand(2), TrueVal, FalseVal}); 6714 6715 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6716 {Slct.getOperand(0), TrueVal, FalseVal}); 6717 } 6718 6719 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6720 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6721 bool AllOnes) { 6722 SDValue N0 = N->getOperand(0); 6723 SDValue N1 = N->getOperand(1); 6724 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6725 return Result; 6726 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6727 return Result; 6728 return SDValue(); 6729 } 6730 6731 // Transform (add (mul x, c0), c1) -> 6732 // (add (mul (add x, c1/c0), c0), c1%c0). 6733 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6734 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6735 // to an infinite loop in DAGCombine if transformed. 6736 // Or transform (add (mul x, c0), c1) -> 6737 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6738 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6739 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6740 // lead to an infinite loop in DAGCombine if transformed. 6741 // Or transform (add (mul x, c0), c1) -> 6742 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6743 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6744 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6745 // lead to an infinite loop in DAGCombine if transformed. 6746 // Or transform (add (mul x, c0), c1) -> 6747 // (mul (add x, c1/c0), c0). 6748 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6749 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6750 const RISCVSubtarget &Subtarget) { 6751 // Skip for vector types and larger types. 6752 EVT VT = N->getValueType(0); 6753 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6754 return SDValue(); 6755 // The first operand node must be a MUL and has no other use. 6756 SDValue N0 = N->getOperand(0); 6757 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6758 return SDValue(); 6759 // Check if c0 and c1 match above conditions. 6760 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6761 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6762 if (!N0C || !N1C) 6763 return SDValue(); 6764 int64_t C0 = N0C->getSExtValue(); 6765 int64_t C1 = N1C->getSExtValue(); 6766 int64_t CA, CB; 6767 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6768 return SDValue(); 6769 // Search for proper CA (non-zero) and CB that both are simm12. 6770 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6771 !isInt<12>(C0 * (C1 / C0))) { 6772 CA = C1 / C0; 6773 CB = C1 % C0; 6774 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6775 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6776 CA = C1 / C0 + 1; 6777 CB = C1 % C0 - C0; 6778 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6779 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6780 CA = C1 / C0 - 1; 6781 CB = C1 % C0 + C0; 6782 } else 6783 return SDValue(); 6784 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6785 SDLoc DL(N); 6786 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6787 DAG.getConstant(CA, DL, VT)); 6788 SDValue New1 = 6789 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6790 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6791 } 6792 6793 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6794 const RISCVSubtarget &Subtarget) { 6795 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6796 return V; 6797 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6798 return V; 6799 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6800 // (select lhs, rhs, cc, x, (add x, y)) 6801 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6802 } 6803 6804 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6805 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6806 // (select lhs, rhs, cc, x, (sub x, y)) 6807 SDValue N0 = N->getOperand(0); 6808 SDValue N1 = N->getOperand(1); 6809 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6810 } 6811 6812 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6813 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6814 // (select lhs, rhs, cc, x, (and x, y)) 6815 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6816 } 6817 6818 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6819 const RISCVSubtarget &Subtarget) { 6820 if (Subtarget.hasStdExtZbp()) { 6821 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6822 return GREV; 6823 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6824 return GORC; 6825 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6826 return SHFL; 6827 } 6828 6829 // fold (or (select cond, 0, y), x) -> 6830 // (select cond, x, (or x, y)) 6831 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6832 } 6833 6834 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6835 // fold (xor (select cond, 0, y), x) -> 6836 // (select cond, x, (xor x, y)) 6837 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6838 } 6839 6840 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6841 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6842 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6843 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6844 // ADDW/SUBW/MULW. 6845 static SDValue performANY_EXTENDCombine(SDNode *N, 6846 TargetLowering::DAGCombinerInfo &DCI, 6847 const RISCVSubtarget &Subtarget) { 6848 if (!Subtarget.is64Bit()) 6849 return SDValue(); 6850 6851 SelectionDAG &DAG = DCI.DAG; 6852 6853 SDValue Src = N->getOperand(0); 6854 EVT VT = N->getValueType(0); 6855 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6856 return SDValue(); 6857 6858 // The opcode must be one that can implicitly sign_extend. 6859 // FIXME: Additional opcodes. 6860 switch (Src.getOpcode()) { 6861 default: 6862 return SDValue(); 6863 case ISD::MUL: 6864 if (!Subtarget.hasStdExtM()) 6865 return SDValue(); 6866 LLVM_FALLTHROUGH; 6867 case ISD::ADD: 6868 case ISD::SUB: 6869 break; 6870 } 6871 6872 // Only handle cases where the result is used by a CopyToReg. That likely 6873 // means the value is a liveout of the basic block. This helps prevent 6874 // infinite combine loops like PR51206. 6875 if (none_of(N->uses(), 6876 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6877 return SDValue(); 6878 6879 SmallVector<SDNode *, 4> SetCCs; 6880 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6881 UE = Src.getNode()->use_end(); 6882 UI != UE; ++UI) { 6883 SDNode *User = *UI; 6884 if (User == N) 6885 continue; 6886 if (UI.getUse().getResNo() != Src.getResNo()) 6887 continue; 6888 // All i32 setccs are legalized by sign extending operands. 6889 if (User->getOpcode() == ISD::SETCC) { 6890 SetCCs.push_back(User); 6891 continue; 6892 } 6893 // We don't know if we can extend this user. 6894 break; 6895 } 6896 6897 // If we don't have any SetCCs, this isn't worthwhile. 6898 if (SetCCs.empty()) 6899 return SDValue(); 6900 6901 SDLoc DL(N); 6902 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6903 DCI.CombineTo(N, SExt); 6904 6905 // Promote all the setccs. 6906 for (SDNode *SetCC : SetCCs) { 6907 SmallVector<SDValue, 4> Ops; 6908 6909 for (unsigned j = 0; j != 2; ++j) { 6910 SDValue SOp = SetCC->getOperand(j); 6911 if (SOp == Src) 6912 Ops.push_back(SExt); 6913 else 6914 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6915 } 6916 6917 Ops.push_back(SetCC->getOperand(2)); 6918 DCI.CombineTo(SetCC, 6919 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6920 } 6921 return SDValue(N, 0); 6922 } 6923 6924 // Try to form VWMUL or VWMULU. 6925 // FIXME: Support VWMULSU. 6926 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6927 SelectionDAG &DAG) { 6928 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6929 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6930 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6931 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6932 return SDValue(); 6933 6934 SDValue Mask = N->getOperand(2); 6935 SDValue VL = N->getOperand(3); 6936 6937 // Make sure the mask and VL match. 6938 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6939 return SDValue(); 6940 6941 MVT VT = N->getSimpleValueType(0); 6942 6943 // Determine the narrow size for a widening multiply. 6944 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 6945 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 6946 VT.getVectorElementCount()); 6947 6948 SDLoc DL(N); 6949 6950 // See if the other operand is the same opcode. 6951 if (Op0.getOpcode() == Op1.getOpcode()) { 6952 if (!Op1.hasOneUse()) 6953 return SDValue(); 6954 6955 // Make sure the mask and VL match. 6956 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 6957 return SDValue(); 6958 6959 Op1 = Op1.getOperand(0); 6960 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 6961 // The operand is a splat of a scalar. 6962 6963 // The VL must be the same. 6964 if (Op1.getOperand(1) != VL) 6965 return SDValue(); 6966 6967 // Get the scalar value. 6968 Op1 = Op1.getOperand(0); 6969 6970 // See if have enough sign bits or zero bits in the scalar to use a 6971 // widening multiply by splatting to smaller element size. 6972 unsigned EltBits = VT.getScalarSizeInBits(); 6973 unsigned ScalarBits = Op1.getValueSizeInBits(); 6974 // Make sure we're getting all element bits from the scalar register. 6975 // FIXME: Support implicit sign extension of vmv.v.x? 6976 if (ScalarBits < EltBits) 6977 return SDValue(); 6978 6979 if (IsSignExt) { 6980 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 6981 return SDValue(); 6982 } else { 6983 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 6984 if (!DAG.MaskedValueIsZero(Op1, Mask)) 6985 return SDValue(); 6986 } 6987 6988 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 6989 } else 6990 return SDValue(); 6991 6992 Op0 = Op0.getOperand(0); 6993 6994 // Re-introduce narrower extends if needed. 6995 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 6996 if (Op0.getValueType() != NarrowVT) 6997 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 6998 if (Op1.getValueType() != NarrowVT) 6999 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7000 7001 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7002 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7003 } 7004 7005 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7006 DAGCombinerInfo &DCI) const { 7007 SelectionDAG &DAG = DCI.DAG; 7008 7009 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7010 // bits are demanded. N will be added to the Worklist if it was not deleted. 7011 // Caller should return SDValue(N, 0) if this returns true. 7012 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7013 SDValue Op = N->getOperand(OpNo); 7014 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7015 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7016 return false; 7017 7018 if (N->getOpcode() != ISD::DELETED_NODE) 7019 DCI.AddToWorklist(N); 7020 return true; 7021 }; 7022 7023 switch (N->getOpcode()) { 7024 default: 7025 break; 7026 case RISCVISD::SplitF64: { 7027 SDValue Op0 = N->getOperand(0); 7028 // If the input to SplitF64 is just BuildPairF64 then the operation is 7029 // redundant. Instead, use BuildPairF64's operands directly. 7030 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7031 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7032 7033 SDLoc DL(N); 7034 7035 // It's cheaper to materialise two 32-bit integers than to load a double 7036 // from the constant pool and transfer it to integer registers through the 7037 // stack. 7038 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7039 APInt V = C->getValueAPF().bitcastToAPInt(); 7040 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7041 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7042 return DCI.CombineTo(N, Lo, Hi); 7043 } 7044 7045 // This is a target-specific version of a DAGCombine performed in 7046 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7047 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7048 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7049 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7050 !Op0.getNode()->hasOneUse()) 7051 break; 7052 SDValue NewSplitF64 = 7053 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7054 Op0.getOperand(0)); 7055 SDValue Lo = NewSplitF64.getValue(0); 7056 SDValue Hi = NewSplitF64.getValue(1); 7057 APInt SignBit = APInt::getSignMask(32); 7058 if (Op0.getOpcode() == ISD::FNEG) { 7059 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7060 DAG.getConstant(SignBit, DL, MVT::i32)); 7061 return DCI.CombineTo(N, Lo, NewHi); 7062 } 7063 assert(Op0.getOpcode() == ISD::FABS); 7064 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7065 DAG.getConstant(~SignBit, DL, MVT::i32)); 7066 return DCI.CombineTo(N, Lo, NewHi); 7067 } 7068 case RISCVISD::SLLW: 7069 case RISCVISD::SRAW: 7070 case RISCVISD::SRLW: 7071 case RISCVISD::ROLW: 7072 case RISCVISD::RORW: { 7073 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7074 if (SimplifyDemandedLowBitsHelper(0, 32) || 7075 SimplifyDemandedLowBitsHelper(1, 5)) 7076 return SDValue(N, 0); 7077 break; 7078 } 7079 case RISCVISD::CLZW: 7080 case RISCVISD::CTZW: { 7081 // Only the lower 32 bits of the first operand are read 7082 if (SimplifyDemandedLowBitsHelper(0, 32)) 7083 return SDValue(N, 0); 7084 break; 7085 } 7086 case RISCVISD::FSL: 7087 case RISCVISD::FSR: { 7088 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 7089 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 7090 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7091 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 7092 return SDValue(N, 0); 7093 break; 7094 } 7095 case RISCVISD::FSLW: 7096 case RISCVISD::FSRW: { 7097 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 7098 // read. 7099 if (SimplifyDemandedLowBitsHelper(0, 32) || 7100 SimplifyDemandedLowBitsHelper(1, 32) || 7101 SimplifyDemandedLowBitsHelper(2, 6)) 7102 return SDValue(N, 0); 7103 break; 7104 } 7105 case RISCVISD::GREV: 7106 case RISCVISD::GORC: { 7107 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7108 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7109 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7110 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7111 return SDValue(N, 0); 7112 7113 return combineGREVI_GORCI(N, DAG); 7114 } 7115 case RISCVISD::GREVW: 7116 case RISCVISD::GORCW: { 7117 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7118 if (SimplifyDemandedLowBitsHelper(0, 32) || 7119 SimplifyDemandedLowBitsHelper(1, 5)) 7120 return SDValue(N, 0); 7121 7122 return combineGREVI_GORCI(N, DAG); 7123 } 7124 case RISCVISD::SHFL: 7125 case RISCVISD::UNSHFL: { 7126 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7127 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7128 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7129 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7130 return SDValue(N, 0); 7131 7132 break; 7133 } 7134 case RISCVISD::SHFLW: 7135 case RISCVISD::UNSHFLW: { 7136 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7137 SDValue LHS = N->getOperand(0); 7138 SDValue RHS = N->getOperand(1); 7139 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 7140 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 7141 if (SimplifyDemandedLowBitsHelper(0, 32) || 7142 SimplifyDemandedLowBitsHelper(1, 4)) 7143 return SDValue(N, 0); 7144 7145 break; 7146 } 7147 case RISCVISD::BCOMPRESSW: 7148 case RISCVISD::BDECOMPRESSW: { 7149 // Only the lower 32 bits of LHS and RHS are read. 7150 if (SimplifyDemandedLowBitsHelper(0, 32) || 7151 SimplifyDemandedLowBitsHelper(1, 32)) 7152 return SDValue(N, 0); 7153 7154 break; 7155 } 7156 case RISCVISD::FMV_X_ANYEXTH: 7157 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7158 SDLoc DL(N); 7159 SDValue Op0 = N->getOperand(0); 7160 MVT VT = N->getSimpleValueType(0); 7161 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7162 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7163 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7164 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7165 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7166 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7167 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7168 assert(Op0.getOperand(0).getValueType() == VT && 7169 "Unexpected value type!"); 7170 return Op0.getOperand(0); 7171 } 7172 7173 // This is a target-specific version of a DAGCombine performed in 7174 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7175 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7176 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7177 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7178 !Op0.getNode()->hasOneUse()) 7179 break; 7180 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7181 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7182 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7183 if (Op0.getOpcode() == ISD::FNEG) 7184 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7185 DAG.getConstant(SignBit, DL, VT)); 7186 7187 assert(Op0.getOpcode() == ISD::FABS); 7188 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7189 DAG.getConstant(~SignBit, DL, VT)); 7190 } 7191 case ISD::ADD: 7192 return performADDCombine(N, DAG, Subtarget); 7193 case ISD::SUB: 7194 return performSUBCombine(N, DAG); 7195 case ISD::AND: 7196 return performANDCombine(N, DAG); 7197 case ISD::OR: 7198 return performORCombine(N, DAG, Subtarget); 7199 case ISD::XOR: 7200 return performXORCombine(N, DAG); 7201 case ISD::ANY_EXTEND: 7202 return performANY_EXTENDCombine(N, DCI, Subtarget); 7203 case ISD::ZERO_EXTEND: 7204 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7205 // type legalization. This is safe because fp_to_uint produces poison if 7206 // it overflows. 7207 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7208 SDValue Src = N->getOperand(0); 7209 if (Src.getOpcode() == ISD::FP_TO_UINT && 7210 isTypeLegal(Src.getOperand(0).getValueType())) 7211 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7212 Src.getOperand(0)); 7213 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7214 isTypeLegal(Src.getOperand(1).getValueType())) { 7215 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7216 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7217 Src.getOperand(0), Src.getOperand(1)); 7218 DCI.CombineTo(N, Res); 7219 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7220 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7221 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7222 } 7223 } 7224 return SDValue(); 7225 case RISCVISD::SELECT_CC: { 7226 // Transform 7227 SDValue LHS = N->getOperand(0); 7228 SDValue RHS = N->getOperand(1); 7229 SDValue TrueV = N->getOperand(3); 7230 SDValue FalseV = N->getOperand(4); 7231 7232 // If the True and False values are the same, we don't need a select_cc. 7233 if (TrueV == FalseV) 7234 return TrueV; 7235 7236 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7237 if (!ISD::isIntEqualitySetCC(CCVal)) 7238 break; 7239 7240 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7241 // (select_cc X, Y, lt, trueV, falseV) 7242 // Sometimes the setcc is introduced after select_cc has been formed. 7243 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7244 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7245 // If we're looking for eq 0 instead of ne 0, we need to invert the 7246 // condition. 7247 bool Invert = CCVal == ISD::SETEQ; 7248 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7249 if (Invert) 7250 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7251 7252 SDLoc DL(N); 7253 RHS = LHS.getOperand(1); 7254 LHS = LHS.getOperand(0); 7255 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7256 7257 SDValue TargetCC = DAG.getCondCode(CCVal); 7258 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7259 {LHS, RHS, TargetCC, TrueV, FalseV}); 7260 } 7261 7262 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7263 // (select_cc X, Y, eq/ne, trueV, falseV) 7264 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7265 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7266 {LHS.getOperand(0), LHS.getOperand(1), 7267 N->getOperand(2), TrueV, FalseV}); 7268 // (select_cc X, 1, setne, trueV, falseV) -> 7269 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7270 // This can occur when legalizing some floating point comparisons. 7271 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7272 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7273 SDLoc DL(N); 7274 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7275 SDValue TargetCC = DAG.getCondCode(CCVal); 7276 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7277 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7278 {LHS, RHS, TargetCC, TrueV, FalseV}); 7279 } 7280 7281 break; 7282 } 7283 case RISCVISD::BR_CC: { 7284 SDValue LHS = N->getOperand(1); 7285 SDValue RHS = N->getOperand(2); 7286 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7287 if (!ISD::isIntEqualitySetCC(CCVal)) 7288 break; 7289 7290 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7291 // (br_cc X, Y, lt, dest) 7292 // Sometimes the setcc is introduced after br_cc has been formed. 7293 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7294 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7295 // If we're looking for eq 0 instead of ne 0, we need to invert the 7296 // condition. 7297 bool Invert = CCVal == ISD::SETEQ; 7298 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7299 if (Invert) 7300 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7301 7302 SDLoc DL(N); 7303 RHS = LHS.getOperand(1); 7304 LHS = LHS.getOperand(0); 7305 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7306 7307 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7308 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7309 N->getOperand(4)); 7310 } 7311 7312 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7313 // (br_cc X, Y, eq/ne, trueV, falseV) 7314 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7315 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7316 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7317 N->getOperand(3), N->getOperand(4)); 7318 7319 // (br_cc X, 1, setne, br_cc) -> 7320 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7321 // This can occur when legalizing some floating point comparisons. 7322 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7323 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7324 SDLoc DL(N); 7325 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7326 SDValue TargetCC = DAG.getCondCode(CCVal); 7327 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7328 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7329 N->getOperand(0), LHS, RHS, TargetCC, 7330 N->getOperand(4)); 7331 } 7332 break; 7333 } 7334 case ISD::FCOPYSIGN: { 7335 EVT VT = N->getValueType(0); 7336 if (!VT.isVector()) 7337 break; 7338 // There is a form of VFSGNJ which injects the negated sign of its second 7339 // operand. Try and bubble any FNEG up after the extend/round to produce 7340 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7341 // TRUNC=1. 7342 SDValue In2 = N->getOperand(1); 7343 // Avoid cases where the extend/round has multiple uses, as duplicating 7344 // those is typically more expensive than removing a fneg. 7345 if (!In2.hasOneUse()) 7346 break; 7347 if (In2.getOpcode() != ISD::FP_EXTEND && 7348 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7349 break; 7350 In2 = In2.getOperand(0); 7351 if (In2.getOpcode() != ISD::FNEG) 7352 break; 7353 SDLoc DL(N); 7354 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7355 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7356 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7357 } 7358 case ISD::MGATHER: 7359 case ISD::MSCATTER: 7360 case ISD::VP_GATHER: 7361 case ISD::VP_SCATTER: { 7362 if (!DCI.isBeforeLegalize()) 7363 break; 7364 SDValue Index, ScaleOp; 7365 bool IsIndexScaled = false; 7366 bool IsIndexSigned = false; 7367 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7368 Index = VPGSN->getIndex(); 7369 ScaleOp = VPGSN->getScale(); 7370 IsIndexScaled = VPGSN->isIndexScaled(); 7371 IsIndexSigned = VPGSN->isIndexSigned(); 7372 } else { 7373 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7374 Index = MGSN->getIndex(); 7375 ScaleOp = MGSN->getScale(); 7376 IsIndexScaled = MGSN->isIndexScaled(); 7377 IsIndexSigned = MGSN->isIndexSigned(); 7378 } 7379 EVT IndexVT = Index.getValueType(); 7380 MVT XLenVT = Subtarget.getXLenVT(); 7381 // RISCV indexed loads only support the "unsigned unscaled" addressing 7382 // mode, so anything else must be manually legalized. 7383 bool NeedsIdxLegalization = 7384 IsIndexScaled || 7385 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7386 if (!NeedsIdxLegalization) 7387 break; 7388 7389 SDLoc DL(N); 7390 7391 // Any index legalization should first promote to XLenVT, so we don't lose 7392 // bits when scaling. This may create an illegal index type so we let 7393 // LLVM's legalization take care of the splitting. 7394 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7395 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7396 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7397 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7398 DL, IndexVT, Index); 7399 } 7400 7401 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7402 if (IsIndexScaled && Scale != 1) { 7403 // Manually scale the indices by the element size. 7404 // TODO: Sanitize the scale operand here? 7405 // TODO: For VP nodes, should we use VP_SHL here? 7406 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7407 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7408 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7409 } 7410 7411 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7412 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7413 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7414 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7415 VPGN->getScale(), VPGN->getMask(), 7416 VPGN->getVectorLength()}, 7417 VPGN->getMemOperand(), NewIndexTy); 7418 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7419 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7420 {VPSN->getChain(), VPSN->getValue(), 7421 VPSN->getBasePtr(), Index, VPSN->getScale(), 7422 VPSN->getMask(), VPSN->getVectorLength()}, 7423 VPSN->getMemOperand(), NewIndexTy); 7424 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7425 return DAG.getMaskedGather( 7426 N->getVTList(), MGN->getMemoryVT(), DL, 7427 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7428 MGN->getBasePtr(), Index, MGN->getScale()}, 7429 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7430 const auto *MSN = cast<MaskedScatterSDNode>(N); 7431 return DAG.getMaskedScatter( 7432 N->getVTList(), MSN->getMemoryVT(), DL, 7433 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7434 Index, MSN->getScale()}, 7435 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7436 } 7437 case RISCVISD::SRA_VL: 7438 case RISCVISD::SRL_VL: 7439 case RISCVISD::SHL_VL: { 7440 SDValue ShAmt = N->getOperand(1); 7441 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7442 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7443 SDLoc DL(N); 7444 SDValue VL = N->getOperand(3); 7445 EVT VT = N->getValueType(0); 7446 ShAmt = 7447 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7448 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7449 N->getOperand(2), N->getOperand(3)); 7450 } 7451 break; 7452 } 7453 case ISD::SRA: 7454 case ISD::SRL: 7455 case ISD::SHL: { 7456 SDValue ShAmt = N->getOperand(1); 7457 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7458 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7459 SDLoc DL(N); 7460 EVT VT = N->getValueType(0); 7461 ShAmt = 7462 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7463 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7464 } 7465 break; 7466 } 7467 case RISCVISD::MUL_VL: { 7468 SDValue Op0 = N->getOperand(0); 7469 SDValue Op1 = N->getOperand(1); 7470 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7471 return V; 7472 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7473 return V; 7474 return SDValue(); 7475 } 7476 case ISD::STORE: { 7477 auto *Store = cast<StoreSDNode>(N); 7478 SDValue Val = Store->getValue(); 7479 // Combine store of vmv.x.s to vse with VL of 1. 7480 // FIXME: Support FP. 7481 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7482 SDValue Src = Val.getOperand(0); 7483 EVT VecVT = Src.getValueType(); 7484 EVT MemVT = Store->getMemoryVT(); 7485 // The memory VT and the element type must match. 7486 if (VecVT.getVectorElementType() == MemVT) { 7487 SDLoc DL(N); 7488 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7489 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7490 DAG.getConstant(1, DL, MaskVT), 7491 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7492 Store->getPointerInfo(), 7493 Store->getOriginalAlign(), 7494 Store->getMemOperand()->getFlags()); 7495 } 7496 } 7497 7498 break; 7499 } 7500 } 7501 7502 return SDValue(); 7503 } 7504 7505 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7506 const SDNode *N, CombineLevel Level) const { 7507 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7508 // materialised in fewer instructions than `(OP _, c1)`: 7509 // 7510 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7511 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7512 SDValue N0 = N->getOperand(0); 7513 EVT Ty = N0.getValueType(); 7514 if (Ty.isScalarInteger() && 7515 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7516 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7517 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7518 if (C1 && C2) { 7519 const APInt &C1Int = C1->getAPIntValue(); 7520 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7521 7522 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7523 // and the combine should happen, to potentially allow further combines 7524 // later. 7525 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7526 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7527 return true; 7528 7529 // We can materialise `c1` in an add immediate, so it's "free", and the 7530 // combine should be prevented. 7531 if (C1Int.getMinSignedBits() <= 64 && 7532 isLegalAddImmediate(C1Int.getSExtValue())) 7533 return false; 7534 7535 // Neither constant will fit into an immediate, so find materialisation 7536 // costs. 7537 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7538 Subtarget.getFeatureBits(), 7539 /*CompressionCost*/true); 7540 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7541 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7542 /*CompressionCost*/true); 7543 7544 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7545 // combine should be prevented. 7546 if (C1Cost < ShiftedC1Cost) 7547 return false; 7548 } 7549 } 7550 return true; 7551 } 7552 7553 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7554 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7555 TargetLoweringOpt &TLO) const { 7556 // Delay this optimization as late as possible. 7557 if (!TLO.LegalOps) 7558 return false; 7559 7560 EVT VT = Op.getValueType(); 7561 if (VT.isVector()) 7562 return false; 7563 7564 // Only handle AND for now. 7565 if (Op.getOpcode() != ISD::AND) 7566 return false; 7567 7568 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7569 if (!C) 7570 return false; 7571 7572 const APInt &Mask = C->getAPIntValue(); 7573 7574 // Clear all non-demanded bits initially. 7575 APInt ShrunkMask = Mask & DemandedBits; 7576 7577 // Try to make a smaller immediate by setting undemanded bits. 7578 7579 APInt ExpandedMask = Mask | ~DemandedBits; 7580 7581 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7582 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7583 }; 7584 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7585 if (NewMask == Mask) 7586 return true; 7587 SDLoc DL(Op); 7588 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7589 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7590 return TLO.CombineTo(Op, NewOp); 7591 }; 7592 7593 // If the shrunk mask fits in sign extended 12 bits, let the target 7594 // independent code apply it. 7595 if (ShrunkMask.isSignedIntN(12)) 7596 return false; 7597 7598 // Preserve (and X, 0xffff) when zext.h is supported. 7599 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7600 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7601 if (IsLegalMask(NewMask)) 7602 return UseMask(NewMask); 7603 } 7604 7605 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7606 if (VT == MVT::i64) { 7607 APInt NewMask = APInt(64, 0xffffffff); 7608 if (IsLegalMask(NewMask)) 7609 return UseMask(NewMask); 7610 } 7611 7612 // For the remaining optimizations, we need to be able to make a negative 7613 // number through a combination of mask and undemanded bits. 7614 if (!ExpandedMask.isNegative()) 7615 return false; 7616 7617 // What is the fewest number of bits we need to represent the negative number. 7618 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7619 7620 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7621 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7622 APInt NewMask = ShrunkMask; 7623 if (MinSignedBits <= 12) 7624 NewMask.setBitsFrom(11); 7625 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7626 NewMask.setBitsFrom(31); 7627 else 7628 return false; 7629 7630 // Check that our new mask is a subset of the demanded mask. 7631 assert(IsLegalMask(NewMask)); 7632 return UseMask(NewMask); 7633 } 7634 7635 static void computeGREV(APInt &Src, unsigned ShAmt) { 7636 ShAmt &= Src.getBitWidth() - 1; 7637 uint64_t x = Src.getZExtValue(); 7638 if (ShAmt & 1) 7639 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7640 if (ShAmt & 2) 7641 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7642 if (ShAmt & 4) 7643 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7644 if (ShAmt & 8) 7645 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7646 if (ShAmt & 16) 7647 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7648 if (ShAmt & 32) 7649 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7650 Src = x; 7651 } 7652 7653 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7654 KnownBits &Known, 7655 const APInt &DemandedElts, 7656 const SelectionDAG &DAG, 7657 unsigned Depth) const { 7658 unsigned BitWidth = Known.getBitWidth(); 7659 unsigned Opc = Op.getOpcode(); 7660 assert((Opc >= ISD::BUILTIN_OP_END || 7661 Opc == ISD::INTRINSIC_WO_CHAIN || 7662 Opc == ISD::INTRINSIC_W_CHAIN || 7663 Opc == ISD::INTRINSIC_VOID) && 7664 "Should use MaskedValueIsZero if you don't know whether Op" 7665 " is a target node!"); 7666 7667 Known.resetAll(); 7668 switch (Opc) { 7669 default: break; 7670 case RISCVISD::SELECT_CC: { 7671 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7672 // If we don't know any bits, early out. 7673 if (Known.isUnknown()) 7674 break; 7675 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7676 7677 // Only known if known in both the LHS and RHS. 7678 Known = KnownBits::commonBits(Known, Known2); 7679 break; 7680 } 7681 case RISCVISD::REMUW: { 7682 KnownBits Known2; 7683 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7684 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7685 // We only care about the lower 32 bits. 7686 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7687 // Restore the original width by sign extending. 7688 Known = Known.sext(BitWidth); 7689 break; 7690 } 7691 case RISCVISD::DIVUW: { 7692 KnownBits Known2; 7693 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7694 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7695 // We only care about the lower 32 bits. 7696 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7697 // Restore the original width by sign extending. 7698 Known = Known.sext(BitWidth); 7699 break; 7700 } 7701 case RISCVISD::CTZW: { 7702 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7703 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7704 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7705 Known.Zero.setBitsFrom(LowBits); 7706 break; 7707 } 7708 case RISCVISD::CLZW: { 7709 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7710 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7711 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7712 Known.Zero.setBitsFrom(LowBits); 7713 break; 7714 } 7715 case RISCVISD::GREV: 7716 case RISCVISD::GREVW: { 7717 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7718 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7719 if (Opc == RISCVISD::GREVW) 7720 Known = Known.trunc(32); 7721 unsigned ShAmt = C->getZExtValue(); 7722 computeGREV(Known.Zero, ShAmt); 7723 computeGREV(Known.One, ShAmt); 7724 if (Opc == RISCVISD::GREVW) 7725 Known = Known.sext(BitWidth); 7726 } 7727 break; 7728 } 7729 case RISCVISD::READ_VLENB: 7730 // We assume VLENB is at least 16 bytes. 7731 Known.Zero.setLowBits(4); 7732 // We assume VLENB is no more than 65536 / 8 bytes. 7733 Known.Zero.setBitsFrom(14); 7734 break; 7735 case ISD::INTRINSIC_W_CHAIN: { 7736 unsigned IntNo = Op.getConstantOperandVal(1); 7737 switch (IntNo) { 7738 default: 7739 // We can't do anything for most intrinsics. 7740 break; 7741 case Intrinsic::riscv_vsetvli: 7742 case Intrinsic::riscv_vsetvlimax: 7743 // Assume that VL output is positive and would fit in an int32_t. 7744 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7745 if (BitWidth >= 32) 7746 Known.Zero.setBitsFrom(31); 7747 break; 7748 } 7749 break; 7750 } 7751 } 7752 } 7753 7754 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7755 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7756 unsigned Depth) const { 7757 switch (Op.getOpcode()) { 7758 default: 7759 break; 7760 case RISCVISD::SELECT_CC: { 7761 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7762 if (Tmp == 1) return 1; // Early out. 7763 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7764 return std::min(Tmp, Tmp2); 7765 } 7766 case RISCVISD::SLLW: 7767 case RISCVISD::SRAW: 7768 case RISCVISD::SRLW: 7769 case RISCVISD::DIVW: 7770 case RISCVISD::DIVUW: 7771 case RISCVISD::REMUW: 7772 case RISCVISD::ROLW: 7773 case RISCVISD::RORW: 7774 case RISCVISD::GREVW: 7775 case RISCVISD::GORCW: 7776 case RISCVISD::FSLW: 7777 case RISCVISD::FSRW: 7778 case RISCVISD::SHFLW: 7779 case RISCVISD::UNSHFLW: 7780 case RISCVISD::BCOMPRESSW: 7781 case RISCVISD::BDECOMPRESSW: 7782 case RISCVISD::FCVT_W_RTZ_RV64: 7783 case RISCVISD::FCVT_WU_RTZ_RV64: 7784 case RISCVISD::STRICT_FCVT_W_RTZ_RV64: 7785 case RISCVISD::STRICT_FCVT_WU_RTZ_RV64: 7786 // TODO: As the result is sign-extended, this is conservatively correct. A 7787 // more precise answer could be calculated for SRAW depending on known 7788 // bits in the shift amount. 7789 return 33; 7790 case RISCVISD::SHFL: 7791 case RISCVISD::UNSHFL: { 7792 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7793 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7794 // will stay within the upper 32 bits. If there were more than 32 sign bits 7795 // before there will be at least 33 sign bits after. 7796 if (Op.getValueType() == MVT::i64 && 7797 isa<ConstantSDNode>(Op.getOperand(1)) && 7798 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7799 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7800 if (Tmp > 32) 7801 return 33; 7802 } 7803 break; 7804 } 7805 case RISCVISD::VMV_X_S: 7806 // The number of sign bits of the scalar result is computed by obtaining the 7807 // element type of the input vector operand, subtracting its width from the 7808 // XLEN, and then adding one (sign bit within the element type). If the 7809 // element type is wider than XLen, the least-significant XLEN bits are 7810 // taken. 7811 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7812 return 1; 7813 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7814 } 7815 7816 return 1; 7817 } 7818 7819 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7820 MachineBasicBlock *BB) { 7821 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7822 7823 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7824 // Should the count have wrapped while it was being read, we need to try 7825 // again. 7826 // ... 7827 // read: 7828 // rdcycleh x3 # load high word of cycle 7829 // rdcycle x2 # load low word of cycle 7830 // rdcycleh x4 # load high word of cycle 7831 // bne x3, x4, read # check if high word reads match, otherwise try again 7832 // ... 7833 7834 MachineFunction &MF = *BB->getParent(); 7835 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7836 MachineFunction::iterator It = ++BB->getIterator(); 7837 7838 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7839 MF.insert(It, LoopMBB); 7840 7841 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7842 MF.insert(It, DoneMBB); 7843 7844 // Transfer the remainder of BB and its successor edges to DoneMBB. 7845 DoneMBB->splice(DoneMBB->begin(), BB, 7846 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7847 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7848 7849 BB->addSuccessor(LoopMBB); 7850 7851 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7852 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7853 Register LoReg = MI.getOperand(0).getReg(); 7854 Register HiReg = MI.getOperand(1).getReg(); 7855 DebugLoc DL = MI.getDebugLoc(); 7856 7857 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7858 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7859 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7860 .addReg(RISCV::X0); 7861 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7862 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7863 .addReg(RISCV::X0); 7864 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7865 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7866 .addReg(RISCV::X0); 7867 7868 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7869 .addReg(HiReg) 7870 .addReg(ReadAgainReg) 7871 .addMBB(LoopMBB); 7872 7873 LoopMBB->addSuccessor(LoopMBB); 7874 LoopMBB->addSuccessor(DoneMBB); 7875 7876 MI.eraseFromParent(); 7877 7878 return DoneMBB; 7879 } 7880 7881 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7882 MachineBasicBlock *BB) { 7883 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7884 7885 MachineFunction &MF = *BB->getParent(); 7886 DebugLoc DL = MI.getDebugLoc(); 7887 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7888 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7889 Register LoReg = MI.getOperand(0).getReg(); 7890 Register HiReg = MI.getOperand(1).getReg(); 7891 Register SrcReg = MI.getOperand(2).getReg(); 7892 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7893 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7894 7895 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7896 RI); 7897 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7898 MachineMemOperand *MMOLo = 7899 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7900 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7901 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7902 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7903 .addFrameIndex(FI) 7904 .addImm(0) 7905 .addMemOperand(MMOLo); 7906 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7907 .addFrameIndex(FI) 7908 .addImm(4) 7909 .addMemOperand(MMOHi); 7910 MI.eraseFromParent(); // The pseudo instruction is gone now. 7911 return BB; 7912 } 7913 7914 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7915 MachineBasicBlock *BB) { 7916 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7917 "Unexpected instruction"); 7918 7919 MachineFunction &MF = *BB->getParent(); 7920 DebugLoc DL = MI.getDebugLoc(); 7921 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7922 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7923 Register DstReg = MI.getOperand(0).getReg(); 7924 Register LoReg = MI.getOperand(1).getReg(); 7925 Register HiReg = MI.getOperand(2).getReg(); 7926 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7927 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7928 7929 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7930 MachineMemOperand *MMOLo = 7931 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7932 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7933 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7934 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7935 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7936 .addFrameIndex(FI) 7937 .addImm(0) 7938 .addMemOperand(MMOLo); 7939 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7940 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7941 .addFrameIndex(FI) 7942 .addImm(4) 7943 .addMemOperand(MMOHi); 7944 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7945 MI.eraseFromParent(); // The pseudo instruction is gone now. 7946 return BB; 7947 } 7948 7949 static bool isSelectPseudo(MachineInstr &MI) { 7950 switch (MI.getOpcode()) { 7951 default: 7952 return false; 7953 case RISCV::Select_GPR_Using_CC_GPR: 7954 case RISCV::Select_FPR16_Using_CC_GPR: 7955 case RISCV::Select_FPR32_Using_CC_GPR: 7956 case RISCV::Select_FPR64_Using_CC_GPR: 7957 return true; 7958 } 7959 } 7960 7961 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7962 MachineBasicBlock *BB, 7963 const RISCVSubtarget &Subtarget) { 7964 // To "insert" Select_* instructions, we actually have to insert the triangle 7965 // control-flow pattern. The incoming instructions know the destination vreg 7966 // to set, the condition code register to branch on, the true/false values to 7967 // select between, and the condcode to use to select the appropriate branch. 7968 // 7969 // We produce the following control flow: 7970 // HeadMBB 7971 // | \ 7972 // | IfFalseMBB 7973 // | / 7974 // TailMBB 7975 // 7976 // When we find a sequence of selects we attempt to optimize their emission 7977 // by sharing the control flow. Currently we only handle cases where we have 7978 // multiple selects with the exact same condition (same LHS, RHS and CC). 7979 // The selects may be interleaved with other instructions if the other 7980 // instructions meet some requirements we deem safe: 7981 // - They are debug instructions. Otherwise, 7982 // - They do not have side-effects, do not access memory and their inputs do 7983 // not depend on the results of the select pseudo-instructions. 7984 // The TrueV/FalseV operands of the selects cannot depend on the result of 7985 // previous selects in the sequence. 7986 // These conditions could be further relaxed. See the X86 target for a 7987 // related approach and more information. 7988 Register LHS = MI.getOperand(1).getReg(); 7989 Register RHS = MI.getOperand(2).getReg(); 7990 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 7991 7992 SmallVector<MachineInstr *, 4> SelectDebugValues; 7993 SmallSet<Register, 4> SelectDests; 7994 SelectDests.insert(MI.getOperand(0).getReg()); 7995 7996 MachineInstr *LastSelectPseudo = &MI; 7997 7998 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 7999 SequenceMBBI != E; ++SequenceMBBI) { 8000 if (SequenceMBBI->isDebugInstr()) 8001 continue; 8002 else if (isSelectPseudo(*SequenceMBBI)) { 8003 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8004 SequenceMBBI->getOperand(2).getReg() != RHS || 8005 SequenceMBBI->getOperand(3).getImm() != CC || 8006 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8007 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8008 break; 8009 LastSelectPseudo = &*SequenceMBBI; 8010 SequenceMBBI->collectDebugValues(SelectDebugValues); 8011 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8012 } else { 8013 if (SequenceMBBI->hasUnmodeledSideEffects() || 8014 SequenceMBBI->mayLoadOrStore()) 8015 break; 8016 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8017 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8018 })) 8019 break; 8020 } 8021 } 8022 8023 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8024 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8025 DebugLoc DL = MI.getDebugLoc(); 8026 MachineFunction::iterator I = ++BB->getIterator(); 8027 8028 MachineBasicBlock *HeadMBB = BB; 8029 MachineFunction *F = BB->getParent(); 8030 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8031 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8032 8033 F->insert(I, IfFalseMBB); 8034 F->insert(I, TailMBB); 8035 8036 // Transfer debug instructions associated with the selects to TailMBB. 8037 for (MachineInstr *DebugInstr : SelectDebugValues) { 8038 TailMBB->push_back(DebugInstr->removeFromParent()); 8039 } 8040 8041 // Move all instructions after the sequence to TailMBB. 8042 TailMBB->splice(TailMBB->end(), HeadMBB, 8043 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8044 // Update machine-CFG edges by transferring all successors of the current 8045 // block to the new block which will contain the Phi nodes for the selects. 8046 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8047 // Set the successors for HeadMBB. 8048 HeadMBB->addSuccessor(IfFalseMBB); 8049 HeadMBB->addSuccessor(TailMBB); 8050 8051 // Insert appropriate branch. 8052 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8053 .addReg(LHS) 8054 .addReg(RHS) 8055 .addMBB(TailMBB); 8056 8057 // IfFalseMBB just falls through to TailMBB. 8058 IfFalseMBB->addSuccessor(TailMBB); 8059 8060 // Create PHIs for all of the select pseudo-instructions. 8061 auto SelectMBBI = MI.getIterator(); 8062 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8063 auto InsertionPoint = TailMBB->begin(); 8064 while (SelectMBBI != SelectEnd) { 8065 auto Next = std::next(SelectMBBI); 8066 if (isSelectPseudo(*SelectMBBI)) { 8067 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8068 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8069 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8070 .addReg(SelectMBBI->getOperand(4).getReg()) 8071 .addMBB(HeadMBB) 8072 .addReg(SelectMBBI->getOperand(5).getReg()) 8073 .addMBB(IfFalseMBB); 8074 SelectMBBI->eraseFromParent(); 8075 } 8076 SelectMBBI = Next; 8077 } 8078 8079 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8080 return TailMBB; 8081 } 8082 8083 MachineBasicBlock * 8084 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8085 MachineBasicBlock *BB) const { 8086 switch (MI.getOpcode()) { 8087 default: 8088 llvm_unreachable("Unexpected instr type to insert"); 8089 case RISCV::ReadCycleWide: 8090 assert(!Subtarget.is64Bit() && 8091 "ReadCycleWrite is only to be used on riscv32"); 8092 return emitReadCycleWidePseudo(MI, BB); 8093 case RISCV::Select_GPR_Using_CC_GPR: 8094 case RISCV::Select_FPR16_Using_CC_GPR: 8095 case RISCV::Select_FPR32_Using_CC_GPR: 8096 case RISCV::Select_FPR64_Using_CC_GPR: 8097 return emitSelectPseudo(MI, BB, Subtarget); 8098 case RISCV::BuildPairF64Pseudo: 8099 return emitBuildPairF64Pseudo(MI, BB); 8100 case RISCV::SplitF64Pseudo: 8101 return emitSplitF64Pseudo(MI, BB); 8102 } 8103 } 8104 8105 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8106 SDNode *Node) const { 8107 // Add FRM dependency to any instructions with dynamic rounding mode. 8108 unsigned Opc = MI.getOpcode(); 8109 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8110 if (Idx < 0) 8111 return; 8112 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8113 return; 8114 // If the instruction already reads FRM, don't add another read. 8115 if (MI.readsRegister(RISCV::FRM)) 8116 return; 8117 MI.addOperand( 8118 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8119 } 8120 8121 // Calling Convention Implementation. 8122 // The expectations for frontend ABI lowering vary from target to target. 8123 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8124 // details, but this is a longer term goal. For now, we simply try to keep the 8125 // role of the frontend as simple and well-defined as possible. The rules can 8126 // be summarised as: 8127 // * Never split up large scalar arguments. We handle them here. 8128 // * If a hardfloat calling convention is being used, and the struct may be 8129 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8130 // available, then pass as two separate arguments. If either the GPRs or FPRs 8131 // are exhausted, then pass according to the rule below. 8132 // * If a struct could never be passed in registers or directly in a stack 8133 // slot (as it is larger than 2*XLEN and the floating point rules don't 8134 // apply), then pass it using a pointer with the byval attribute. 8135 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8136 // word-sized array or a 2*XLEN scalar (depending on alignment). 8137 // * The frontend can determine whether a struct is returned by reference or 8138 // not based on its size and fields. If it will be returned by reference, the 8139 // frontend must modify the prototype so a pointer with the sret annotation is 8140 // passed as the first argument. This is not necessary for large scalar 8141 // returns. 8142 // * Struct return values and varargs should be coerced to structs containing 8143 // register-size fields in the same situations they would be for fixed 8144 // arguments. 8145 8146 static const MCPhysReg ArgGPRs[] = { 8147 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8148 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8149 }; 8150 static const MCPhysReg ArgFPR16s[] = { 8151 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8152 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8153 }; 8154 static const MCPhysReg ArgFPR32s[] = { 8155 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8156 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8157 }; 8158 static const MCPhysReg ArgFPR64s[] = { 8159 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8160 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8161 }; 8162 // This is an interim calling convention and it may be changed in the future. 8163 static const MCPhysReg ArgVRs[] = { 8164 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8165 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8166 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8167 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8168 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8169 RISCV::V20M2, RISCV::V22M2}; 8170 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8171 RISCV::V20M4}; 8172 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8173 8174 // Pass a 2*XLEN argument that has been split into two XLEN values through 8175 // registers or the stack as necessary. 8176 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8177 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8178 MVT ValVT2, MVT LocVT2, 8179 ISD::ArgFlagsTy ArgFlags2) { 8180 unsigned XLenInBytes = XLen / 8; 8181 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8182 // At least one half can be passed via register. 8183 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8184 VA1.getLocVT(), CCValAssign::Full)); 8185 } else { 8186 // Both halves must be passed on the stack, with proper alignment. 8187 Align StackAlign = 8188 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8189 State.addLoc( 8190 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8191 State.AllocateStack(XLenInBytes, StackAlign), 8192 VA1.getLocVT(), CCValAssign::Full)); 8193 State.addLoc(CCValAssign::getMem( 8194 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8195 LocVT2, CCValAssign::Full)); 8196 return false; 8197 } 8198 8199 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8200 // The second half can also be passed via register. 8201 State.addLoc( 8202 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8203 } else { 8204 // The second half is passed via the stack, without additional alignment. 8205 State.addLoc(CCValAssign::getMem( 8206 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8207 LocVT2, CCValAssign::Full)); 8208 } 8209 8210 return false; 8211 } 8212 8213 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8214 Optional<unsigned> FirstMaskArgument, 8215 CCState &State, const RISCVTargetLowering &TLI) { 8216 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8217 if (RC == &RISCV::VRRegClass) { 8218 // Assign the first mask argument to V0. 8219 // This is an interim calling convention and it may be changed in the 8220 // future. 8221 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8222 return State.AllocateReg(RISCV::V0); 8223 return State.AllocateReg(ArgVRs); 8224 } 8225 if (RC == &RISCV::VRM2RegClass) 8226 return State.AllocateReg(ArgVRM2s); 8227 if (RC == &RISCV::VRM4RegClass) 8228 return State.AllocateReg(ArgVRM4s); 8229 if (RC == &RISCV::VRM8RegClass) 8230 return State.AllocateReg(ArgVRM8s); 8231 llvm_unreachable("Unhandled register class for ValueType"); 8232 } 8233 8234 // Implements the RISC-V calling convention. Returns true upon failure. 8235 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8236 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8237 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8238 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8239 Optional<unsigned> FirstMaskArgument) { 8240 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8241 assert(XLen == 32 || XLen == 64); 8242 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8243 8244 // Any return value split in to more than two values can't be returned 8245 // directly. Vectors are returned via the available vector registers. 8246 if (!LocVT.isVector() && IsRet && ValNo > 1) 8247 return true; 8248 8249 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8250 // variadic argument, or if no F16/F32 argument registers are available. 8251 bool UseGPRForF16_F32 = true; 8252 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8253 // variadic argument, or if no F64 argument registers are available. 8254 bool UseGPRForF64 = true; 8255 8256 switch (ABI) { 8257 default: 8258 llvm_unreachable("Unexpected ABI"); 8259 case RISCVABI::ABI_ILP32: 8260 case RISCVABI::ABI_LP64: 8261 break; 8262 case RISCVABI::ABI_ILP32F: 8263 case RISCVABI::ABI_LP64F: 8264 UseGPRForF16_F32 = !IsFixed; 8265 break; 8266 case RISCVABI::ABI_ILP32D: 8267 case RISCVABI::ABI_LP64D: 8268 UseGPRForF16_F32 = !IsFixed; 8269 UseGPRForF64 = !IsFixed; 8270 break; 8271 } 8272 8273 // FPR16, FPR32, and FPR64 alias each other. 8274 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8275 UseGPRForF16_F32 = true; 8276 UseGPRForF64 = true; 8277 } 8278 8279 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8280 // similar local variables rather than directly checking against the target 8281 // ABI. 8282 8283 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8284 LocVT = XLenVT; 8285 LocInfo = CCValAssign::BCvt; 8286 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8287 LocVT = MVT::i64; 8288 LocInfo = CCValAssign::BCvt; 8289 } 8290 8291 // If this is a variadic argument, the RISC-V calling convention requires 8292 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8293 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8294 // be used regardless of whether the original argument was split during 8295 // legalisation or not. The argument will not be passed by registers if the 8296 // original type is larger than 2*XLEN, so the register alignment rule does 8297 // not apply. 8298 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8299 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8300 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8301 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8302 // Skip 'odd' register if necessary. 8303 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8304 State.AllocateReg(ArgGPRs); 8305 } 8306 8307 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8308 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8309 State.getPendingArgFlags(); 8310 8311 assert(PendingLocs.size() == PendingArgFlags.size() && 8312 "PendingLocs and PendingArgFlags out of sync"); 8313 8314 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8315 // registers are exhausted. 8316 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8317 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8318 "Can't lower f64 if it is split"); 8319 // Depending on available argument GPRS, f64 may be passed in a pair of 8320 // GPRs, split between a GPR and the stack, or passed completely on the 8321 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8322 // cases. 8323 Register Reg = State.AllocateReg(ArgGPRs); 8324 LocVT = MVT::i32; 8325 if (!Reg) { 8326 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8327 State.addLoc( 8328 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8329 return false; 8330 } 8331 if (!State.AllocateReg(ArgGPRs)) 8332 State.AllocateStack(4, Align(4)); 8333 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8334 return false; 8335 } 8336 8337 // Fixed-length vectors are located in the corresponding scalable-vector 8338 // container types. 8339 if (ValVT.isFixedLengthVector()) 8340 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8341 8342 // Split arguments might be passed indirectly, so keep track of the pending 8343 // values. Split vectors are passed via a mix of registers and indirectly, so 8344 // treat them as we would any other argument. 8345 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8346 LocVT = XLenVT; 8347 LocInfo = CCValAssign::Indirect; 8348 PendingLocs.push_back( 8349 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8350 PendingArgFlags.push_back(ArgFlags); 8351 if (!ArgFlags.isSplitEnd()) { 8352 return false; 8353 } 8354 } 8355 8356 // If the split argument only had two elements, it should be passed directly 8357 // in registers or on the stack. 8358 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8359 PendingLocs.size() <= 2) { 8360 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8361 // Apply the normal calling convention rules to the first half of the 8362 // split argument. 8363 CCValAssign VA = PendingLocs[0]; 8364 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8365 PendingLocs.clear(); 8366 PendingArgFlags.clear(); 8367 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8368 ArgFlags); 8369 } 8370 8371 // Allocate to a register if possible, or else a stack slot. 8372 Register Reg; 8373 unsigned StoreSizeBytes = XLen / 8; 8374 Align StackAlign = Align(XLen / 8); 8375 8376 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8377 Reg = State.AllocateReg(ArgFPR16s); 8378 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8379 Reg = State.AllocateReg(ArgFPR32s); 8380 else if (ValVT == MVT::f64 && !UseGPRForF64) 8381 Reg = State.AllocateReg(ArgFPR64s); 8382 else if (ValVT.isVector()) { 8383 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8384 if (!Reg) { 8385 // For return values, the vector must be passed fully via registers or 8386 // via the stack. 8387 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8388 // but we're using all of them. 8389 if (IsRet) 8390 return true; 8391 // Try using a GPR to pass the address 8392 if ((Reg = State.AllocateReg(ArgGPRs))) { 8393 LocVT = XLenVT; 8394 LocInfo = CCValAssign::Indirect; 8395 } else if (ValVT.isScalableVector()) { 8396 report_fatal_error("Unable to pass scalable vector types on the stack"); 8397 } else { 8398 // Pass fixed-length vectors on the stack. 8399 LocVT = ValVT; 8400 StoreSizeBytes = ValVT.getStoreSize(); 8401 // Align vectors to their element sizes, being careful for vXi1 8402 // vectors. 8403 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8404 } 8405 } 8406 } else { 8407 Reg = State.AllocateReg(ArgGPRs); 8408 } 8409 8410 unsigned StackOffset = 8411 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8412 8413 // If we reach this point and PendingLocs is non-empty, we must be at the 8414 // end of a split argument that must be passed indirectly. 8415 if (!PendingLocs.empty()) { 8416 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8417 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8418 8419 for (auto &It : PendingLocs) { 8420 if (Reg) 8421 It.convertToReg(Reg); 8422 else 8423 It.convertToMem(StackOffset); 8424 State.addLoc(It); 8425 } 8426 PendingLocs.clear(); 8427 PendingArgFlags.clear(); 8428 return false; 8429 } 8430 8431 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8432 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8433 "Expected an XLenVT or vector types at this stage"); 8434 8435 if (Reg) { 8436 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8437 return false; 8438 } 8439 8440 // When a floating-point value is passed on the stack, no bit-conversion is 8441 // needed. 8442 if (ValVT.isFloatingPoint()) { 8443 LocVT = ValVT; 8444 LocInfo = CCValAssign::Full; 8445 } 8446 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8447 return false; 8448 } 8449 8450 template <typename ArgTy> 8451 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8452 for (const auto &ArgIdx : enumerate(Args)) { 8453 MVT ArgVT = ArgIdx.value().VT; 8454 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8455 return ArgIdx.index(); 8456 } 8457 return None; 8458 } 8459 8460 void RISCVTargetLowering::analyzeInputArgs( 8461 MachineFunction &MF, CCState &CCInfo, 8462 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8463 RISCVCCAssignFn Fn) const { 8464 unsigned NumArgs = Ins.size(); 8465 FunctionType *FType = MF.getFunction().getFunctionType(); 8466 8467 Optional<unsigned> FirstMaskArgument; 8468 if (Subtarget.hasVInstructions()) 8469 FirstMaskArgument = preAssignMask(Ins); 8470 8471 for (unsigned i = 0; i != NumArgs; ++i) { 8472 MVT ArgVT = Ins[i].VT; 8473 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8474 8475 Type *ArgTy = nullptr; 8476 if (IsRet) 8477 ArgTy = FType->getReturnType(); 8478 else if (Ins[i].isOrigArg()) 8479 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8480 8481 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8482 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8483 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8484 FirstMaskArgument)) { 8485 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8486 << EVT(ArgVT).getEVTString() << '\n'); 8487 llvm_unreachable(nullptr); 8488 } 8489 } 8490 } 8491 8492 void RISCVTargetLowering::analyzeOutputArgs( 8493 MachineFunction &MF, CCState &CCInfo, 8494 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8495 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8496 unsigned NumArgs = Outs.size(); 8497 8498 Optional<unsigned> FirstMaskArgument; 8499 if (Subtarget.hasVInstructions()) 8500 FirstMaskArgument = preAssignMask(Outs); 8501 8502 for (unsigned i = 0; i != NumArgs; i++) { 8503 MVT ArgVT = Outs[i].VT; 8504 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8505 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8506 8507 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8508 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8509 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8510 FirstMaskArgument)) { 8511 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8512 << EVT(ArgVT).getEVTString() << "\n"); 8513 llvm_unreachable(nullptr); 8514 } 8515 } 8516 } 8517 8518 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8519 // values. 8520 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8521 const CCValAssign &VA, const SDLoc &DL, 8522 const RISCVSubtarget &Subtarget) { 8523 switch (VA.getLocInfo()) { 8524 default: 8525 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8526 case CCValAssign::Full: 8527 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8528 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8529 break; 8530 case CCValAssign::BCvt: 8531 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8532 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8533 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8534 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8535 else 8536 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8537 break; 8538 } 8539 return Val; 8540 } 8541 8542 // The caller is responsible for loading the full value if the argument is 8543 // passed with CCValAssign::Indirect. 8544 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8545 const CCValAssign &VA, const SDLoc &DL, 8546 const RISCVTargetLowering &TLI) { 8547 MachineFunction &MF = DAG.getMachineFunction(); 8548 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8549 EVT LocVT = VA.getLocVT(); 8550 SDValue Val; 8551 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8552 Register VReg = RegInfo.createVirtualRegister(RC); 8553 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8554 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8555 8556 if (VA.getLocInfo() == CCValAssign::Indirect) 8557 return Val; 8558 8559 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8560 } 8561 8562 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8563 const CCValAssign &VA, const SDLoc &DL, 8564 const RISCVSubtarget &Subtarget) { 8565 EVT LocVT = VA.getLocVT(); 8566 8567 switch (VA.getLocInfo()) { 8568 default: 8569 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8570 case CCValAssign::Full: 8571 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8572 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8573 break; 8574 case CCValAssign::BCvt: 8575 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8576 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8577 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8578 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8579 else 8580 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8581 break; 8582 } 8583 return Val; 8584 } 8585 8586 // The caller is responsible for loading the full value if the argument is 8587 // passed with CCValAssign::Indirect. 8588 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8589 const CCValAssign &VA, const SDLoc &DL) { 8590 MachineFunction &MF = DAG.getMachineFunction(); 8591 MachineFrameInfo &MFI = MF.getFrameInfo(); 8592 EVT LocVT = VA.getLocVT(); 8593 EVT ValVT = VA.getValVT(); 8594 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8595 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8596 /*Immutable=*/true); 8597 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8598 SDValue Val; 8599 8600 ISD::LoadExtType ExtType; 8601 switch (VA.getLocInfo()) { 8602 default: 8603 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8604 case CCValAssign::Full: 8605 case CCValAssign::Indirect: 8606 case CCValAssign::BCvt: 8607 ExtType = ISD::NON_EXTLOAD; 8608 break; 8609 } 8610 Val = DAG.getExtLoad( 8611 ExtType, DL, LocVT, Chain, FIN, 8612 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8613 return Val; 8614 } 8615 8616 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8617 const CCValAssign &VA, const SDLoc &DL) { 8618 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8619 "Unexpected VA"); 8620 MachineFunction &MF = DAG.getMachineFunction(); 8621 MachineFrameInfo &MFI = MF.getFrameInfo(); 8622 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8623 8624 if (VA.isMemLoc()) { 8625 // f64 is passed on the stack. 8626 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8627 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8628 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8629 MachinePointerInfo::getFixedStack(MF, FI)); 8630 } 8631 8632 assert(VA.isRegLoc() && "Expected register VA assignment"); 8633 8634 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8635 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8636 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8637 SDValue Hi; 8638 if (VA.getLocReg() == RISCV::X17) { 8639 // Second half of f64 is passed on the stack. 8640 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8641 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8642 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8643 MachinePointerInfo::getFixedStack(MF, FI)); 8644 } else { 8645 // Second half of f64 is passed in another GPR. 8646 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8647 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8648 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8649 } 8650 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8651 } 8652 8653 // FastCC has less than 1% performance improvement for some particular 8654 // benchmark. But theoretically, it may has benenfit for some cases. 8655 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8656 unsigned ValNo, MVT ValVT, MVT LocVT, 8657 CCValAssign::LocInfo LocInfo, 8658 ISD::ArgFlagsTy ArgFlags, CCState &State, 8659 bool IsFixed, bool IsRet, Type *OrigTy, 8660 const RISCVTargetLowering &TLI, 8661 Optional<unsigned> FirstMaskArgument) { 8662 8663 // X5 and X6 might be used for save-restore libcall. 8664 static const MCPhysReg GPRList[] = { 8665 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8666 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8667 RISCV::X29, RISCV::X30, RISCV::X31}; 8668 8669 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8670 if (unsigned Reg = State.AllocateReg(GPRList)) { 8671 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8672 return false; 8673 } 8674 } 8675 8676 if (LocVT == MVT::f16) { 8677 static const MCPhysReg FPR16List[] = { 8678 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8679 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8680 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8681 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8682 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8683 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8684 return false; 8685 } 8686 } 8687 8688 if (LocVT == MVT::f32) { 8689 static const MCPhysReg FPR32List[] = { 8690 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8691 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8692 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8693 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8694 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8695 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8696 return false; 8697 } 8698 } 8699 8700 if (LocVT == MVT::f64) { 8701 static const MCPhysReg FPR64List[] = { 8702 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8703 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8704 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8705 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8706 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8707 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8708 return false; 8709 } 8710 } 8711 8712 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8713 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8714 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8715 return false; 8716 } 8717 8718 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8719 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8720 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8721 return false; 8722 } 8723 8724 if (LocVT.isVector()) { 8725 if (unsigned Reg = 8726 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8727 // Fixed-length vectors are located in the corresponding scalable-vector 8728 // container types. 8729 if (ValVT.isFixedLengthVector()) 8730 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8731 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8732 } else { 8733 // Try and pass the address via a "fast" GPR. 8734 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8735 LocInfo = CCValAssign::Indirect; 8736 LocVT = TLI.getSubtarget().getXLenVT(); 8737 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8738 } else if (ValVT.isFixedLengthVector()) { 8739 auto StackAlign = 8740 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8741 unsigned StackOffset = 8742 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8743 State.addLoc( 8744 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8745 } else { 8746 // Can't pass scalable vectors on the stack. 8747 return true; 8748 } 8749 } 8750 8751 return false; 8752 } 8753 8754 return true; // CC didn't match. 8755 } 8756 8757 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8758 CCValAssign::LocInfo LocInfo, 8759 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8760 8761 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8762 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8763 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8764 static const MCPhysReg GPRList[] = { 8765 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8766 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8767 if (unsigned Reg = State.AllocateReg(GPRList)) { 8768 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8769 return false; 8770 } 8771 } 8772 8773 if (LocVT == MVT::f32) { 8774 // Pass in STG registers: F1, ..., F6 8775 // fs0 ... fs5 8776 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8777 RISCV::F18_F, RISCV::F19_F, 8778 RISCV::F20_F, RISCV::F21_F}; 8779 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8780 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8781 return false; 8782 } 8783 } 8784 8785 if (LocVT == MVT::f64) { 8786 // Pass in STG registers: D1, ..., D6 8787 // fs6 ... fs11 8788 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8789 RISCV::F24_D, RISCV::F25_D, 8790 RISCV::F26_D, RISCV::F27_D}; 8791 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8792 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8793 return false; 8794 } 8795 } 8796 8797 report_fatal_error("No registers left in GHC calling convention"); 8798 return true; 8799 } 8800 8801 // Transform physical registers into virtual registers. 8802 SDValue RISCVTargetLowering::LowerFormalArguments( 8803 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8804 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8805 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8806 8807 MachineFunction &MF = DAG.getMachineFunction(); 8808 8809 switch (CallConv) { 8810 default: 8811 report_fatal_error("Unsupported calling convention"); 8812 case CallingConv::C: 8813 case CallingConv::Fast: 8814 break; 8815 case CallingConv::GHC: 8816 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8817 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8818 report_fatal_error( 8819 "GHC calling convention requires the F and D instruction set extensions"); 8820 } 8821 8822 const Function &Func = MF.getFunction(); 8823 if (Func.hasFnAttribute("interrupt")) { 8824 if (!Func.arg_empty()) 8825 report_fatal_error( 8826 "Functions with the interrupt attribute cannot have arguments!"); 8827 8828 StringRef Kind = 8829 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8830 8831 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8832 report_fatal_error( 8833 "Function interrupt attribute argument not supported!"); 8834 } 8835 8836 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8837 MVT XLenVT = Subtarget.getXLenVT(); 8838 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8839 // Used with vargs to acumulate store chains. 8840 std::vector<SDValue> OutChains; 8841 8842 // Assign locations to all of the incoming arguments. 8843 SmallVector<CCValAssign, 16> ArgLocs; 8844 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8845 8846 if (CallConv == CallingConv::GHC) 8847 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8848 else 8849 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8850 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8851 : CC_RISCV); 8852 8853 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8854 CCValAssign &VA = ArgLocs[i]; 8855 SDValue ArgValue; 8856 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8857 // case. 8858 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8859 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8860 else if (VA.isRegLoc()) 8861 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8862 else 8863 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8864 8865 if (VA.getLocInfo() == CCValAssign::Indirect) { 8866 // If the original argument was split and passed by reference (e.g. i128 8867 // on RV32), we need to load all parts of it here (using the same 8868 // address). Vectors may be partly split to registers and partly to the 8869 // stack, in which case the base address is partly offset and subsequent 8870 // stores are relative to that. 8871 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8872 MachinePointerInfo())); 8873 unsigned ArgIndex = Ins[i].OrigArgIndex; 8874 unsigned ArgPartOffset = Ins[i].PartOffset; 8875 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8876 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8877 CCValAssign &PartVA = ArgLocs[i + 1]; 8878 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8879 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8880 if (PartVA.getValVT().isScalableVector()) 8881 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8882 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8883 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8884 MachinePointerInfo())); 8885 ++i; 8886 } 8887 continue; 8888 } 8889 InVals.push_back(ArgValue); 8890 } 8891 8892 if (IsVarArg) { 8893 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8894 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8895 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8896 MachineFrameInfo &MFI = MF.getFrameInfo(); 8897 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8898 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8899 8900 // Offset of the first variable argument from stack pointer, and size of 8901 // the vararg save area. For now, the varargs save area is either zero or 8902 // large enough to hold a0-a7. 8903 int VaArgOffset, VarArgsSaveSize; 8904 8905 // If all registers are allocated, then all varargs must be passed on the 8906 // stack and we don't need to save any argregs. 8907 if (ArgRegs.size() == Idx) { 8908 VaArgOffset = CCInfo.getNextStackOffset(); 8909 VarArgsSaveSize = 0; 8910 } else { 8911 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8912 VaArgOffset = -VarArgsSaveSize; 8913 } 8914 8915 // Record the frame index of the first variable argument 8916 // which is a value necessary to VASTART. 8917 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8918 RVFI->setVarArgsFrameIndex(FI); 8919 8920 // If saving an odd number of registers then create an extra stack slot to 8921 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8922 // offsets to even-numbered registered remain 2*XLEN-aligned. 8923 if (Idx % 2) { 8924 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8925 VarArgsSaveSize += XLenInBytes; 8926 } 8927 8928 // Copy the integer registers that may have been used for passing varargs 8929 // to the vararg save area. 8930 for (unsigned I = Idx; I < ArgRegs.size(); 8931 ++I, VaArgOffset += XLenInBytes) { 8932 const Register Reg = RegInfo.createVirtualRegister(RC); 8933 RegInfo.addLiveIn(ArgRegs[I], Reg); 8934 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8935 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8936 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8937 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8938 MachinePointerInfo::getFixedStack(MF, FI)); 8939 cast<StoreSDNode>(Store.getNode()) 8940 ->getMemOperand() 8941 ->setValue((Value *)nullptr); 8942 OutChains.push_back(Store); 8943 } 8944 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8945 } 8946 8947 // All stores are grouped in one node to allow the matching between 8948 // the size of Ins and InVals. This only happens for vararg functions. 8949 if (!OutChains.empty()) { 8950 OutChains.push_back(Chain); 8951 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8952 } 8953 8954 return Chain; 8955 } 8956 8957 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8958 /// for tail call optimization. 8959 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8960 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8961 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8962 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8963 8964 auto &Callee = CLI.Callee; 8965 auto CalleeCC = CLI.CallConv; 8966 auto &Outs = CLI.Outs; 8967 auto &Caller = MF.getFunction(); 8968 auto CallerCC = Caller.getCallingConv(); 8969 8970 // Exception-handling functions need a special set of instructions to 8971 // indicate a return to the hardware. Tail-calling another function would 8972 // probably break this. 8973 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8974 // should be expanded as new function attributes are introduced. 8975 if (Caller.hasFnAttribute("interrupt")) 8976 return false; 8977 8978 // Do not tail call opt if the stack is used to pass parameters. 8979 if (CCInfo.getNextStackOffset() != 0) 8980 return false; 8981 8982 // Do not tail call opt if any parameters need to be passed indirectly. 8983 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 8984 // passed indirectly. So the address of the value will be passed in a 8985 // register, or if not available, then the address is put on the stack. In 8986 // order to pass indirectly, space on the stack often needs to be allocated 8987 // in order to store the value. In this case the CCInfo.getNextStackOffset() 8988 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 8989 // are passed CCValAssign::Indirect. 8990 for (auto &VA : ArgLocs) 8991 if (VA.getLocInfo() == CCValAssign::Indirect) 8992 return false; 8993 8994 // Do not tail call opt if either caller or callee uses struct return 8995 // semantics. 8996 auto IsCallerStructRet = Caller.hasStructRetAttr(); 8997 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 8998 if (IsCallerStructRet || IsCalleeStructRet) 8999 return false; 9000 9001 // Externally-defined functions with weak linkage should not be 9002 // tail-called. The behaviour of branch instructions in this situation (as 9003 // used for tail calls) is implementation-defined, so we cannot rely on the 9004 // linker replacing the tail call with a return. 9005 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9006 const GlobalValue *GV = G->getGlobal(); 9007 if (GV->hasExternalWeakLinkage()) 9008 return false; 9009 } 9010 9011 // The callee has to preserve all registers the caller needs to preserve. 9012 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9013 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9014 if (CalleeCC != CallerCC) { 9015 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9016 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9017 return false; 9018 } 9019 9020 // Byval parameters hand the function a pointer directly into the stack area 9021 // we want to reuse during a tail call. Working around this *is* possible 9022 // but less efficient and uglier in LowerCall. 9023 for (auto &Arg : Outs) 9024 if (Arg.Flags.isByVal()) 9025 return false; 9026 9027 return true; 9028 } 9029 9030 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9031 return DAG.getDataLayout().getPrefTypeAlign( 9032 VT.getTypeForEVT(*DAG.getContext())); 9033 } 9034 9035 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9036 // and output parameter nodes. 9037 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9038 SmallVectorImpl<SDValue> &InVals) const { 9039 SelectionDAG &DAG = CLI.DAG; 9040 SDLoc &DL = CLI.DL; 9041 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9042 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9043 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9044 SDValue Chain = CLI.Chain; 9045 SDValue Callee = CLI.Callee; 9046 bool &IsTailCall = CLI.IsTailCall; 9047 CallingConv::ID CallConv = CLI.CallConv; 9048 bool IsVarArg = CLI.IsVarArg; 9049 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9050 MVT XLenVT = Subtarget.getXLenVT(); 9051 9052 MachineFunction &MF = DAG.getMachineFunction(); 9053 9054 // Analyze the operands of the call, assigning locations to each operand. 9055 SmallVector<CCValAssign, 16> ArgLocs; 9056 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9057 9058 if (CallConv == CallingConv::GHC) 9059 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9060 else 9061 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9062 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9063 : CC_RISCV); 9064 9065 // Check if it's really possible to do a tail call. 9066 if (IsTailCall) 9067 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9068 9069 if (IsTailCall) 9070 ++NumTailCalls; 9071 else if (CLI.CB && CLI.CB->isMustTailCall()) 9072 report_fatal_error("failed to perform tail call elimination on a call " 9073 "site marked musttail"); 9074 9075 // Get a count of how many bytes are to be pushed on the stack. 9076 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9077 9078 // Create local copies for byval args 9079 SmallVector<SDValue, 8> ByValArgs; 9080 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9081 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9082 if (!Flags.isByVal()) 9083 continue; 9084 9085 SDValue Arg = OutVals[i]; 9086 unsigned Size = Flags.getByValSize(); 9087 Align Alignment = Flags.getNonZeroByValAlign(); 9088 9089 int FI = 9090 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9091 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9092 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9093 9094 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9095 /*IsVolatile=*/false, 9096 /*AlwaysInline=*/false, IsTailCall, 9097 MachinePointerInfo(), MachinePointerInfo()); 9098 ByValArgs.push_back(FIPtr); 9099 } 9100 9101 if (!IsTailCall) 9102 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9103 9104 // Copy argument values to their designated locations. 9105 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9106 SmallVector<SDValue, 8> MemOpChains; 9107 SDValue StackPtr; 9108 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9109 CCValAssign &VA = ArgLocs[i]; 9110 SDValue ArgValue = OutVals[i]; 9111 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9112 9113 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9114 bool IsF64OnRV32DSoftABI = 9115 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9116 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9117 SDValue SplitF64 = DAG.getNode( 9118 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9119 SDValue Lo = SplitF64.getValue(0); 9120 SDValue Hi = SplitF64.getValue(1); 9121 9122 Register RegLo = VA.getLocReg(); 9123 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9124 9125 if (RegLo == RISCV::X17) { 9126 // Second half of f64 is passed on the stack. 9127 // Work out the address of the stack slot. 9128 if (!StackPtr.getNode()) 9129 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9130 // Emit the store. 9131 MemOpChains.push_back( 9132 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9133 } else { 9134 // Second half of f64 is passed in another GPR. 9135 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9136 Register RegHigh = RegLo + 1; 9137 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9138 } 9139 continue; 9140 } 9141 9142 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9143 // as any other MemLoc. 9144 9145 // Promote the value if needed. 9146 // For now, only handle fully promoted and indirect arguments. 9147 if (VA.getLocInfo() == CCValAssign::Indirect) { 9148 // Store the argument in a stack slot and pass its address. 9149 Align StackAlign = 9150 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9151 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9152 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9153 // If the original argument was split (e.g. i128), we need 9154 // to store the required parts of it here (and pass just one address). 9155 // Vectors may be partly split to registers and partly to the stack, in 9156 // which case the base address is partly offset and subsequent stores are 9157 // relative to that. 9158 unsigned ArgIndex = Outs[i].OrigArgIndex; 9159 unsigned ArgPartOffset = Outs[i].PartOffset; 9160 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9161 // Calculate the total size to store. We don't have access to what we're 9162 // actually storing other than performing the loop and collecting the 9163 // info. 9164 SmallVector<std::pair<SDValue, SDValue>> Parts; 9165 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9166 SDValue PartValue = OutVals[i + 1]; 9167 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9168 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9169 EVT PartVT = PartValue.getValueType(); 9170 if (PartVT.isScalableVector()) 9171 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9172 StoredSize += PartVT.getStoreSize(); 9173 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9174 Parts.push_back(std::make_pair(PartValue, Offset)); 9175 ++i; 9176 } 9177 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9178 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9179 MemOpChains.push_back( 9180 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9181 MachinePointerInfo::getFixedStack(MF, FI))); 9182 for (const auto &Part : Parts) { 9183 SDValue PartValue = Part.first; 9184 SDValue PartOffset = Part.second; 9185 SDValue Address = 9186 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9187 MemOpChains.push_back( 9188 DAG.getStore(Chain, DL, PartValue, Address, 9189 MachinePointerInfo::getFixedStack(MF, FI))); 9190 } 9191 ArgValue = SpillSlot; 9192 } else { 9193 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9194 } 9195 9196 // Use local copy if it is a byval arg. 9197 if (Flags.isByVal()) 9198 ArgValue = ByValArgs[j++]; 9199 9200 if (VA.isRegLoc()) { 9201 // Queue up the argument copies and emit them at the end. 9202 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9203 } else { 9204 assert(VA.isMemLoc() && "Argument not register or memory"); 9205 assert(!IsTailCall && "Tail call not allowed if stack is used " 9206 "for passing parameters"); 9207 9208 // Work out the address of the stack slot. 9209 if (!StackPtr.getNode()) 9210 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9211 SDValue Address = 9212 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9213 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9214 9215 // Emit the store. 9216 MemOpChains.push_back( 9217 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9218 } 9219 } 9220 9221 // Join the stores, which are independent of one another. 9222 if (!MemOpChains.empty()) 9223 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9224 9225 SDValue Glue; 9226 9227 // Build a sequence of copy-to-reg nodes, chained and glued together. 9228 for (auto &Reg : RegsToPass) { 9229 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9230 Glue = Chain.getValue(1); 9231 } 9232 9233 // Validate that none of the argument registers have been marked as 9234 // reserved, if so report an error. Do the same for the return address if this 9235 // is not a tailcall. 9236 validateCCReservedRegs(RegsToPass, MF); 9237 if (!IsTailCall && 9238 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9239 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9240 MF.getFunction(), 9241 "Return address register required, but has been reserved."}); 9242 9243 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9244 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9245 // split it and then direct call can be matched by PseudoCALL. 9246 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9247 const GlobalValue *GV = S->getGlobal(); 9248 9249 unsigned OpFlags = RISCVII::MO_CALL; 9250 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9251 OpFlags = RISCVII::MO_PLT; 9252 9253 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9254 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9255 unsigned OpFlags = RISCVII::MO_CALL; 9256 9257 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9258 nullptr)) 9259 OpFlags = RISCVII::MO_PLT; 9260 9261 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9262 } 9263 9264 // The first call operand is the chain and the second is the target address. 9265 SmallVector<SDValue, 8> Ops; 9266 Ops.push_back(Chain); 9267 Ops.push_back(Callee); 9268 9269 // Add argument registers to the end of the list so that they are 9270 // known live into the call. 9271 for (auto &Reg : RegsToPass) 9272 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9273 9274 if (!IsTailCall) { 9275 // Add a register mask operand representing the call-preserved registers. 9276 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9277 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9278 assert(Mask && "Missing call preserved mask for calling convention"); 9279 Ops.push_back(DAG.getRegisterMask(Mask)); 9280 } 9281 9282 // Glue the call to the argument copies, if any. 9283 if (Glue.getNode()) 9284 Ops.push_back(Glue); 9285 9286 // Emit the call. 9287 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9288 9289 if (IsTailCall) { 9290 MF.getFrameInfo().setHasTailCall(); 9291 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9292 } 9293 9294 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9295 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9296 Glue = Chain.getValue(1); 9297 9298 // Mark the end of the call, which is glued to the call itself. 9299 Chain = DAG.getCALLSEQ_END(Chain, 9300 DAG.getConstant(NumBytes, DL, PtrVT, true), 9301 DAG.getConstant(0, DL, PtrVT, true), 9302 Glue, DL); 9303 Glue = Chain.getValue(1); 9304 9305 // Assign locations to each value returned by this call. 9306 SmallVector<CCValAssign, 16> RVLocs; 9307 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9308 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9309 9310 // Copy all of the result registers out of their specified physreg. 9311 for (auto &VA : RVLocs) { 9312 // Copy the value out 9313 SDValue RetValue = 9314 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9315 // Glue the RetValue to the end of the call sequence 9316 Chain = RetValue.getValue(1); 9317 Glue = RetValue.getValue(2); 9318 9319 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9320 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9321 SDValue RetValue2 = 9322 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9323 Chain = RetValue2.getValue(1); 9324 Glue = RetValue2.getValue(2); 9325 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9326 RetValue2); 9327 } 9328 9329 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9330 9331 InVals.push_back(RetValue); 9332 } 9333 9334 return Chain; 9335 } 9336 9337 bool RISCVTargetLowering::CanLowerReturn( 9338 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9339 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9340 SmallVector<CCValAssign, 16> RVLocs; 9341 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9342 9343 Optional<unsigned> FirstMaskArgument; 9344 if (Subtarget.hasVInstructions()) 9345 FirstMaskArgument = preAssignMask(Outs); 9346 9347 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9348 MVT VT = Outs[i].VT; 9349 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9350 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9351 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9352 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9353 *this, FirstMaskArgument)) 9354 return false; 9355 } 9356 return true; 9357 } 9358 9359 SDValue 9360 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9361 bool IsVarArg, 9362 const SmallVectorImpl<ISD::OutputArg> &Outs, 9363 const SmallVectorImpl<SDValue> &OutVals, 9364 const SDLoc &DL, SelectionDAG &DAG) const { 9365 const MachineFunction &MF = DAG.getMachineFunction(); 9366 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9367 9368 // Stores the assignment of the return value to a location. 9369 SmallVector<CCValAssign, 16> RVLocs; 9370 9371 // Info about the registers and stack slot. 9372 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9373 *DAG.getContext()); 9374 9375 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9376 nullptr, CC_RISCV); 9377 9378 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9379 report_fatal_error("GHC functions return void only"); 9380 9381 SDValue Glue; 9382 SmallVector<SDValue, 4> RetOps(1, Chain); 9383 9384 // Copy the result values into the output registers. 9385 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9386 SDValue Val = OutVals[i]; 9387 CCValAssign &VA = RVLocs[i]; 9388 assert(VA.isRegLoc() && "Can only return in registers!"); 9389 9390 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9391 // Handle returning f64 on RV32D with a soft float ABI. 9392 assert(VA.isRegLoc() && "Expected return via registers"); 9393 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9394 DAG.getVTList(MVT::i32, MVT::i32), Val); 9395 SDValue Lo = SplitF64.getValue(0); 9396 SDValue Hi = SplitF64.getValue(1); 9397 Register RegLo = VA.getLocReg(); 9398 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9399 Register RegHi = RegLo + 1; 9400 9401 if (STI.isRegisterReservedByUser(RegLo) || 9402 STI.isRegisterReservedByUser(RegHi)) 9403 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9404 MF.getFunction(), 9405 "Return value register required, but has been reserved."}); 9406 9407 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9408 Glue = Chain.getValue(1); 9409 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9410 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9411 Glue = Chain.getValue(1); 9412 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9413 } else { 9414 // Handle a 'normal' return. 9415 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9416 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9417 9418 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9419 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9420 MF.getFunction(), 9421 "Return value register required, but has been reserved."}); 9422 9423 // Guarantee that all emitted copies are stuck together. 9424 Glue = Chain.getValue(1); 9425 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9426 } 9427 } 9428 9429 RetOps[0] = Chain; // Update chain. 9430 9431 // Add the glue node if we have it. 9432 if (Glue.getNode()) { 9433 RetOps.push_back(Glue); 9434 } 9435 9436 unsigned RetOpc = RISCVISD::RET_FLAG; 9437 // Interrupt service routines use different return instructions. 9438 const Function &Func = DAG.getMachineFunction().getFunction(); 9439 if (Func.hasFnAttribute("interrupt")) { 9440 if (!Func.getReturnType()->isVoidTy()) 9441 report_fatal_error( 9442 "Functions with the interrupt attribute must have void return type!"); 9443 9444 MachineFunction &MF = DAG.getMachineFunction(); 9445 StringRef Kind = 9446 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9447 9448 if (Kind == "user") 9449 RetOpc = RISCVISD::URET_FLAG; 9450 else if (Kind == "supervisor") 9451 RetOpc = RISCVISD::SRET_FLAG; 9452 else 9453 RetOpc = RISCVISD::MRET_FLAG; 9454 } 9455 9456 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9457 } 9458 9459 void RISCVTargetLowering::validateCCReservedRegs( 9460 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9461 MachineFunction &MF) const { 9462 const Function &F = MF.getFunction(); 9463 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9464 9465 if (llvm::any_of(Regs, [&STI](auto Reg) { 9466 return STI.isRegisterReservedByUser(Reg.first); 9467 })) 9468 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9469 F, "Argument register required, but has been reserved."}); 9470 } 9471 9472 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9473 return CI->isTailCall(); 9474 } 9475 9476 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9477 #define NODE_NAME_CASE(NODE) \ 9478 case RISCVISD::NODE: \ 9479 return "RISCVISD::" #NODE; 9480 // clang-format off 9481 switch ((RISCVISD::NodeType)Opcode) { 9482 case RISCVISD::FIRST_NUMBER: 9483 break; 9484 NODE_NAME_CASE(RET_FLAG) 9485 NODE_NAME_CASE(URET_FLAG) 9486 NODE_NAME_CASE(SRET_FLAG) 9487 NODE_NAME_CASE(MRET_FLAG) 9488 NODE_NAME_CASE(CALL) 9489 NODE_NAME_CASE(SELECT_CC) 9490 NODE_NAME_CASE(BR_CC) 9491 NODE_NAME_CASE(BuildPairF64) 9492 NODE_NAME_CASE(SplitF64) 9493 NODE_NAME_CASE(TAIL) 9494 NODE_NAME_CASE(MULHSU) 9495 NODE_NAME_CASE(SLLW) 9496 NODE_NAME_CASE(SRAW) 9497 NODE_NAME_CASE(SRLW) 9498 NODE_NAME_CASE(DIVW) 9499 NODE_NAME_CASE(DIVUW) 9500 NODE_NAME_CASE(REMUW) 9501 NODE_NAME_CASE(ROLW) 9502 NODE_NAME_CASE(RORW) 9503 NODE_NAME_CASE(CLZW) 9504 NODE_NAME_CASE(CTZW) 9505 NODE_NAME_CASE(FSLW) 9506 NODE_NAME_CASE(FSRW) 9507 NODE_NAME_CASE(FSL) 9508 NODE_NAME_CASE(FSR) 9509 NODE_NAME_CASE(FMV_H_X) 9510 NODE_NAME_CASE(FMV_X_ANYEXTH) 9511 NODE_NAME_CASE(FMV_W_X_RV64) 9512 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9513 NODE_NAME_CASE(FCVT_X_RTZ) 9514 NODE_NAME_CASE(FCVT_XU_RTZ) 9515 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9516 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9517 NODE_NAME_CASE(STRICT_FCVT_W_RTZ_RV64) 9518 NODE_NAME_CASE(STRICT_FCVT_WU_RTZ_RV64) 9519 NODE_NAME_CASE(READ_CYCLE_WIDE) 9520 NODE_NAME_CASE(GREV) 9521 NODE_NAME_CASE(GREVW) 9522 NODE_NAME_CASE(GORC) 9523 NODE_NAME_CASE(GORCW) 9524 NODE_NAME_CASE(SHFL) 9525 NODE_NAME_CASE(SHFLW) 9526 NODE_NAME_CASE(UNSHFL) 9527 NODE_NAME_CASE(UNSHFLW) 9528 NODE_NAME_CASE(BCOMPRESS) 9529 NODE_NAME_CASE(BCOMPRESSW) 9530 NODE_NAME_CASE(BDECOMPRESS) 9531 NODE_NAME_CASE(BDECOMPRESSW) 9532 NODE_NAME_CASE(VMV_V_X_VL) 9533 NODE_NAME_CASE(VFMV_V_F_VL) 9534 NODE_NAME_CASE(VMV_X_S) 9535 NODE_NAME_CASE(VMV_S_X_VL) 9536 NODE_NAME_CASE(VFMV_S_F_VL) 9537 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9538 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9539 NODE_NAME_CASE(READ_VLENB) 9540 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9541 NODE_NAME_CASE(VSLIDEUP_VL) 9542 NODE_NAME_CASE(VSLIDE1UP_VL) 9543 NODE_NAME_CASE(VSLIDEDOWN_VL) 9544 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9545 NODE_NAME_CASE(VID_VL) 9546 NODE_NAME_CASE(VFNCVT_ROD_VL) 9547 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9548 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9549 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9550 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9551 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9552 NODE_NAME_CASE(VECREDUCE_AND_VL) 9553 NODE_NAME_CASE(VECREDUCE_OR_VL) 9554 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9555 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9556 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9557 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9558 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9559 NODE_NAME_CASE(ADD_VL) 9560 NODE_NAME_CASE(AND_VL) 9561 NODE_NAME_CASE(MUL_VL) 9562 NODE_NAME_CASE(OR_VL) 9563 NODE_NAME_CASE(SDIV_VL) 9564 NODE_NAME_CASE(SHL_VL) 9565 NODE_NAME_CASE(SREM_VL) 9566 NODE_NAME_CASE(SRA_VL) 9567 NODE_NAME_CASE(SRL_VL) 9568 NODE_NAME_CASE(SUB_VL) 9569 NODE_NAME_CASE(UDIV_VL) 9570 NODE_NAME_CASE(UREM_VL) 9571 NODE_NAME_CASE(XOR_VL) 9572 NODE_NAME_CASE(SADDSAT_VL) 9573 NODE_NAME_CASE(UADDSAT_VL) 9574 NODE_NAME_CASE(SSUBSAT_VL) 9575 NODE_NAME_CASE(USUBSAT_VL) 9576 NODE_NAME_CASE(FADD_VL) 9577 NODE_NAME_CASE(FSUB_VL) 9578 NODE_NAME_CASE(FMUL_VL) 9579 NODE_NAME_CASE(FDIV_VL) 9580 NODE_NAME_CASE(FNEG_VL) 9581 NODE_NAME_CASE(FABS_VL) 9582 NODE_NAME_CASE(FSQRT_VL) 9583 NODE_NAME_CASE(FMA_VL) 9584 NODE_NAME_CASE(FCOPYSIGN_VL) 9585 NODE_NAME_CASE(SMIN_VL) 9586 NODE_NAME_CASE(SMAX_VL) 9587 NODE_NAME_CASE(UMIN_VL) 9588 NODE_NAME_CASE(UMAX_VL) 9589 NODE_NAME_CASE(FMINNUM_VL) 9590 NODE_NAME_CASE(FMAXNUM_VL) 9591 NODE_NAME_CASE(MULHS_VL) 9592 NODE_NAME_CASE(MULHU_VL) 9593 NODE_NAME_CASE(FP_TO_SINT_VL) 9594 NODE_NAME_CASE(FP_TO_UINT_VL) 9595 NODE_NAME_CASE(SINT_TO_FP_VL) 9596 NODE_NAME_CASE(UINT_TO_FP_VL) 9597 NODE_NAME_CASE(FP_EXTEND_VL) 9598 NODE_NAME_CASE(FP_ROUND_VL) 9599 NODE_NAME_CASE(VWMUL_VL) 9600 NODE_NAME_CASE(VWMULU_VL) 9601 NODE_NAME_CASE(SETCC_VL) 9602 NODE_NAME_CASE(VSELECT_VL) 9603 NODE_NAME_CASE(VMAND_VL) 9604 NODE_NAME_CASE(VMOR_VL) 9605 NODE_NAME_CASE(VMXOR_VL) 9606 NODE_NAME_CASE(VMCLR_VL) 9607 NODE_NAME_CASE(VMSET_VL) 9608 NODE_NAME_CASE(VRGATHER_VX_VL) 9609 NODE_NAME_CASE(VRGATHER_VV_VL) 9610 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9611 NODE_NAME_CASE(VSEXT_VL) 9612 NODE_NAME_CASE(VZEXT_VL) 9613 NODE_NAME_CASE(VCPOP_VL) 9614 NODE_NAME_CASE(VLE_VL) 9615 NODE_NAME_CASE(VSE_VL) 9616 NODE_NAME_CASE(READ_CSR) 9617 NODE_NAME_CASE(WRITE_CSR) 9618 NODE_NAME_CASE(SWAP_CSR) 9619 } 9620 // clang-format on 9621 return nullptr; 9622 #undef NODE_NAME_CASE 9623 } 9624 9625 /// getConstraintType - Given a constraint letter, return the type of 9626 /// constraint it is for this target. 9627 RISCVTargetLowering::ConstraintType 9628 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9629 if (Constraint.size() == 1) { 9630 switch (Constraint[0]) { 9631 default: 9632 break; 9633 case 'f': 9634 return C_RegisterClass; 9635 case 'I': 9636 case 'J': 9637 case 'K': 9638 return C_Immediate; 9639 case 'A': 9640 return C_Memory; 9641 case 'S': // A symbolic address 9642 return C_Other; 9643 } 9644 } else { 9645 if (Constraint == "vr" || Constraint == "vm") 9646 return C_RegisterClass; 9647 } 9648 return TargetLowering::getConstraintType(Constraint); 9649 } 9650 9651 std::pair<unsigned, const TargetRegisterClass *> 9652 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9653 StringRef Constraint, 9654 MVT VT) const { 9655 // First, see if this is a constraint that directly corresponds to a 9656 // RISCV register class. 9657 if (Constraint.size() == 1) { 9658 switch (Constraint[0]) { 9659 case 'r': 9660 // TODO: Support fixed vectors up to XLen for P extension? 9661 if (VT.isVector()) 9662 break; 9663 return std::make_pair(0U, &RISCV::GPRRegClass); 9664 case 'f': 9665 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9666 return std::make_pair(0U, &RISCV::FPR16RegClass); 9667 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9668 return std::make_pair(0U, &RISCV::FPR32RegClass); 9669 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9670 return std::make_pair(0U, &RISCV::FPR64RegClass); 9671 break; 9672 default: 9673 break; 9674 } 9675 } else if (Constraint == "vr") { 9676 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9677 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9678 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9679 return std::make_pair(0U, RC); 9680 } 9681 } else if (Constraint == "vm") { 9682 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 9683 return std::make_pair(0U, &RISCV::VMV0RegClass); 9684 } 9685 9686 // Clang will correctly decode the usage of register name aliases into their 9687 // official names. However, other frontends like `rustc` do not. This allows 9688 // users of these frontends to use the ABI names for registers in LLVM-style 9689 // register constraints. 9690 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9691 .Case("{zero}", RISCV::X0) 9692 .Case("{ra}", RISCV::X1) 9693 .Case("{sp}", RISCV::X2) 9694 .Case("{gp}", RISCV::X3) 9695 .Case("{tp}", RISCV::X4) 9696 .Case("{t0}", RISCV::X5) 9697 .Case("{t1}", RISCV::X6) 9698 .Case("{t2}", RISCV::X7) 9699 .Cases("{s0}", "{fp}", RISCV::X8) 9700 .Case("{s1}", RISCV::X9) 9701 .Case("{a0}", RISCV::X10) 9702 .Case("{a1}", RISCV::X11) 9703 .Case("{a2}", RISCV::X12) 9704 .Case("{a3}", RISCV::X13) 9705 .Case("{a4}", RISCV::X14) 9706 .Case("{a5}", RISCV::X15) 9707 .Case("{a6}", RISCV::X16) 9708 .Case("{a7}", RISCV::X17) 9709 .Case("{s2}", RISCV::X18) 9710 .Case("{s3}", RISCV::X19) 9711 .Case("{s4}", RISCV::X20) 9712 .Case("{s5}", RISCV::X21) 9713 .Case("{s6}", RISCV::X22) 9714 .Case("{s7}", RISCV::X23) 9715 .Case("{s8}", RISCV::X24) 9716 .Case("{s9}", RISCV::X25) 9717 .Case("{s10}", RISCV::X26) 9718 .Case("{s11}", RISCV::X27) 9719 .Case("{t3}", RISCV::X28) 9720 .Case("{t4}", RISCV::X29) 9721 .Case("{t5}", RISCV::X30) 9722 .Case("{t6}", RISCV::X31) 9723 .Default(RISCV::NoRegister); 9724 if (XRegFromAlias != RISCV::NoRegister) 9725 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9726 9727 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9728 // TableGen record rather than the AsmName to choose registers for InlineAsm 9729 // constraints, plus we want to match those names to the widest floating point 9730 // register type available, manually select floating point registers here. 9731 // 9732 // The second case is the ABI name of the register, so that frontends can also 9733 // use the ABI names in register constraint lists. 9734 if (Subtarget.hasStdExtF()) { 9735 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9736 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9737 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9738 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9739 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9740 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9741 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9742 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9743 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9744 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9745 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9746 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9747 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9748 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9749 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9750 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9751 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9752 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9753 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9754 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9755 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9756 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9757 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9758 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9759 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9760 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9761 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9762 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9763 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9764 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9765 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9766 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9767 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9768 .Default(RISCV::NoRegister); 9769 if (FReg != RISCV::NoRegister) { 9770 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9771 if (Subtarget.hasStdExtD()) { 9772 unsigned RegNo = FReg - RISCV::F0_F; 9773 unsigned DReg = RISCV::F0_D + RegNo; 9774 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9775 } 9776 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9777 } 9778 } 9779 9780 if (Subtarget.hasVInstructions()) { 9781 Register VReg = StringSwitch<Register>(Constraint.lower()) 9782 .Case("{v0}", RISCV::V0) 9783 .Case("{v1}", RISCV::V1) 9784 .Case("{v2}", RISCV::V2) 9785 .Case("{v3}", RISCV::V3) 9786 .Case("{v4}", RISCV::V4) 9787 .Case("{v5}", RISCV::V5) 9788 .Case("{v6}", RISCV::V6) 9789 .Case("{v7}", RISCV::V7) 9790 .Case("{v8}", RISCV::V8) 9791 .Case("{v9}", RISCV::V9) 9792 .Case("{v10}", RISCV::V10) 9793 .Case("{v11}", RISCV::V11) 9794 .Case("{v12}", RISCV::V12) 9795 .Case("{v13}", RISCV::V13) 9796 .Case("{v14}", RISCV::V14) 9797 .Case("{v15}", RISCV::V15) 9798 .Case("{v16}", RISCV::V16) 9799 .Case("{v17}", RISCV::V17) 9800 .Case("{v18}", RISCV::V18) 9801 .Case("{v19}", RISCV::V19) 9802 .Case("{v20}", RISCV::V20) 9803 .Case("{v21}", RISCV::V21) 9804 .Case("{v22}", RISCV::V22) 9805 .Case("{v23}", RISCV::V23) 9806 .Case("{v24}", RISCV::V24) 9807 .Case("{v25}", RISCV::V25) 9808 .Case("{v26}", RISCV::V26) 9809 .Case("{v27}", RISCV::V27) 9810 .Case("{v28}", RISCV::V28) 9811 .Case("{v29}", RISCV::V29) 9812 .Case("{v30}", RISCV::V30) 9813 .Case("{v31}", RISCV::V31) 9814 .Default(RISCV::NoRegister); 9815 if (VReg != RISCV::NoRegister) { 9816 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9817 return std::make_pair(VReg, &RISCV::VMRegClass); 9818 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9819 return std::make_pair(VReg, &RISCV::VRRegClass); 9820 for (const auto *RC : 9821 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9822 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9823 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9824 return std::make_pair(VReg, RC); 9825 } 9826 } 9827 } 9828 } 9829 9830 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9831 } 9832 9833 unsigned 9834 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9835 // Currently only support length 1 constraints. 9836 if (ConstraintCode.size() == 1) { 9837 switch (ConstraintCode[0]) { 9838 case 'A': 9839 return InlineAsm::Constraint_A; 9840 default: 9841 break; 9842 } 9843 } 9844 9845 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9846 } 9847 9848 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9849 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9850 SelectionDAG &DAG) const { 9851 // Currently only support length 1 constraints. 9852 if (Constraint.length() == 1) { 9853 switch (Constraint[0]) { 9854 case 'I': 9855 // Validate & create a 12-bit signed immediate operand. 9856 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9857 uint64_t CVal = C->getSExtValue(); 9858 if (isInt<12>(CVal)) 9859 Ops.push_back( 9860 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9861 } 9862 return; 9863 case 'J': 9864 // Validate & create an integer zero operand. 9865 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9866 if (C->getZExtValue() == 0) 9867 Ops.push_back( 9868 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9869 return; 9870 case 'K': 9871 // Validate & create a 5-bit unsigned immediate operand. 9872 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9873 uint64_t CVal = C->getZExtValue(); 9874 if (isUInt<5>(CVal)) 9875 Ops.push_back( 9876 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9877 } 9878 return; 9879 case 'S': 9880 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9881 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9882 GA->getValueType(0))); 9883 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9884 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9885 BA->getValueType(0))); 9886 } 9887 return; 9888 default: 9889 break; 9890 } 9891 } 9892 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9893 } 9894 9895 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9896 Instruction *Inst, 9897 AtomicOrdering Ord) const { 9898 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9899 return Builder.CreateFence(Ord); 9900 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9901 return Builder.CreateFence(AtomicOrdering::Release); 9902 return nullptr; 9903 } 9904 9905 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9906 Instruction *Inst, 9907 AtomicOrdering Ord) const { 9908 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9909 return Builder.CreateFence(AtomicOrdering::Acquire); 9910 return nullptr; 9911 } 9912 9913 TargetLowering::AtomicExpansionKind 9914 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9915 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9916 // point operations can't be used in an lr/sc sequence without breaking the 9917 // forward-progress guarantee. 9918 if (AI->isFloatingPointOperation()) 9919 return AtomicExpansionKind::CmpXChg; 9920 9921 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9922 if (Size == 8 || Size == 16) 9923 return AtomicExpansionKind::MaskedIntrinsic; 9924 return AtomicExpansionKind::None; 9925 } 9926 9927 static Intrinsic::ID 9928 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9929 if (XLen == 32) { 9930 switch (BinOp) { 9931 default: 9932 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9933 case AtomicRMWInst::Xchg: 9934 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9935 case AtomicRMWInst::Add: 9936 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9937 case AtomicRMWInst::Sub: 9938 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9939 case AtomicRMWInst::Nand: 9940 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9941 case AtomicRMWInst::Max: 9942 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9943 case AtomicRMWInst::Min: 9944 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9945 case AtomicRMWInst::UMax: 9946 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9947 case AtomicRMWInst::UMin: 9948 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9949 } 9950 } 9951 9952 if (XLen == 64) { 9953 switch (BinOp) { 9954 default: 9955 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9956 case AtomicRMWInst::Xchg: 9957 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9958 case AtomicRMWInst::Add: 9959 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9960 case AtomicRMWInst::Sub: 9961 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9962 case AtomicRMWInst::Nand: 9963 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9964 case AtomicRMWInst::Max: 9965 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9966 case AtomicRMWInst::Min: 9967 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9968 case AtomicRMWInst::UMax: 9969 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9970 case AtomicRMWInst::UMin: 9971 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9972 } 9973 } 9974 9975 llvm_unreachable("Unexpected XLen\n"); 9976 } 9977 9978 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 9979 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 9980 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 9981 unsigned XLen = Subtarget.getXLen(); 9982 Value *Ordering = 9983 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 9984 Type *Tys[] = {AlignedAddr->getType()}; 9985 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 9986 AI->getModule(), 9987 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 9988 9989 if (XLen == 64) { 9990 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 9991 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 9992 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 9993 } 9994 9995 Value *Result; 9996 9997 // Must pass the shift amount needed to sign extend the loaded value prior 9998 // to performing a signed comparison for min/max. ShiftAmt is the number of 9999 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10000 // is the number of bits to left+right shift the value in order to 10001 // sign-extend. 10002 if (AI->getOperation() == AtomicRMWInst::Min || 10003 AI->getOperation() == AtomicRMWInst::Max) { 10004 const DataLayout &DL = AI->getModule()->getDataLayout(); 10005 unsigned ValWidth = 10006 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10007 Value *SextShamt = 10008 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10009 Result = Builder.CreateCall(LrwOpScwLoop, 10010 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10011 } else { 10012 Result = 10013 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10014 } 10015 10016 if (XLen == 64) 10017 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10018 return Result; 10019 } 10020 10021 TargetLowering::AtomicExpansionKind 10022 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10023 AtomicCmpXchgInst *CI) const { 10024 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10025 if (Size == 8 || Size == 16) 10026 return AtomicExpansionKind::MaskedIntrinsic; 10027 return AtomicExpansionKind::None; 10028 } 10029 10030 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10031 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10032 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10033 unsigned XLen = Subtarget.getXLen(); 10034 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10035 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10036 if (XLen == 64) { 10037 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10038 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10039 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10040 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10041 } 10042 Type *Tys[] = {AlignedAddr->getType()}; 10043 Function *MaskedCmpXchg = 10044 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10045 Value *Result = Builder.CreateCall( 10046 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10047 if (XLen == 64) 10048 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10049 return Result; 10050 } 10051 10052 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10053 return false; 10054 } 10055 10056 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10057 EVT VT) const { 10058 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10059 return false; 10060 10061 switch (FPVT.getSimpleVT().SimpleTy) { 10062 case MVT::f16: 10063 return Subtarget.hasStdExtZfh(); 10064 case MVT::f32: 10065 return Subtarget.hasStdExtF(); 10066 case MVT::f64: 10067 return Subtarget.hasStdExtD(); 10068 default: 10069 return false; 10070 } 10071 } 10072 10073 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10074 EVT VT) const { 10075 VT = VT.getScalarType(); 10076 10077 if (!VT.isSimple()) 10078 return false; 10079 10080 switch (VT.getSimpleVT().SimpleTy) { 10081 case MVT::f16: 10082 return Subtarget.hasStdExtZfh(); 10083 case MVT::f32: 10084 return Subtarget.hasStdExtF(); 10085 case MVT::f64: 10086 return Subtarget.hasStdExtD(); 10087 default: 10088 break; 10089 } 10090 10091 return false; 10092 } 10093 10094 Register RISCVTargetLowering::getExceptionPointerRegister( 10095 const Constant *PersonalityFn) const { 10096 return RISCV::X10; 10097 } 10098 10099 Register RISCVTargetLowering::getExceptionSelectorRegister( 10100 const Constant *PersonalityFn) const { 10101 return RISCV::X11; 10102 } 10103 10104 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10105 // Return false to suppress the unnecessary extensions if the LibCall 10106 // arguments or return value is f32 type for LP64 ABI. 10107 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10108 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10109 return false; 10110 10111 return true; 10112 } 10113 10114 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10115 if (Subtarget.is64Bit() && Type == MVT::i32) 10116 return true; 10117 10118 return IsSigned; 10119 } 10120 10121 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10122 SDValue C) const { 10123 // Check integral scalar types. 10124 if (VT.isScalarInteger()) { 10125 // Omit the optimization if the sub target has the M extension and the data 10126 // size exceeds XLen. 10127 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10128 return false; 10129 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10130 // Break the MUL to a SLLI and an ADD/SUB. 10131 const APInt &Imm = ConstNode->getAPIntValue(); 10132 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10133 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10134 return true; 10135 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10136 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10137 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10138 (Imm - 8).isPowerOf2())) 10139 return true; 10140 // Omit the following optimization if the sub target has the M extension 10141 // and the data size >= XLen. 10142 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10143 return false; 10144 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10145 // a pair of LUI/ADDI. 10146 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10147 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10148 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10149 (1 - ImmS).isPowerOf2()) 10150 return true; 10151 } 10152 } 10153 } 10154 10155 return false; 10156 } 10157 10158 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10159 const SDValue &AddNode, const SDValue &ConstNode) const { 10160 // Let the DAGCombiner decide for vectors. 10161 EVT VT = AddNode.getValueType(); 10162 if (VT.isVector()) 10163 return true; 10164 10165 // Let the DAGCombiner decide for larger types. 10166 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10167 return true; 10168 10169 // It is worse if c1 is simm12 while c1*c2 is not. 10170 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10171 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10172 const APInt &C1 = C1Node->getAPIntValue(); 10173 const APInt &C2 = C2Node->getAPIntValue(); 10174 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10175 return false; 10176 10177 // Default to true and let the DAGCombiner decide. 10178 return true; 10179 } 10180 10181 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10182 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10183 bool *Fast) const { 10184 if (!VT.isVector()) 10185 return false; 10186 10187 EVT ElemVT = VT.getVectorElementType(); 10188 if (Alignment >= ElemVT.getStoreSize()) { 10189 if (Fast) 10190 *Fast = true; 10191 return true; 10192 } 10193 10194 return false; 10195 } 10196 10197 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10198 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10199 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10200 bool IsABIRegCopy = CC.hasValue(); 10201 EVT ValueVT = Val.getValueType(); 10202 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10203 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10204 // and cast to f32. 10205 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10206 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10207 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10208 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10209 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 10210 Parts[0] = Val; 10211 return true; 10212 } 10213 10214 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10215 LLVMContext &Context = *DAG.getContext(); 10216 EVT ValueEltVT = ValueVT.getVectorElementType(); 10217 EVT PartEltVT = PartVT.getVectorElementType(); 10218 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10219 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10220 if (PartVTBitSize % ValueVTBitSize == 0) { 10221 assert(PartVTBitSize >= ValueVTBitSize); 10222 // If the element types are different, bitcast to the same element type of 10223 // PartVT first. 10224 // Give an example here, we want copy a <vscale x 1 x i8> value to 10225 // <vscale x 4 x i16>. 10226 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 10227 // subvector, then we can bitcast to <vscale x 4 x i16>. 10228 if (ValueEltVT != PartEltVT) { 10229 if (PartVTBitSize > ValueVTBitSize) { 10230 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10231 assert(Count != 0 && "The number of element should not be zero."); 10232 EVT SameEltTypeVT = 10233 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10234 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 10235 DAG.getUNDEF(SameEltTypeVT), Val, 10236 DAG.getVectorIdxConstant(0, DL)); 10237 } 10238 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 10239 } else { 10240 Val = 10241 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 10242 Val, DAG.getVectorIdxConstant(0, DL)); 10243 } 10244 Parts[0] = Val; 10245 return true; 10246 } 10247 } 10248 return false; 10249 } 10250 10251 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10252 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10253 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10254 bool IsABIRegCopy = CC.hasValue(); 10255 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10256 SDValue Val = Parts[0]; 10257 10258 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10259 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10260 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10261 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10262 return Val; 10263 } 10264 10265 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10266 LLVMContext &Context = *DAG.getContext(); 10267 SDValue Val = Parts[0]; 10268 EVT ValueEltVT = ValueVT.getVectorElementType(); 10269 EVT PartEltVT = PartVT.getVectorElementType(); 10270 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10271 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10272 if (PartVTBitSize % ValueVTBitSize == 0) { 10273 assert(PartVTBitSize >= ValueVTBitSize); 10274 EVT SameEltTypeVT = ValueVT; 10275 // If the element types are different, convert it to the same element type 10276 // of PartVT. 10277 // Give an example here, we want copy a <vscale x 1 x i8> value from 10278 // <vscale x 4 x i16>. 10279 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 10280 // then we can extract <vscale x 1 x i8>. 10281 if (ValueEltVT != PartEltVT) { 10282 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10283 assert(Count != 0 && "The number of element should not be zero."); 10284 SameEltTypeVT = 10285 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10286 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 10287 } 10288 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 10289 DAG.getVectorIdxConstant(0, DL)); 10290 return Val; 10291 } 10292 } 10293 return SDValue(); 10294 } 10295 10296 #define GET_REGISTER_MATCHER 10297 #include "RISCVGenAsmMatcher.inc" 10298 10299 Register 10300 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10301 const MachineFunction &MF) const { 10302 Register Reg = MatchRegisterAltName(RegName); 10303 if (Reg == RISCV::NoRegister) 10304 Reg = MatchRegisterName(RegName); 10305 if (Reg == RISCV::NoRegister) 10306 report_fatal_error( 10307 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10308 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10309 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10310 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10311 StringRef(RegName) + "\".")); 10312 return Reg; 10313 } 10314 10315 namespace llvm { 10316 namespace RISCVVIntrinsicsTable { 10317 10318 #define GET_RISCVVIntrinsicsTable_IMPL 10319 #include "RISCVGenSearchableTables.inc" 10320 10321 } // namespace RISCVVIntrinsicsTable 10322 10323 } // namespace llvm 10324