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/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 } 307 308 if (Subtarget.hasStdExtZbt()) { 309 setOperationAction(ISD::FSHL, XLenVT, Custom); 310 setOperationAction(ISD::FSHR, XLenVT, Custom); 311 setOperationAction(ISD::SELECT, XLenVT, Legal); 312 313 if (Subtarget.is64Bit()) { 314 setOperationAction(ISD::FSHL, MVT::i32, Custom); 315 setOperationAction(ISD::FSHR, MVT::i32, Custom); 316 } 317 } else { 318 setOperationAction(ISD::SELECT, XLenVT, Custom); 319 } 320 321 static const ISD::CondCode FPCCToExpand[] = { 322 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 323 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 324 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 325 326 static const ISD::NodeType FPOpToExpand[] = { 327 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 328 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 329 330 if (Subtarget.hasStdExtZfh()) 331 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 332 333 if (Subtarget.hasStdExtZfh()) { 334 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 335 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 336 setOperationAction(ISD::LRINT, MVT::f16, Legal); 337 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 338 setOperationAction(ISD::LROUND, MVT::f16, Legal); 339 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 340 setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal); 341 setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal); 342 setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal); 343 setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 345 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 346 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 349 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 350 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 351 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 352 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal); 353 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal); 354 for (auto CC : FPCCToExpand) 355 setCondCodeAction(CC, MVT::f16, Expand); 356 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 357 setOperationAction(ISD::SELECT, MVT::f16, Custom); 358 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 359 360 setOperationAction(ISD::FREM, MVT::f16, Promote); 361 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 362 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 363 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 364 setOperationAction(ISD::FRINT, MVT::f16, Promote); 365 setOperationAction(ISD::FROUND, MVT::f16, Promote); 366 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 367 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 368 setOperationAction(ISD::FPOW, MVT::f16, Promote); 369 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 370 setOperationAction(ISD::FCOS, MVT::f16, Promote); 371 setOperationAction(ISD::FSIN, MVT::f16, Promote); 372 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 373 setOperationAction(ISD::FEXP, MVT::f16, Promote); 374 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 375 setOperationAction(ISD::FLOG, MVT::f16, Promote); 376 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 377 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 378 379 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 380 // complete support for all operations in LegalizeDAG. 381 382 // We need to custom promote this. 383 if (Subtarget.is64Bit()) 384 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 385 } 386 387 if (Subtarget.hasStdExtF()) { 388 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 389 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 390 setOperationAction(ISD::LRINT, MVT::f32, Legal); 391 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 392 setOperationAction(ISD::LROUND, MVT::f32, Legal); 393 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 394 setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal); 395 setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal); 396 setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal); 397 setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal); 398 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 399 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 400 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 401 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 402 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 404 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 405 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 406 for (auto CC : FPCCToExpand) 407 setCondCodeAction(CC, MVT::f32, Expand); 408 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 409 setOperationAction(ISD::SELECT, MVT::f32, Custom); 410 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f32, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 415 } 416 417 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 418 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 419 420 if (Subtarget.hasStdExtD()) { 421 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 422 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 423 setOperationAction(ISD::LRINT, MVT::f64, Legal); 424 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 425 setOperationAction(ISD::LROUND, MVT::f64, Legal); 426 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 427 setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal); 428 setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal); 429 setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal); 431 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 432 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 433 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 434 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 435 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 436 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 437 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 438 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 439 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 440 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 441 for (auto CC : FPCCToExpand) 442 setCondCodeAction(CC, MVT::f64, Expand); 443 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 444 setOperationAction(ISD::SELECT, MVT::f64, Custom); 445 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 446 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 447 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 448 for (auto Op : FPOpToExpand) 449 setOperationAction(Op, MVT::f64, Expand); 450 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 451 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 452 } 453 454 if (Subtarget.is64Bit()) { 455 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 456 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 457 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 458 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 459 } 460 461 if (Subtarget.hasStdExtF()) { 462 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 463 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 464 465 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 466 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 467 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 468 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 469 470 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 471 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 472 } 473 474 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 475 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 476 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 477 setOperationAction(ISD::JumpTable, XLenVT, Custom); 478 479 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 480 481 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 482 // Unfortunately this can't be determined just from the ISA naming string. 483 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 484 Subtarget.is64Bit() ? Legal : Custom); 485 486 setOperationAction(ISD::TRAP, MVT::Other, Legal); 487 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 488 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 489 if (Subtarget.is64Bit()) 490 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 491 492 if (Subtarget.hasStdExtA()) { 493 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 494 setMinCmpXchgSizeInBits(32); 495 } else { 496 setMaxAtomicSizeInBitsSupported(0); 497 } 498 499 setBooleanContents(ZeroOrOneBooleanContent); 500 501 if (Subtarget.hasVInstructions()) { 502 setBooleanVectorContents(ZeroOrOneBooleanContent); 503 504 setOperationAction(ISD::VSCALE, XLenVT, Custom); 505 506 // RVV intrinsics may have illegal operands. 507 // We also need to custom legalize vmv.x.s. 508 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 509 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 510 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 511 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 512 if (Subtarget.is64Bit()) { 513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 514 } else { 515 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 516 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 517 } 518 519 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 520 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 521 522 static const unsigned IntegerVPOps[] = { 523 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 524 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 525 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 526 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 527 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 528 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 529 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 530 ISD::VP_MERGE, ISD::VP_SELECT}; 531 532 static const unsigned FloatingPointVPOps[] = { 533 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 534 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 535 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, 536 ISD::VP_SELECT}; 537 538 if (!Subtarget.is64Bit()) { 539 // We must custom-lower certain vXi64 operations on RV32 due to the vector 540 // element type being illegal. 541 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 542 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 543 544 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 545 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 546 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 547 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 548 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 549 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 550 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 551 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 552 553 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 554 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 555 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 556 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 557 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 558 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 559 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 560 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 561 } 562 563 for (MVT VT : BoolVecVTs) { 564 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 565 566 // Mask VTs are custom-expanded into a series of standard nodes 567 setOperationAction(ISD::TRUNCATE, VT, Custom); 568 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 569 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 570 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 571 572 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 573 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 574 575 setOperationAction(ISD::SELECT, VT, Custom); 576 setOperationAction(ISD::SELECT_CC, VT, Expand); 577 setOperationAction(ISD::VSELECT, VT, Expand); 578 setOperationAction(ISD::VP_MERGE, VT, Expand); 579 setOperationAction(ISD::VP_SELECT, VT, Expand); 580 581 setOperationAction(ISD::VP_AND, VT, Custom); 582 setOperationAction(ISD::VP_OR, VT, Custom); 583 setOperationAction(ISD::VP_XOR, VT, Custom); 584 585 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 586 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 587 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 588 589 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 590 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 591 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 592 593 // RVV has native int->float & float->int conversions where the 594 // element type sizes are within one power-of-two of each other. Any 595 // wider distances between type sizes have to be lowered as sequences 596 // which progressively narrow the gap in stages. 597 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 598 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 599 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 600 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 601 602 // Expand all extending loads to types larger than this, and truncating 603 // stores from types larger than this. 604 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 605 setTruncStoreAction(OtherVT, VT, Expand); 606 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 607 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 608 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 609 } 610 } 611 612 for (MVT VT : IntVecVTs) { 613 if (VT.getVectorElementType() == MVT::i64 && 614 !Subtarget.hasVInstructionsI64()) 615 continue; 616 617 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 618 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 619 620 // Vectors implement MULHS/MULHU. 621 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 622 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 623 624 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 625 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 626 setOperationAction(ISD::MULHU, VT, Expand); 627 setOperationAction(ISD::MULHS, VT, Expand); 628 } 629 630 setOperationAction(ISD::SMIN, VT, Legal); 631 setOperationAction(ISD::SMAX, VT, Legal); 632 setOperationAction(ISD::UMIN, VT, Legal); 633 setOperationAction(ISD::UMAX, VT, Legal); 634 635 setOperationAction(ISD::ROTL, VT, Expand); 636 setOperationAction(ISD::ROTR, VT, Expand); 637 638 setOperationAction(ISD::CTTZ, VT, Expand); 639 setOperationAction(ISD::CTLZ, VT, Expand); 640 setOperationAction(ISD::CTPOP, VT, Expand); 641 642 setOperationAction(ISD::BSWAP, VT, Expand); 643 644 // Custom-lower extensions and truncations from/to mask types. 645 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 646 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 647 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 648 649 // RVV has native int->float & float->int conversions where the 650 // element type sizes are within one power-of-two of each other. Any 651 // wider distances between type sizes have to be lowered as sequences 652 // which progressively narrow the gap in stages. 653 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 654 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 655 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 656 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 657 658 setOperationAction(ISD::SADDSAT, VT, Legal); 659 setOperationAction(ISD::UADDSAT, VT, Legal); 660 setOperationAction(ISD::SSUBSAT, VT, Legal); 661 setOperationAction(ISD::USUBSAT, VT, Legal); 662 663 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 664 // nodes which truncate by one power of two at a time. 665 setOperationAction(ISD::TRUNCATE, VT, Custom); 666 667 // Custom-lower insert/extract operations to simplify patterns. 668 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 669 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 670 671 // Custom-lower reduction operations to set up the corresponding custom 672 // nodes' operands. 673 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 674 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 675 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 676 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 677 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 678 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 679 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 681 682 for (unsigned VPOpc : IntegerVPOps) 683 setOperationAction(VPOpc, VT, Custom); 684 685 setOperationAction(ISD::LOAD, VT, Custom); 686 setOperationAction(ISD::STORE, VT, Custom); 687 688 setOperationAction(ISD::MLOAD, VT, Custom); 689 setOperationAction(ISD::MSTORE, VT, Custom); 690 setOperationAction(ISD::MGATHER, VT, Custom); 691 setOperationAction(ISD::MSCATTER, VT, Custom); 692 693 setOperationAction(ISD::VP_LOAD, VT, Custom); 694 setOperationAction(ISD::VP_STORE, VT, Custom); 695 setOperationAction(ISD::VP_GATHER, VT, Custom); 696 setOperationAction(ISD::VP_SCATTER, VT, Custom); 697 698 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 699 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 700 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 701 702 setOperationAction(ISD::SELECT, VT, Custom); 703 setOperationAction(ISD::SELECT_CC, VT, Expand); 704 705 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 706 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 707 708 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 709 setTruncStoreAction(VT, OtherVT, Expand); 710 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 711 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 712 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 713 } 714 715 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 716 // type that can represent the value exactly. 717 if (VT.getVectorElementType() != MVT::i64) { 718 MVT FloatEltVT = 719 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 720 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 721 if (isTypeLegal(FloatVT)) { 722 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 723 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 724 } 725 } 726 } 727 728 // Expand various CCs to best match the RVV ISA, which natively supports UNE 729 // but no other unordered comparisons, and supports all ordered comparisons 730 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 731 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 732 // and we pattern-match those back to the "original", swapping operands once 733 // more. This way we catch both operations and both "vf" and "fv" forms with 734 // fewer patterns. 735 static const ISD::CondCode VFPCCToExpand[] = { 736 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 737 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 738 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 739 }; 740 741 // Sets common operation actions on RVV floating-point vector types. 742 const auto SetCommonVFPActions = [&](MVT VT) { 743 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 744 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 745 // sizes are within one power-of-two of each other. Therefore conversions 746 // between vXf16 and vXf64 must be lowered as sequences which convert via 747 // vXf32. 748 setOperationAction(ISD::FP_ROUND, VT, Custom); 749 setOperationAction(ISD::FP_EXTEND, VT, Custom); 750 // Custom-lower insert/extract operations to simplify patterns. 751 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 752 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 753 // Expand various condition codes (explained above). 754 for (auto CC : VFPCCToExpand) 755 setCondCodeAction(CC, VT, Expand); 756 757 setOperationAction(ISD::FMINNUM, VT, Legal); 758 setOperationAction(ISD::FMAXNUM, VT, Legal); 759 760 setOperationAction(ISD::FTRUNC, VT, Custom); 761 setOperationAction(ISD::FCEIL, VT, Custom); 762 setOperationAction(ISD::FFLOOR, VT, Custom); 763 764 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 765 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 766 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 767 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 768 769 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 770 771 setOperationAction(ISD::LOAD, VT, Custom); 772 setOperationAction(ISD::STORE, VT, Custom); 773 774 setOperationAction(ISD::MLOAD, VT, Custom); 775 setOperationAction(ISD::MSTORE, VT, Custom); 776 setOperationAction(ISD::MGATHER, VT, Custom); 777 setOperationAction(ISD::MSCATTER, VT, Custom); 778 779 setOperationAction(ISD::VP_LOAD, VT, Custom); 780 setOperationAction(ISD::VP_STORE, VT, Custom); 781 setOperationAction(ISD::VP_GATHER, VT, Custom); 782 setOperationAction(ISD::VP_SCATTER, VT, Custom); 783 784 setOperationAction(ISD::SELECT, VT, Custom); 785 setOperationAction(ISD::SELECT_CC, VT, Expand); 786 787 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 788 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 789 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 790 791 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 792 793 for (unsigned VPOpc : FloatingPointVPOps) 794 setOperationAction(VPOpc, VT, Custom); 795 }; 796 797 // Sets common extload/truncstore actions on RVV floating-point vector 798 // types. 799 const auto SetCommonVFPExtLoadTruncStoreActions = 800 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 801 for (auto SmallVT : SmallerVTs) { 802 setTruncStoreAction(VT, SmallVT, Expand); 803 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 804 } 805 }; 806 807 if (Subtarget.hasVInstructionsF16()) 808 for (MVT VT : F16VecVTs) 809 SetCommonVFPActions(VT); 810 811 for (MVT VT : F32VecVTs) { 812 if (Subtarget.hasVInstructionsF32()) 813 SetCommonVFPActions(VT); 814 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 815 } 816 817 for (MVT VT : F64VecVTs) { 818 if (Subtarget.hasVInstructionsF64()) 819 SetCommonVFPActions(VT); 820 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 821 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 822 } 823 824 if (Subtarget.useRVVForFixedLengthVectors()) { 825 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 826 if (!useRVVForFixedLengthVectorVT(VT)) 827 continue; 828 829 // By default everything must be expanded. 830 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 831 setOperationAction(Op, VT, Expand); 832 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 833 setTruncStoreAction(VT, OtherVT, Expand); 834 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 835 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 836 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 837 } 838 839 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 840 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 841 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 842 843 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 844 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 845 846 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 847 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 848 849 setOperationAction(ISD::LOAD, VT, Custom); 850 setOperationAction(ISD::STORE, VT, Custom); 851 852 setOperationAction(ISD::SETCC, VT, Custom); 853 854 setOperationAction(ISD::SELECT, VT, Custom); 855 856 setOperationAction(ISD::TRUNCATE, VT, Custom); 857 858 setOperationAction(ISD::BITCAST, VT, Custom); 859 860 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 861 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 862 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 863 864 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 865 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 866 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 867 868 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 869 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 870 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 871 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 872 873 // Operations below are different for between masks and other vectors. 874 if (VT.getVectorElementType() == MVT::i1) { 875 setOperationAction(ISD::VP_AND, VT, Custom); 876 setOperationAction(ISD::VP_OR, VT, Custom); 877 setOperationAction(ISD::VP_XOR, VT, Custom); 878 setOperationAction(ISD::AND, VT, Custom); 879 setOperationAction(ISD::OR, VT, Custom); 880 setOperationAction(ISD::XOR, VT, Custom); 881 continue; 882 } 883 884 // Use SPLAT_VECTOR to prevent type legalization from destroying the 885 // splats when type legalizing i64 scalar on RV32. 886 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 887 // improvements first. 888 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 889 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 890 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 891 } 892 893 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 894 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 895 896 setOperationAction(ISD::MLOAD, VT, Custom); 897 setOperationAction(ISD::MSTORE, VT, Custom); 898 setOperationAction(ISD::MGATHER, VT, Custom); 899 setOperationAction(ISD::MSCATTER, VT, Custom); 900 901 setOperationAction(ISD::VP_LOAD, VT, Custom); 902 setOperationAction(ISD::VP_STORE, VT, Custom); 903 setOperationAction(ISD::VP_GATHER, VT, Custom); 904 setOperationAction(ISD::VP_SCATTER, VT, Custom); 905 906 setOperationAction(ISD::ADD, VT, Custom); 907 setOperationAction(ISD::MUL, VT, Custom); 908 setOperationAction(ISD::SUB, VT, Custom); 909 setOperationAction(ISD::AND, VT, Custom); 910 setOperationAction(ISD::OR, VT, Custom); 911 setOperationAction(ISD::XOR, VT, Custom); 912 setOperationAction(ISD::SDIV, VT, Custom); 913 setOperationAction(ISD::SREM, VT, Custom); 914 setOperationAction(ISD::UDIV, VT, Custom); 915 setOperationAction(ISD::UREM, VT, Custom); 916 setOperationAction(ISD::SHL, VT, Custom); 917 setOperationAction(ISD::SRA, VT, Custom); 918 setOperationAction(ISD::SRL, VT, Custom); 919 920 setOperationAction(ISD::SMIN, VT, Custom); 921 setOperationAction(ISD::SMAX, VT, Custom); 922 setOperationAction(ISD::UMIN, VT, Custom); 923 setOperationAction(ISD::UMAX, VT, Custom); 924 setOperationAction(ISD::ABS, VT, Custom); 925 926 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 927 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 928 setOperationAction(ISD::MULHS, VT, Custom); 929 setOperationAction(ISD::MULHU, VT, Custom); 930 } 931 932 setOperationAction(ISD::SADDSAT, VT, Custom); 933 setOperationAction(ISD::UADDSAT, VT, Custom); 934 setOperationAction(ISD::SSUBSAT, VT, Custom); 935 setOperationAction(ISD::USUBSAT, VT, Custom); 936 937 setOperationAction(ISD::VSELECT, VT, Custom); 938 setOperationAction(ISD::SELECT_CC, VT, Expand); 939 940 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 941 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 942 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 943 944 // Custom-lower reduction operations to set up the corresponding custom 945 // nodes' operands. 946 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 947 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 948 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 949 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 950 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 951 952 for (unsigned VPOpc : IntegerVPOps) 953 setOperationAction(VPOpc, VT, Custom); 954 955 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 956 // type that can represent the value exactly. 957 if (VT.getVectorElementType() != MVT::i64) { 958 MVT FloatEltVT = 959 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 960 EVT FloatVT = 961 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 962 if (isTypeLegal(FloatVT)) { 963 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 964 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 965 } 966 } 967 } 968 969 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 970 if (!useRVVForFixedLengthVectorVT(VT)) 971 continue; 972 973 // By default everything must be expanded. 974 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 975 setOperationAction(Op, VT, Expand); 976 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 977 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 978 setTruncStoreAction(VT, OtherVT, Expand); 979 } 980 981 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 982 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 983 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 984 985 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 986 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 987 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 988 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 990 991 setOperationAction(ISD::LOAD, VT, Custom); 992 setOperationAction(ISD::STORE, VT, Custom); 993 setOperationAction(ISD::MLOAD, VT, Custom); 994 setOperationAction(ISD::MSTORE, VT, Custom); 995 setOperationAction(ISD::MGATHER, VT, Custom); 996 setOperationAction(ISD::MSCATTER, VT, Custom); 997 998 setOperationAction(ISD::VP_LOAD, VT, Custom); 999 setOperationAction(ISD::VP_STORE, VT, Custom); 1000 setOperationAction(ISD::VP_GATHER, VT, Custom); 1001 setOperationAction(ISD::VP_SCATTER, VT, Custom); 1002 1003 setOperationAction(ISD::FADD, VT, Custom); 1004 setOperationAction(ISD::FSUB, VT, Custom); 1005 setOperationAction(ISD::FMUL, VT, Custom); 1006 setOperationAction(ISD::FDIV, VT, Custom); 1007 setOperationAction(ISD::FNEG, VT, Custom); 1008 setOperationAction(ISD::FABS, VT, Custom); 1009 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1010 setOperationAction(ISD::FSQRT, VT, Custom); 1011 setOperationAction(ISD::FMA, VT, Custom); 1012 setOperationAction(ISD::FMINNUM, VT, Custom); 1013 setOperationAction(ISD::FMAXNUM, VT, Custom); 1014 1015 setOperationAction(ISD::FP_ROUND, VT, Custom); 1016 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1017 1018 setOperationAction(ISD::FTRUNC, VT, Custom); 1019 setOperationAction(ISD::FCEIL, VT, Custom); 1020 setOperationAction(ISD::FFLOOR, VT, Custom); 1021 1022 for (auto CC : VFPCCToExpand) 1023 setCondCodeAction(CC, VT, Expand); 1024 1025 setOperationAction(ISD::VSELECT, VT, Custom); 1026 setOperationAction(ISD::SELECT, VT, Custom); 1027 setOperationAction(ISD::SELECT_CC, VT, Expand); 1028 1029 setOperationAction(ISD::BITCAST, VT, Custom); 1030 1031 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1032 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1033 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1034 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1035 1036 for (unsigned VPOpc : FloatingPointVPOps) 1037 setOperationAction(VPOpc, VT, Custom); 1038 } 1039 1040 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1041 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1042 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1043 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1044 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1045 if (Subtarget.hasStdExtZfh()) 1046 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1047 if (Subtarget.hasStdExtF()) 1048 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1049 if (Subtarget.hasStdExtD()) 1050 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1051 } 1052 } 1053 1054 // Function alignments. 1055 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1056 setMinFunctionAlignment(FunctionAlignment); 1057 setPrefFunctionAlignment(FunctionAlignment); 1058 1059 setMinimumJumpTableEntries(5); 1060 1061 // Jumps are expensive, compared to logic 1062 setJumpIsExpensive(); 1063 1064 setTargetDAGCombine(ISD::ADD); 1065 setTargetDAGCombine(ISD::SUB); 1066 setTargetDAGCombine(ISD::AND); 1067 setTargetDAGCombine(ISD::OR); 1068 setTargetDAGCombine(ISD::XOR); 1069 setTargetDAGCombine(ISD::ANY_EXTEND); 1070 if (Subtarget.hasStdExtF()) { 1071 setTargetDAGCombine(ISD::ZERO_EXTEND); 1072 setTargetDAGCombine(ISD::FP_TO_SINT); 1073 setTargetDAGCombine(ISD::FP_TO_UINT); 1074 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1075 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1076 } 1077 if (Subtarget.hasVInstructions()) { 1078 setTargetDAGCombine(ISD::FCOPYSIGN); 1079 setTargetDAGCombine(ISD::MGATHER); 1080 setTargetDAGCombine(ISD::MSCATTER); 1081 setTargetDAGCombine(ISD::VP_GATHER); 1082 setTargetDAGCombine(ISD::VP_SCATTER); 1083 setTargetDAGCombine(ISD::SRA); 1084 setTargetDAGCombine(ISD::SRL); 1085 setTargetDAGCombine(ISD::SHL); 1086 setTargetDAGCombine(ISD::STORE); 1087 } 1088 1089 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1090 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1091 } 1092 1093 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1094 LLVMContext &Context, 1095 EVT VT) const { 1096 if (!VT.isVector()) 1097 return getPointerTy(DL); 1098 if (Subtarget.hasVInstructions() && 1099 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1100 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1101 return VT.changeVectorElementTypeToInteger(); 1102 } 1103 1104 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1105 return Subtarget.getXLenVT(); 1106 } 1107 1108 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1109 const CallInst &I, 1110 MachineFunction &MF, 1111 unsigned Intrinsic) const { 1112 auto &DL = I.getModule()->getDataLayout(); 1113 switch (Intrinsic) { 1114 default: 1115 return false; 1116 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1117 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1118 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1119 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1120 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1121 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1122 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1123 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1124 case Intrinsic::riscv_masked_cmpxchg_i32: 1125 Info.opc = ISD::INTRINSIC_W_CHAIN; 1126 Info.memVT = MVT::i32; 1127 Info.ptrVal = I.getArgOperand(0); 1128 Info.offset = 0; 1129 Info.align = Align(4); 1130 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1131 MachineMemOperand::MOVolatile; 1132 return true; 1133 case Intrinsic::riscv_masked_strided_load: 1134 Info.opc = ISD::INTRINSIC_W_CHAIN; 1135 Info.ptrVal = I.getArgOperand(1); 1136 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1137 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1138 Info.size = MemoryLocation::UnknownSize; 1139 Info.flags |= MachineMemOperand::MOLoad; 1140 return true; 1141 case Intrinsic::riscv_masked_strided_store: 1142 Info.opc = ISD::INTRINSIC_VOID; 1143 Info.ptrVal = I.getArgOperand(1); 1144 Info.memVT = 1145 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1146 Info.align = Align( 1147 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1148 8); 1149 Info.size = MemoryLocation::UnknownSize; 1150 Info.flags |= MachineMemOperand::MOStore; 1151 return true; 1152 } 1153 } 1154 1155 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1156 const AddrMode &AM, Type *Ty, 1157 unsigned AS, 1158 Instruction *I) const { 1159 // No global is ever allowed as a base. 1160 if (AM.BaseGV) 1161 return false; 1162 1163 // Require a 12-bit signed offset. 1164 if (!isInt<12>(AM.BaseOffs)) 1165 return false; 1166 1167 switch (AM.Scale) { 1168 case 0: // "r+i" or just "i", depending on HasBaseReg. 1169 break; 1170 case 1: 1171 if (!AM.HasBaseReg) // allow "r+i". 1172 break; 1173 return false; // disallow "r+r" or "r+r+i". 1174 default: 1175 return false; 1176 } 1177 1178 return true; 1179 } 1180 1181 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1182 return isInt<12>(Imm); 1183 } 1184 1185 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1186 return isInt<12>(Imm); 1187 } 1188 1189 // On RV32, 64-bit integers are split into their high and low parts and held 1190 // in two different registers, so the trunc is free since the low register can 1191 // just be used. 1192 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1193 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1194 return false; 1195 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1196 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1197 return (SrcBits == 64 && DestBits == 32); 1198 } 1199 1200 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1201 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1202 !SrcVT.isInteger() || !DstVT.isInteger()) 1203 return false; 1204 unsigned SrcBits = SrcVT.getSizeInBits(); 1205 unsigned DestBits = DstVT.getSizeInBits(); 1206 return (SrcBits == 64 && DestBits == 32); 1207 } 1208 1209 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1210 // Zexts are free if they can be combined with a load. 1211 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1212 // poorly with type legalization of compares preferring sext. 1213 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1214 EVT MemVT = LD->getMemoryVT(); 1215 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1216 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1217 LD->getExtensionType() == ISD::ZEXTLOAD)) 1218 return true; 1219 } 1220 1221 return TargetLowering::isZExtFree(Val, VT2); 1222 } 1223 1224 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1225 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1226 } 1227 1228 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1229 return Subtarget.hasStdExtZbb(); 1230 } 1231 1232 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1233 return Subtarget.hasStdExtZbb(); 1234 } 1235 1236 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1237 EVT VT = Y.getValueType(); 1238 1239 // FIXME: Support vectors once we have tests. 1240 if (VT.isVector()) 1241 return false; 1242 1243 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1244 Subtarget.hasStdExtZbkb()) && 1245 !isa<ConstantSDNode>(Y); 1246 } 1247 1248 /// Check if sinking \p I's operands to I's basic block is profitable, because 1249 /// the operands can be folded into a target instruction, e.g. 1250 /// splats of scalars can fold into vector instructions. 1251 bool RISCVTargetLowering::shouldSinkOperands( 1252 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1253 using namespace llvm::PatternMatch; 1254 1255 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1256 return false; 1257 1258 auto IsSinker = [&](Instruction *I, int Operand) { 1259 switch (I->getOpcode()) { 1260 case Instruction::Add: 1261 case Instruction::Sub: 1262 case Instruction::Mul: 1263 case Instruction::And: 1264 case Instruction::Or: 1265 case Instruction::Xor: 1266 case Instruction::FAdd: 1267 case Instruction::FSub: 1268 case Instruction::FMul: 1269 case Instruction::FDiv: 1270 case Instruction::ICmp: 1271 case Instruction::FCmp: 1272 return true; 1273 case Instruction::Shl: 1274 case Instruction::LShr: 1275 case Instruction::AShr: 1276 case Instruction::UDiv: 1277 case Instruction::SDiv: 1278 case Instruction::URem: 1279 case Instruction::SRem: 1280 return Operand == 1; 1281 case Instruction::Call: 1282 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1283 switch (II->getIntrinsicID()) { 1284 case Intrinsic::fma: 1285 return Operand == 0 || Operand == 1; 1286 // FIXME: Our patterns can only match vx/vf instructions when the splat 1287 // it on the RHS, because TableGen doesn't recognize our VP operations 1288 // as commutative. 1289 case Intrinsic::vp_add: 1290 case Intrinsic::vp_mul: 1291 case Intrinsic::vp_and: 1292 case Intrinsic::vp_or: 1293 case Intrinsic::vp_xor: 1294 case Intrinsic::vp_fadd: 1295 case Intrinsic::vp_fmul: 1296 case Intrinsic::vp_shl: 1297 case Intrinsic::vp_lshr: 1298 case Intrinsic::vp_ashr: 1299 case Intrinsic::vp_udiv: 1300 case Intrinsic::vp_sdiv: 1301 case Intrinsic::vp_urem: 1302 case Intrinsic::vp_srem: 1303 return Operand == 1; 1304 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1305 // explicit patterns for both LHS and RHS (as 'vr' versions). 1306 case Intrinsic::vp_sub: 1307 case Intrinsic::vp_fsub: 1308 case Intrinsic::vp_fdiv: 1309 return Operand == 0 || Operand == 1; 1310 default: 1311 return false; 1312 } 1313 } 1314 return false; 1315 default: 1316 return false; 1317 } 1318 }; 1319 1320 for (auto OpIdx : enumerate(I->operands())) { 1321 if (!IsSinker(I, OpIdx.index())) 1322 continue; 1323 1324 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1325 // Make sure we are not already sinking this operand 1326 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1327 continue; 1328 1329 // We are looking for a splat that can be sunk. 1330 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1331 m_Undef(), m_ZeroMask()))) 1332 continue; 1333 1334 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1335 // and vector registers 1336 for (Use &U : Op->uses()) { 1337 Instruction *Insn = cast<Instruction>(U.getUser()); 1338 if (!IsSinker(Insn, U.getOperandNo())) 1339 return false; 1340 } 1341 1342 Ops.push_back(&Op->getOperandUse(0)); 1343 Ops.push_back(&OpIdx.value()); 1344 } 1345 return true; 1346 } 1347 1348 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1349 bool ForCodeSize) const { 1350 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1351 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1352 return false; 1353 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1354 return false; 1355 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1356 return false; 1357 return Imm.isZero(); 1358 } 1359 1360 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1361 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1362 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1363 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1364 } 1365 1366 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1367 CallingConv::ID CC, 1368 EVT VT) const { 1369 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1370 // We might still end up using a GPR but that will be decided based on ABI. 1371 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1372 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1373 return MVT::f32; 1374 1375 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1376 } 1377 1378 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1379 CallingConv::ID CC, 1380 EVT VT) const { 1381 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1382 // We might still end up using a GPR but that will be decided based on ABI. 1383 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1384 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1385 return 1; 1386 1387 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1388 } 1389 1390 // Changes the condition code and swaps operands if necessary, so the SetCC 1391 // operation matches one of the comparisons supported directly by branches 1392 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1393 // with 1/-1. 1394 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1395 ISD::CondCode &CC, SelectionDAG &DAG) { 1396 // Convert X > -1 to X >= 0. 1397 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1398 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1399 CC = ISD::SETGE; 1400 return; 1401 } 1402 // Convert X < 1 to 0 >= X. 1403 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1404 RHS = LHS; 1405 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1406 CC = ISD::SETGE; 1407 return; 1408 } 1409 1410 switch (CC) { 1411 default: 1412 break; 1413 case ISD::SETGT: 1414 case ISD::SETLE: 1415 case ISD::SETUGT: 1416 case ISD::SETULE: 1417 CC = ISD::getSetCCSwappedOperands(CC); 1418 std::swap(LHS, RHS); 1419 break; 1420 } 1421 } 1422 1423 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1424 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1425 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1426 if (VT.getVectorElementType() == MVT::i1) 1427 KnownSize *= 8; 1428 1429 switch (KnownSize) { 1430 default: 1431 llvm_unreachable("Invalid LMUL."); 1432 case 8: 1433 return RISCVII::VLMUL::LMUL_F8; 1434 case 16: 1435 return RISCVII::VLMUL::LMUL_F4; 1436 case 32: 1437 return RISCVII::VLMUL::LMUL_F2; 1438 case 64: 1439 return RISCVII::VLMUL::LMUL_1; 1440 case 128: 1441 return RISCVII::VLMUL::LMUL_2; 1442 case 256: 1443 return RISCVII::VLMUL::LMUL_4; 1444 case 512: 1445 return RISCVII::VLMUL::LMUL_8; 1446 } 1447 } 1448 1449 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1450 switch (LMul) { 1451 default: 1452 llvm_unreachable("Invalid LMUL."); 1453 case RISCVII::VLMUL::LMUL_F8: 1454 case RISCVII::VLMUL::LMUL_F4: 1455 case RISCVII::VLMUL::LMUL_F2: 1456 case RISCVII::VLMUL::LMUL_1: 1457 return RISCV::VRRegClassID; 1458 case RISCVII::VLMUL::LMUL_2: 1459 return RISCV::VRM2RegClassID; 1460 case RISCVII::VLMUL::LMUL_4: 1461 return RISCV::VRM4RegClassID; 1462 case RISCVII::VLMUL::LMUL_8: 1463 return RISCV::VRM8RegClassID; 1464 } 1465 } 1466 1467 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1468 RISCVII::VLMUL LMUL = getLMUL(VT); 1469 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1470 LMUL == RISCVII::VLMUL::LMUL_F4 || 1471 LMUL == RISCVII::VLMUL::LMUL_F2 || 1472 LMUL == RISCVII::VLMUL::LMUL_1) { 1473 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1474 "Unexpected subreg numbering"); 1475 return RISCV::sub_vrm1_0 + Index; 1476 } 1477 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1478 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1479 "Unexpected subreg numbering"); 1480 return RISCV::sub_vrm2_0 + Index; 1481 } 1482 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1483 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1484 "Unexpected subreg numbering"); 1485 return RISCV::sub_vrm4_0 + Index; 1486 } 1487 llvm_unreachable("Invalid vector type."); 1488 } 1489 1490 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1491 if (VT.getVectorElementType() == MVT::i1) 1492 return RISCV::VRRegClassID; 1493 return getRegClassIDForLMUL(getLMUL(VT)); 1494 } 1495 1496 // Attempt to decompose a subvector insert/extract between VecVT and 1497 // SubVecVT via subregister indices. Returns the subregister index that 1498 // can perform the subvector insert/extract with the given element index, as 1499 // well as the index corresponding to any leftover subvectors that must be 1500 // further inserted/extracted within the register class for SubVecVT. 1501 std::pair<unsigned, unsigned> 1502 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1503 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1504 const RISCVRegisterInfo *TRI) { 1505 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1506 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1507 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1508 "Register classes not ordered"); 1509 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1510 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1511 // Try to compose a subregister index that takes us from the incoming 1512 // LMUL>1 register class down to the outgoing one. At each step we half 1513 // the LMUL: 1514 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1515 // Note that this is not guaranteed to find a subregister index, such as 1516 // when we are extracting from one VR type to another. 1517 unsigned SubRegIdx = RISCV::NoSubRegister; 1518 for (const unsigned RCID : 1519 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1520 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1521 VecVT = VecVT.getHalfNumVectorElementsVT(); 1522 bool IsHi = 1523 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1524 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1525 getSubregIndexByMVT(VecVT, IsHi)); 1526 if (IsHi) 1527 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1528 } 1529 return {SubRegIdx, InsertExtractIdx}; 1530 } 1531 1532 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1533 // stores for those types. 1534 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1535 return !Subtarget.useRVVForFixedLengthVectors() || 1536 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1537 } 1538 1539 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1540 if (ScalarTy->isPointerTy()) 1541 return true; 1542 1543 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1544 ScalarTy->isIntegerTy(32)) 1545 return true; 1546 1547 if (ScalarTy->isIntegerTy(64)) 1548 return Subtarget.hasVInstructionsI64(); 1549 1550 if (ScalarTy->isHalfTy()) 1551 return Subtarget.hasVInstructionsF16(); 1552 if (ScalarTy->isFloatTy()) 1553 return Subtarget.hasVInstructionsF32(); 1554 if (ScalarTy->isDoubleTy()) 1555 return Subtarget.hasVInstructionsF64(); 1556 1557 return false; 1558 } 1559 1560 static SDValue getVLOperand(SDValue Op) { 1561 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1562 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1563 "Unexpected opcode"); 1564 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1565 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1566 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1567 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1568 if (!II) 1569 return SDValue(); 1570 return Op.getOperand(II->VLOperand + 1 + HasChain); 1571 } 1572 1573 static bool useRVVForFixedLengthVectorVT(MVT VT, 1574 const RISCVSubtarget &Subtarget) { 1575 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1576 if (!Subtarget.useRVVForFixedLengthVectors()) 1577 return false; 1578 1579 // We only support a set of vector types with a consistent maximum fixed size 1580 // across all supported vector element types to avoid legalization issues. 1581 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1582 // fixed-length vector type we support is 1024 bytes. 1583 if (VT.getFixedSizeInBits() > 1024 * 8) 1584 return false; 1585 1586 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1587 1588 MVT EltVT = VT.getVectorElementType(); 1589 1590 // Don't use RVV for vectors we cannot scalarize if required. 1591 switch (EltVT.SimpleTy) { 1592 // i1 is supported but has different rules. 1593 default: 1594 return false; 1595 case MVT::i1: 1596 // Masks can only use a single register. 1597 if (VT.getVectorNumElements() > MinVLen) 1598 return false; 1599 MinVLen /= 8; 1600 break; 1601 case MVT::i8: 1602 case MVT::i16: 1603 case MVT::i32: 1604 break; 1605 case MVT::i64: 1606 if (!Subtarget.hasVInstructionsI64()) 1607 return false; 1608 break; 1609 case MVT::f16: 1610 if (!Subtarget.hasVInstructionsF16()) 1611 return false; 1612 break; 1613 case MVT::f32: 1614 if (!Subtarget.hasVInstructionsF32()) 1615 return false; 1616 break; 1617 case MVT::f64: 1618 if (!Subtarget.hasVInstructionsF64()) 1619 return false; 1620 break; 1621 } 1622 1623 // Reject elements larger than ELEN. 1624 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1625 return false; 1626 1627 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1628 // Don't use RVV for types that don't fit. 1629 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1630 return false; 1631 1632 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1633 // the base fixed length RVV support in place. 1634 if (!VT.isPow2VectorType()) 1635 return false; 1636 1637 return true; 1638 } 1639 1640 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1641 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1642 } 1643 1644 // Return the largest legal scalable vector type that matches VT's element type. 1645 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1646 const RISCVSubtarget &Subtarget) { 1647 // This may be called before legal types are setup. 1648 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1649 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1650 "Expected legal fixed length vector!"); 1651 1652 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1653 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1654 1655 MVT EltVT = VT.getVectorElementType(); 1656 switch (EltVT.SimpleTy) { 1657 default: 1658 llvm_unreachable("unexpected element type for RVV container"); 1659 case MVT::i1: 1660 case MVT::i8: 1661 case MVT::i16: 1662 case MVT::i32: 1663 case MVT::i64: 1664 case MVT::f16: 1665 case MVT::f32: 1666 case MVT::f64: { 1667 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1668 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1669 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1670 unsigned NumElts = 1671 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1672 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1673 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1674 return MVT::getScalableVectorVT(EltVT, NumElts); 1675 } 1676 } 1677 } 1678 1679 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1680 const RISCVSubtarget &Subtarget) { 1681 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1682 Subtarget); 1683 } 1684 1685 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1686 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1687 } 1688 1689 // Grow V to consume an entire RVV register. 1690 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1691 const RISCVSubtarget &Subtarget) { 1692 assert(VT.isScalableVector() && 1693 "Expected to convert into a scalable vector!"); 1694 assert(V.getValueType().isFixedLengthVector() && 1695 "Expected a fixed length vector operand!"); 1696 SDLoc DL(V); 1697 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1698 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1699 } 1700 1701 // Shrink V so it's just big enough to maintain a VT's worth of data. 1702 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1703 const RISCVSubtarget &Subtarget) { 1704 assert(VT.isFixedLengthVector() && 1705 "Expected to convert into a fixed length vector!"); 1706 assert(V.getValueType().isScalableVector() && 1707 "Expected a scalable vector operand!"); 1708 SDLoc DL(V); 1709 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1710 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1711 } 1712 1713 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1714 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1715 // the vector type that it is contained in. 1716 static std::pair<SDValue, SDValue> 1717 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1718 const RISCVSubtarget &Subtarget) { 1719 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1720 MVT XLenVT = Subtarget.getXLenVT(); 1721 SDValue VL = VecVT.isFixedLengthVector() 1722 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1723 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1724 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1725 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1726 return {Mask, VL}; 1727 } 1728 1729 // As above but assuming the given type is a scalable vector type. 1730 static std::pair<SDValue, SDValue> 1731 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1732 const RISCVSubtarget &Subtarget) { 1733 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1734 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1735 } 1736 1737 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1738 // of either is (currently) supported. This can get us into an infinite loop 1739 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1740 // as a ..., etc. 1741 // Until either (or both) of these can reliably lower any node, reporting that 1742 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1743 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1744 // which is not desirable. 1745 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1746 EVT VT, unsigned DefinedValues) const { 1747 return false; 1748 } 1749 1750 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1751 // Only splats are currently supported. 1752 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1753 return true; 1754 1755 return false; 1756 } 1757 1758 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1759 const RISCVSubtarget &Subtarget) { 1760 // RISCV FP-to-int conversions saturate to the destination register size, but 1761 // don't produce 0 for nan. We can use a conversion instruction and fix the 1762 // nan case with a compare and a select. 1763 SDValue Src = Op.getOperand(0); 1764 1765 EVT DstVT = Op.getValueType(); 1766 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1767 1768 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1769 unsigned Opc; 1770 if (SatVT == DstVT) 1771 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1772 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1773 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1774 else 1775 return SDValue(); 1776 // FIXME: Support other SatVTs by clamping before or after the conversion. 1777 1778 SDLoc DL(Op); 1779 SDValue FpToInt = DAG.getNode( 1780 Opc, DL, DstVT, Src, 1781 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1782 1783 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1784 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1785 } 1786 1787 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1788 // and back. Taking care to avoid converting values that are nan or already 1789 // correct. 1790 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1791 // have FRM dependencies modeled yet. 1792 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1793 MVT VT = Op.getSimpleValueType(); 1794 assert(VT.isVector() && "Unexpected type"); 1795 1796 SDLoc DL(Op); 1797 1798 // Freeze the source since we are increasing the number of uses. 1799 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1800 1801 // Truncate to integer and convert back to FP. 1802 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1803 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1804 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1805 1806 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1807 1808 if (Op.getOpcode() == ISD::FCEIL) { 1809 // If the truncated value is the greater than or equal to the original 1810 // value, we've computed the ceil. Otherwise, we went the wrong way and 1811 // need to increase by 1. 1812 // FIXME: This should use a masked operation. Handle here or in isel? 1813 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1814 DAG.getConstantFP(1.0, DL, VT)); 1815 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1816 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1817 } else if (Op.getOpcode() == ISD::FFLOOR) { 1818 // If the truncated value is the less than or equal to the original value, 1819 // we've computed the floor. Otherwise, we went the wrong way and need to 1820 // decrease by 1. 1821 // FIXME: This should use a masked operation. Handle here or in isel? 1822 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1823 DAG.getConstantFP(1.0, DL, VT)); 1824 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1825 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1826 } 1827 1828 // Restore the original sign so that -0.0 is preserved. 1829 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1830 1831 // Determine the largest integer that can be represented exactly. This and 1832 // values larger than it don't have any fractional bits so don't need to 1833 // be converted. 1834 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1835 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1836 APFloat MaxVal = APFloat(FltSem); 1837 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1838 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1839 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1840 1841 // If abs(Src) was larger than MaxVal or nan, keep it. 1842 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1843 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1844 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1845 } 1846 1847 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1848 const RISCVSubtarget &Subtarget) { 1849 MVT VT = Op.getSimpleValueType(); 1850 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1851 1852 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1853 1854 SDLoc DL(Op); 1855 SDValue Mask, VL; 1856 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1857 1858 unsigned Opc = 1859 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1860 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1861 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1862 } 1863 1864 struct VIDSequence { 1865 int64_t StepNumerator; 1866 unsigned StepDenominator; 1867 int64_t Addend; 1868 }; 1869 1870 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1871 // to the (non-zero) step S and start value X. This can be then lowered as the 1872 // RVV sequence (VID * S) + X, for example. 1873 // The step S is represented as an integer numerator divided by a positive 1874 // denominator. Note that the implementation currently only identifies 1875 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1876 // cannot detect 2/3, for example. 1877 // Note that this method will also match potentially unappealing index 1878 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1879 // determine whether this is worth generating code for. 1880 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1881 unsigned NumElts = Op.getNumOperands(); 1882 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1883 if (!Op.getValueType().isInteger()) 1884 return None; 1885 1886 Optional<unsigned> SeqStepDenom; 1887 Optional<int64_t> SeqStepNum, SeqAddend; 1888 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1889 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1890 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1891 // Assume undef elements match the sequence; we just have to be careful 1892 // when interpolating across them. 1893 if (Op.getOperand(Idx).isUndef()) 1894 continue; 1895 // The BUILD_VECTOR must be all constants. 1896 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1897 return None; 1898 1899 uint64_t Val = Op.getConstantOperandVal(Idx) & 1900 maskTrailingOnes<uint64_t>(EltSizeInBits); 1901 1902 if (PrevElt) { 1903 // Calculate the step since the last non-undef element, and ensure 1904 // it's consistent across the entire sequence. 1905 unsigned IdxDiff = Idx - PrevElt->second; 1906 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1907 1908 // A zero-value value difference means that we're somewhere in the middle 1909 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1910 // step change before evaluating the sequence. 1911 if (ValDiff != 0) { 1912 int64_t Remainder = ValDiff % IdxDiff; 1913 // Normalize the step if it's greater than 1. 1914 if (Remainder != ValDiff) { 1915 // The difference must cleanly divide the element span. 1916 if (Remainder != 0) 1917 return None; 1918 ValDiff /= IdxDiff; 1919 IdxDiff = 1; 1920 } 1921 1922 if (!SeqStepNum) 1923 SeqStepNum = ValDiff; 1924 else if (ValDiff != SeqStepNum) 1925 return None; 1926 1927 if (!SeqStepDenom) 1928 SeqStepDenom = IdxDiff; 1929 else if (IdxDiff != *SeqStepDenom) 1930 return None; 1931 } 1932 } 1933 1934 // Record and/or check any addend. 1935 if (SeqStepNum && SeqStepDenom) { 1936 uint64_t ExpectedVal = 1937 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1938 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1939 if (!SeqAddend) 1940 SeqAddend = Addend; 1941 else if (SeqAddend != Addend) 1942 return None; 1943 } 1944 1945 // Record this non-undef element for later. 1946 if (!PrevElt || PrevElt->first != Val) 1947 PrevElt = std::make_pair(Val, Idx); 1948 } 1949 // We need to have logged both a step and an addend for this to count as 1950 // a legal index sequence. 1951 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1952 return None; 1953 1954 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1955 } 1956 1957 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1958 const RISCVSubtarget &Subtarget) { 1959 MVT VT = Op.getSimpleValueType(); 1960 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1961 1962 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1963 1964 SDLoc DL(Op); 1965 SDValue Mask, VL; 1966 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1967 1968 MVT XLenVT = Subtarget.getXLenVT(); 1969 unsigned NumElts = Op.getNumOperands(); 1970 1971 if (VT.getVectorElementType() == MVT::i1) { 1972 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1973 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1974 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1975 } 1976 1977 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1978 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1979 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1980 } 1981 1982 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1983 // scalar integer chunks whose bit-width depends on the number of mask 1984 // bits and XLEN. 1985 // First, determine the most appropriate scalar integer type to use. This 1986 // is at most XLenVT, but may be shrunk to a smaller vector element type 1987 // according to the size of the final vector - use i8 chunks rather than 1988 // XLenVT if we're producing a v8i1. This results in more consistent 1989 // codegen across RV32 and RV64. 1990 unsigned NumViaIntegerBits = 1991 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1992 NumViaIntegerBits = std::min(NumViaIntegerBits, 1993 Subtarget.getMaxELENForFixedLengthVectors()); 1994 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1995 // If we have to use more than one INSERT_VECTOR_ELT then this 1996 // optimization is likely to increase code size; avoid peforming it in 1997 // such a case. We can use a load from a constant pool in this case. 1998 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1999 return SDValue(); 2000 // Now we can create our integer vector type. Note that it may be larger 2001 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2002 MVT IntegerViaVecVT = 2003 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2004 divideCeil(NumElts, NumViaIntegerBits)); 2005 2006 uint64_t Bits = 0; 2007 unsigned BitPos = 0, IntegerEltIdx = 0; 2008 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2009 2010 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2011 // Once we accumulate enough bits to fill our scalar type, insert into 2012 // our vector and clear our accumulated data. 2013 if (I != 0 && I % NumViaIntegerBits == 0) { 2014 if (NumViaIntegerBits <= 32) 2015 Bits = SignExtend64(Bits, 32); 2016 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2017 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2018 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2019 Bits = 0; 2020 BitPos = 0; 2021 IntegerEltIdx++; 2022 } 2023 SDValue V = Op.getOperand(I); 2024 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2025 Bits |= ((uint64_t)BitValue << BitPos); 2026 } 2027 2028 // Insert the (remaining) scalar value into position in our integer 2029 // vector type. 2030 if (NumViaIntegerBits <= 32) 2031 Bits = SignExtend64(Bits, 32); 2032 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2033 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2034 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2035 2036 if (NumElts < NumViaIntegerBits) { 2037 // If we're producing a smaller vector than our minimum legal integer 2038 // type, bitcast to the equivalent (known-legal) mask type, and extract 2039 // our final mask. 2040 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2041 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2042 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2043 DAG.getConstant(0, DL, XLenVT)); 2044 } else { 2045 // Else we must have produced an integer type with the same size as the 2046 // mask type; bitcast for the final result. 2047 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2048 Vec = DAG.getBitcast(VT, Vec); 2049 } 2050 2051 return Vec; 2052 } 2053 2054 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2055 // vector type, we have a legal equivalently-sized i8 type, so we can use 2056 // that. 2057 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2058 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2059 2060 SDValue WideVec; 2061 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2062 // For a splat, perform a scalar truncate before creating the wider 2063 // vector. 2064 assert(Splat.getValueType() == XLenVT && 2065 "Unexpected type for i1 splat value"); 2066 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2067 DAG.getConstant(1, DL, XLenVT)); 2068 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2069 } else { 2070 SmallVector<SDValue, 8> Ops(Op->op_values()); 2071 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2072 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2073 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2074 } 2075 2076 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2077 } 2078 2079 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2080 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2081 : RISCVISD::VMV_V_X_VL; 2082 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2083 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2084 } 2085 2086 // Try and match index sequences, which we can lower to the vid instruction 2087 // with optional modifications. An all-undef vector is matched by 2088 // getSplatValue, above. 2089 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2090 int64_t StepNumerator = SimpleVID->StepNumerator; 2091 unsigned StepDenominator = SimpleVID->StepDenominator; 2092 int64_t Addend = SimpleVID->Addend; 2093 2094 assert(StepNumerator != 0 && "Invalid step"); 2095 bool Negate = false; 2096 int64_t SplatStepVal = StepNumerator; 2097 unsigned StepOpcode = ISD::MUL; 2098 if (StepNumerator != 1) { 2099 if (isPowerOf2_64(std::abs(StepNumerator))) { 2100 Negate = StepNumerator < 0; 2101 StepOpcode = ISD::SHL; 2102 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2103 } 2104 } 2105 2106 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2107 // threshold since it's the immediate value many RVV instructions accept. 2108 // There is no vmul.vi instruction so ensure multiply constant can fit in 2109 // a single addi instruction. 2110 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2111 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2112 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2113 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2114 // Convert right out of the scalable type so we can use standard ISD 2115 // nodes for the rest of the computation. If we used scalable types with 2116 // these, we'd lose the fixed-length vector info and generate worse 2117 // vsetvli code. 2118 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2119 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2120 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2121 SDValue SplatStep = DAG.getSplatVector( 2122 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2123 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2124 } 2125 if (StepDenominator != 1) { 2126 SDValue SplatStep = DAG.getSplatVector( 2127 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2128 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2129 } 2130 if (Addend != 0 || Negate) { 2131 SDValue SplatAddend = 2132 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2133 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2134 } 2135 return VID; 2136 } 2137 } 2138 2139 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2140 // when re-interpreted as a vector with a larger element type. For example, 2141 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2142 // could be instead splat as 2143 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2144 // TODO: This optimization could also work on non-constant splats, but it 2145 // would require bit-manipulation instructions to construct the splat value. 2146 SmallVector<SDValue> Sequence; 2147 unsigned EltBitSize = VT.getScalarSizeInBits(); 2148 const auto *BV = cast<BuildVectorSDNode>(Op); 2149 if (VT.isInteger() && EltBitSize < 64 && 2150 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2151 BV->getRepeatedSequence(Sequence) && 2152 (Sequence.size() * EltBitSize) <= 64) { 2153 unsigned SeqLen = Sequence.size(); 2154 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2155 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2156 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2157 ViaIntVT == MVT::i64) && 2158 "Unexpected sequence type"); 2159 2160 unsigned EltIdx = 0; 2161 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2162 uint64_t SplatValue = 0; 2163 // Construct the amalgamated value which can be splatted as this larger 2164 // vector type. 2165 for (const auto &SeqV : Sequence) { 2166 if (!SeqV.isUndef()) 2167 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2168 << (EltIdx * EltBitSize)); 2169 EltIdx++; 2170 } 2171 2172 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2173 // achieve better constant materializion. 2174 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2175 SplatValue = SignExtend64(SplatValue, 32); 2176 2177 // Since we can't introduce illegal i64 types at this stage, we can only 2178 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2179 // way we can use RVV instructions to splat. 2180 assert((ViaIntVT.bitsLE(XLenVT) || 2181 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2182 "Unexpected bitcast sequence"); 2183 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2184 SDValue ViaVL = 2185 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2186 MVT ViaContainerVT = 2187 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2188 SDValue Splat = 2189 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2190 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2191 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2192 return DAG.getBitcast(VT, Splat); 2193 } 2194 } 2195 2196 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2197 // which constitute a large proportion of the elements. In such cases we can 2198 // splat a vector with the dominant element and make up the shortfall with 2199 // INSERT_VECTOR_ELTs. 2200 // Note that this includes vectors of 2 elements by association. The 2201 // upper-most element is the "dominant" one, allowing us to use a splat to 2202 // "insert" the upper element, and an insert of the lower element at position 2203 // 0, which improves codegen. 2204 SDValue DominantValue; 2205 unsigned MostCommonCount = 0; 2206 DenseMap<SDValue, unsigned> ValueCounts; 2207 unsigned NumUndefElts = 2208 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2209 2210 // Track the number of scalar loads we know we'd be inserting, estimated as 2211 // any non-zero floating-point constant. Other kinds of element are either 2212 // already in registers or are materialized on demand. The threshold at which 2213 // a vector load is more desirable than several scalar materializion and 2214 // vector-insertion instructions is not known. 2215 unsigned NumScalarLoads = 0; 2216 2217 for (SDValue V : Op->op_values()) { 2218 if (V.isUndef()) 2219 continue; 2220 2221 ValueCounts.insert(std::make_pair(V, 0)); 2222 unsigned &Count = ValueCounts[V]; 2223 2224 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2225 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2226 2227 // Is this value dominant? In case of a tie, prefer the highest element as 2228 // it's cheaper to insert near the beginning of a vector than it is at the 2229 // end. 2230 if (++Count >= MostCommonCount) { 2231 DominantValue = V; 2232 MostCommonCount = Count; 2233 } 2234 } 2235 2236 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2237 unsigned NumDefElts = NumElts - NumUndefElts; 2238 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2239 2240 // Don't perform this optimization when optimizing for size, since 2241 // materializing elements and inserting them tends to cause code bloat. 2242 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2243 ((MostCommonCount > DominantValueCountThreshold) || 2244 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2245 // Start by splatting the most common element. 2246 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2247 2248 DenseSet<SDValue> Processed{DominantValue}; 2249 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2250 for (const auto &OpIdx : enumerate(Op->ops())) { 2251 const SDValue &V = OpIdx.value(); 2252 if (V.isUndef() || !Processed.insert(V).second) 2253 continue; 2254 if (ValueCounts[V] == 1) { 2255 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2256 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2257 } else { 2258 // Blend in all instances of this value using a VSELECT, using a 2259 // mask where each bit signals whether that element is the one 2260 // we're after. 2261 SmallVector<SDValue> Ops; 2262 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2263 return DAG.getConstant(V == V1, DL, XLenVT); 2264 }); 2265 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2266 DAG.getBuildVector(SelMaskTy, DL, Ops), 2267 DAG.getSplatBuildVector(VT, DL, V), Vec); 2268 } 2269 } 2270 2271 return Vec; 2272 } 2273 2274 return SDValue(); 2275 } 2276 2277 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2278 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2279 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2280 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2281 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2282 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2283 // node in order to try and match RVV vector/scalar instructions. 2284 if ((LoC >> 31) == HiC) 2285 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2286 2287 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2288 // vmv.v.x whose EEW = 32 to lower it. 2289 auto *Const = dyn_cast<ConstantSDNode>(VL); 2290 if (LoC == HiC && Const && Const->isAllOnesValue() && 2291 Const->getOpcode() != ISD::TargetConstant) { 2292 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2293 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2294 // access the subtarget here now. 2295 auto InterVec = DAG.getNode( 2296 RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, 2297 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32)); 2298 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2299 } 2300 } 2301 2302 // Fall back to a stack store and stride x0 vector load. 2303 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2304 } 2305 2306 // Called by type legalization to handle splat of i64 on RV32. 2307 // FIXME: We can optimize this when the type has sign or zero bits in one 2308 // of the halves. 2309 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2310 SDValue VL, SelectionDAG &DAG) { 2311 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2312 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2313 DAG.getConstant(0, DL, MVT::i32)); 2314 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2315 DAG.getConstant(1, DL, MVT::i32)); 2316 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2317 } 2318 2319 // This function lowers a splat of a scalar operand Splat with the vector 2320 // length VL. It ensures the final sequence is type legal, which is useful when 2321 // lowering a splat after type legalization. 2322 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2323 SelectionDAG &DAG, 2324 const RISCVSubtarget &Subtarget) { 2325 if (VT.isFloatingPoint()) { 2326 // If VL is 1, we could use vfmv.s.f. 2327 if (isOneConstant(VL)) 2328 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2329 Scalar, VL); 2330 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2331 } 2332 2333 MVT XLenVT = Subtarget.getXLenVT(); 2334 2335 // Simplest case is that the operand needs to be promoted to XLenVT. 2336 if (Scalar.getValueType().bitsLE(XLenVT)) { 2337 // If the operand is a constant, sign extend to increase our chances 2338 // of being able to use a .vi instruction. ANY_EXTEND would become a 2339 // a zero extend and the simm5 check in isel would fail. 2340 // FIXME: Should we ignore the upper bits in isel instead? 2341 unsigned ExtOpc = 2342 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2343 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2344 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2345 // If VL is 1 and the scalar value won't benefit from immediate, we could 2346 // use vmv.s.x. 2347 if (isOneConstant(VL) && 2348 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2349 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2350 VL); 2351 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2352 } 2353 2354 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2355 "Unexpected scalar for splat lowering!"); 2356 2357 if (isOneConstant(VL) && isNullConstant(Scalar)) 2358 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2359 DAG.getConstant(0, DL, XLenVT), VL); 2360 2361 // Otherwise use the more complicated splatting algorithm. 2362 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2363 } 2364 2365 // Is the mask a slidedown that shifts in undefs. 2366 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) { 2367 int Size = Mask.size(); 2368 2369 // Elements shifted in should be undef. 2370 auto CheckUndefs = [&](int Shift) { 2371 for (int i = Size - Shift; i != Size; ++i) 2372 if (Mask[i] >= 0) 2373 return false; 2374 return true; 2375 }; 2376 2377 // Elements should be shifted or undef. 2378 auto MatchShift = [&](int Shift) { 2379 for (int i = 0; i != Size - Shift; ++i) 2380 if (Mask[i] >= 0 && Mask[i] != Shift + i) 2381 return false; 2382 return true; 2383 }; 2384 2385 // Try all possible shifts. 2386 for (int Shift = 1; Shift != Size; ++Shift) 2387 if (CheckUndefs(Shift) && MatchShift(Shift)) 2388 return Shift; 2389 2390 // No match. 2391 return -1; 2392 } 2393 2394 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2395 const RISCVSubtarget &Subtarget) { 2396 // We need to be able to widen elements to the next larger integer type. 2397 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2398 return false; 2399 2400 int Size = Mask.size(); 2401 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2402 2403 int Srcs[] = {-1, -1}; 2404 for (int i = 0; i != Size; ++i) { 2405 // Ignore undef elements. 2406 if (Mask[i] < 0) 2407 continue; 2408 2409 // Is this an even or odd element. 2410 int Pol = i % 2; 2411 2412 // Ensure we consistently use the same source for this element polarity. 2413 int Src = Mask[i] / Size; 2414 if (Srcs[Pol] < 0) 2415 Srcs[Pol] = Src; 2416 if (Srcs[Pol] != Src) 2417 return false; 2418 2419 // Make sure the element within the source is appropriate for this element 2420 // in the destination. 2421 int Elt = Mask[i] % Size; 2422 if (Elt != i / 2) 2423 return false; 2424 } 2425 2426 // We need to find a source for each polarity and they can't be the same. 2427 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2428 return false; 2429 2430 // Swap the sources if the second source was in the even polarity. 2431 SwapSources = Srcs[0] > Srcs[1]; 2432 2433 return true; 2434 } 2435 2436 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2437 const RISCVSubtarget &Subtarget) { 2438 SDValue V1 = Op.getOperand(0); 2439 SDValue V2 = Op.getOperand(1); 2440 SDLoc DL(Op); 2441 MVT XLenVT = Subtarget.getXLenVT(); 2442 MVT VT = Op.getSimpleValueType(); 2443 unsigned NumElts = VT.getVectorNumElements(); 2444 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2445 2446 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2447 2448 SDValue TrueMask, VL; 2449 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2450 2451 if (SVN->isSplat()) { 2452 const int Lane = SVN->getSplatIndex(); 2453 if (Lane >= 0) { 2454 MVT SVT = VT.getVectorElementType(); 2455 2456 // Turn splatted vector load into a strided load with an X0 stride. 2457 SDValue V = V1; 2458 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2459 // with undef. 2460 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2461 int Offset = Lane; 2462 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2463 int OpElements = 2464 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2465 V = V.getOperand(Offset / OpElements); 2466 Offset %= OpElements; 2467 } 2468 2469 // We need to ensure the load isn't atomic or volatile. 2470 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2471 auto *Ld = cast<LoadSDNode>(V); 2472 Offset *= SVT.getStoreSize(); 2473 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2474 TypeSize::Fixed(Offset), DL); 2475 2476 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2477 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2478 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2479 SDValue IntID = 2480 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2481 SDValue Ops[] = {Ld->getChain(), 2482 IntID, 2483 DAG.getUNDEF(ContainerVT), 2484 NewAddr, 2485 DAG.getRegister(RISCV::X0, XLenVT), 2486 VL}; 2487 SDValue NewLoad = DAG.getMemIntrinsicNode( 2488 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2489 DAG.getMachineFunction().getMachineMemOperand( 2490 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2491 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2492 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2493 } 2494 2495 // Otherwise use a scalar load and splat. This will give the best 2496 // opportunity to fold a splat into the operation. ISel can turn it into 2497 // the x0 strided load if we aren't able to fold away the select. 2498 if (SVT.isFloatingPoint()) 2499 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2500 Ld->getPointerInfo().getWithOffset(Offset), 2501 Ld->getOriginalAlign(), 2502 Ld->getMemOperand()->getFlags()); 2503 else 2504 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2505 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2506 Ld->getOriginalAlign(), 2507 Ld->getMemOperand()->getFlags()); 2508 DAG.makeEquivalentMemoryOrdering(Ld, V); 2509 2510 unsigned Opc = 2511 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2512 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2513 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2514 } 2515 2516 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2517 assert(Lane < (int)NumElts && "Unexpected lane!"); 2518 SDValue Gather = 2519 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2520 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2521 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2522 } 2523 } 2524 2525 ArrayRef<int> Mask = SVN->getMask(); 2526 2527 // Try to match as a slidedown. 2528 int SlideAmt = matchShuffleAsSlideDown(Mask); 2529 if (SlideAmt >= 0) { 2530 // TODO: Should we reduce the VL to account for the upper undef elements? 2531 // Requires additional vsetvlis, but might be faster to execute. 2532 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2533 SDValue SlideDown = 2534 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2535 DAG.getUNDEF(ContainerVT), V1, 2536 DAG.getConstant(SlideAmt, DL, XLenVT), 2537 TrueMask, VL); 2538 return convertFromScalableVector(VT, SlideDown, DAG, Subtarget); 2539 } 2540 2541 // Detect an interleave shuffle and lower to 2542 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2543 bool SwapSources; 2544 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2545 // Swap sources if needed. 2546 if (SwapSources) 2547 std::swap(V1, V2); 2548 2549 // Extract the lower half of the vectors. 2550 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2551 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2552 DAG.getConstant(0, DL, XLenVT)); 2553 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2554 DAG.getConstant(0, DL, XLenVT)); 2555 2556 // Double the element width and halve the number of elements in an int type. 2557 unsigned EltBits = VT.getScalarSizeInBits(); 2558 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2559 MVT WideIntVT = 2560 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2561 // Convert this to a scalable vector. We need to base this on the 2562 // destination size to ensure there's always a type with a smaller LMUL. 2563 MVT WideIntContainerVT = 2564 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2565 2566 // Convert sources to scalable vectors with the same element count as the 2567 // larger type. 2568 MVT HalfContainerVT = MVT::getVectorVT( 2569 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2570 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2571 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2572 2573 // Cast sources to integer. 2574 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2575 MVT IntHalfVT = 2576 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2577 V1 = DAG.getBitcast(IntHalfVT, V1); 2578 V2 = DAG.getBitcast(IntHalfVT, V2); 2579 2580 // Freeze V2 since we use it twice and we need to be sure that the add and 2581 // multiply see the same value. 2582 V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2); 2583 2584 // Recreate TrueMask using the widened type's element count. 2585 MVT MaskVT = 2586 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2587 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2588 2589 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2590 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2591 V2, TrueMask, VL); 2592 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2593 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2594 DAG.getAllOnesConstant(DL, XLenVT)); 2595 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2596 V2, Multiplier, TrueMask, VL); 2597 // Add the new copies to our previous addition giving us 2^eltbits copies of 2598 // V2. This is equivalent to shifting V2 left by eltbits. This should 2599 // combine with the vwmulu.vv above to form vwmaccu.vv. 2600 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2601 TrueMask, VL); 2602 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2603 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2604 // vector VT. 2605 ContainerVT = 2606 MVT::getVectorVT(VT.getVectorElementType(), 2607 WideIntContainerVT.getVectorElementCount() * 2); 2608 Add = DAG.getBitcast(ContainerVT, Add); 2609 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2610 } 2611 2612 // Detect shuffles which can be re-expressed as vector selects; these are 2613 // shuffles in which each element in the destination is taken from an element 2614 // at the corresponding index in either source vectors. 2615 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2616 int MaskIndex = MaskIdx.value(); 2617 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2618 }); 2619 2620 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2621 2622 SmallVector<SDValue> MaskVals; 2623 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2624 // merged with a second vrgather. 2625 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2626 2627 // By default we preserve the original operand order, and use a mask to 2628 // select LHS as true and RHS as false. However, since RVV vector selects may 2629 // feature splats but only on the LHS, we may choose to invert our mask and 2630 // instead select between RHS and LHS. 2631 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2632 bool InvertMask = IsSelect == SwapOps; 2633 2634 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2635 // half. 2636 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2637 2638 // Now construct the mask that will be used by the vselect or blended 2639 // vrgather operation. For vrgathers, construct the appropriate indices into 2640 // each vector. 2641 for (int MaskIndex : Mask) { 2642 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2643 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2644 if (!IsSelect) { 2645 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2646 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2647 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2648 : DAG.getUNDEF(XLenVT)); 2649 GatherIndicesRHS.push_back( 2650 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2651 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2652 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2653 ++LHSIndexCounts[MaskIndex]; 2654 if (!IsLHSOrUndefIndex) 2655 ++RHSIndexCounts[MaskIndex - NumElts]; 2656 } 2657 } 2658 2659 if (SwapOps) { 2660 std::swap(V1, V2); 2661 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2662 } 2663 2664 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2665 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2666 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2667 2668 if (IsSelect) 2669 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2670 2671 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2672 // On such a large vector we're unable to use i8 as the index type. 2673 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2674 // may involve vector splitting if we're already at LMUL=8, or our 2675 // user-supplied maximum fixed-length LMUL. 2676 return SDValue(); 2677 } 2678 2679 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2680 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2681 MVT IndexVT = VT.changeTypeToInteger(); 2682 // Since we can't introduce illegal index types at this stage, use i16 and 2683 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2684 // than XLenVT. 2685 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2686 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2687 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2688 } 2689 2690 MVT IndexContainerVT = 2691 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2692 2693 SDValue Gather; 2694 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2695 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2696 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2697 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2698 } else { 2699 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2700 // If only one index is used, we can use a "splat" vrgather. 2701 // TODO: We can splat the most-common index and fix-up any stragglers, if 2702 // that's beneficial. 2703 if (LHSIndexCounts.size() == 1) { 2704 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2705 Gather = 2706 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2707 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2708 } else { 2709 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2710 LHSIndices = 2711 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2712 2713 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2714 TrueMask, VL); 2715 } 2716 } 2717 2718 // If a second vector operand is used by this shuffle, blend it in with an 2719 // additional vrgather. 2720 if (!V2.isUndef()) { 2721 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2722 // If only one index is used, we can use a "splat" vrgather. 2723 // TODO: We can splat the most-common index and fix-up any stragglers, if 2724 // that's beneficial. 2725 if (RHSIndexCounts.size() == 1) { 2726 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2727 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2728 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2729 } else { 2730 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2731 RHSIndices = 2732 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2733 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2734 VL); 2735 } 2736 2737 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2738 SelectMask = 2739 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2740 2741 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2742 Gather, VL); 2743 } 2744 2745 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2746 } 2747 2748 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2749 SDLoc DL, SelectionDAG &DAG, 2750 const RISCVSubtarget &Subtarget) { 2751 if (VT.isScalableVector()) 2752 return DAG.getFPExtendOrRound(Op, DL, VT); 2753 assert(VT.isFixedLengthVector() && 2754 "Unexpected value type for RVV FP extend/round lowering"); 2755 SDValue Mask, VL; 2756 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2757 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2758 ? RISCVISD::FP_EXTEND_VL 2759 : RISCVISD::FP_ROUND_VL; 2760 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2761 } 2762 2763 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2764 // the exponent. 2765 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2766 MVT VT = Op.getSimpleValueType(); 2767 unsigned EltSize = VT.getScalarSizeInBits(); 2768 SDValue Src = Op.getOperand(0); 2769 SDLoc DL(Op); 2770 2771 // We need a FP type that can represent the value. 2772 // TODO: Use f16 for i8 when possible? 2773 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2774 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2775 2776 // Legal types should have been checked in the RISCVTargetLowering 2777 // constructor. 2778 // TODO: Splitting may make sense in some cases. 2779 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2780 "Expected legal float type!"); 2781 2782 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2783 // The trailing zero count is equal to log2 of this single bit value. 2784 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2785 SDValue Neg = 2786 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2787 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2788 } 2789 2790 // We have a legal FP type, convert to it. 2791 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2792 // Bitcast to integer and shift the exponent to the LSB. 2793 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2794 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2795 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2796 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2797 DAG.getConstant(ShiftAmt, DL, IntVT)); 2798 // Truncate back to original type to allow vnsrl. 2799 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2800 // The exponent contains log2 of the value in biased form. 2801 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2802 2803 // For trailing zeros, we just need to subtract the bias. 2804 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2805 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2806 DAG.getConstant(ExponentBias, DL, VT)); 2807 2808 // For leading zeros, we need to remove the bias and convert from log2 to 2809 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2810 unsigned Adjust = ExponentBias + (EltSize - 1); 2811 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2812 } 2813 2814 // While RVV has alignment restrictions, we should always be able to load as a 2815 // legal equivalently-sized byte-typed vector instead. This method is 2816 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2817 // the load is already correctly-aligned, it returns SDValue(). 2818 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2819 SelectionDAG &DAG) const { 2820 auto *Load = cast<LoadSDNode>(Op); 2821 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2822 2823 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2824 Load->getMemoryVT(), 2825 *Load->getMemOperand())) 2826 return SDValue(); 2827 2828 SDLoc DL(Op); 2829 MVT VT = Op.getSimpleValueType(); 2830 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2831 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2832 "Unexpected unaligned RVV load type"); 2833 MVT NewVT = 2834 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2835 assert(NewVT.isValid() && 2836 "Expecting equally-sized RVV vector types to be legal"); 2837 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2838 Load->getPointerInfo(), Load->getOriginalAlign(), 2839 Load->getMemOperand()->getFlags()); 2840 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2841 } 2842 2843 // While RVV has alignment restrictions, we should always be able to store as a 2844 // legal equivalently-sized byte-typed vector instead. This method is 2845 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2846 // returns SDValue() if the store is already correctly aligned. 2847 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2848 SelectionDAG &DAG) const { 2849 auto *Store = cast<StoreSDNode>(Op); 2850 assert(Store && Store->getValue().getValueType().isVector() && 2851 "Expected vector store"); 2852 2853 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2854 Store->getMemoryVT(), 2855 *Store->getMemOperand())) 2856 return SDValue(); 2857 2858 SDLoc DL(Op); 2859 SDValue StoredVal = Store->getValue(); 2860 MVT VT = StoredVal.getSimpleValueType(); 2861 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2862 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2863 "Unexpected unaligned RVV store type"); 2864 MVT NewVT = 2865 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2866 assert(NewVT.isValid() && 2867 "Expecting equally-sized RVV vector types to be legal"); 2868 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2869 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2870 Store->getPointerInfo(), Store->getOriginalAlign(), 2871 Store->getMemOperand()->getFlags()); 2872 } 2873 2874 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2875 SelectionDAG &DAG) const { 2876 switch (Op.getOpcode()) { 2877 default: 2878 report_fatal_error("unimplemented operand"); 2879 case ISD::GlobalAddress: 2880 return lowerGlobalAddress(Op, DAG); 2881 case ISD::BlockAddress: 2882 return lowerBlockAddress(Op, DAG); 2883 case ISD::ConstantPool: 2884 return lowerConstantPool(Op, DAG); 2885 case ISD::JumpTable: 2886 return lowerJumpTable(Op, DAG); 2887 case ISD::GlobalTLSAddress: 2888 return lowerGlobalTLSAddress(Op, DAG); 2889 case ISD::SELECT: 2890 return lowerSELECT(Op, DAG); 2891 case ISD::BRCOND: 2892 return lowerBRCOND(Op, DAG); 2893 case ISD::VASTART: 2894 return lowerVASTART(Op, DAG); 2895 case ISD::FRAMEADDR: 2896 return lowerFRAMEADDR(Op, DAG); 2897 case ISD::RETURNADDR: 2898 return lowerRETURNADDR(Op, DAG); 2899 case ISD::SHL_PARTS: 2900 return lowerShiftLeftParts(Op, DAG); 2901 case ISD::SRA_PARTS: 2902 return lowerShiftRightParts(Op, DAG, true); 2903 case ISD::SRL_PARTS: 2904 return lowerShiftRightParts(Op, DAG, false); 2905 case ISD::BITCAST: { 2906 SDLoc DL(Op); 2907 EVT VT = Op.getValueType(); 2908 SDValue Op0 = Op.getOperand(0); 2909 EVT Op0VT = Op0.getValueType(); 2910 MVT XLenVT = Subtarget.getXLenVT(); 2911 if (VT.isFixedLengthVector()) { 2912 // We can handle fixed length vector bitcasts with a simple replacement 2913 // in isel. 2914 if (Op0VT.isFixedLengthVector()) 2915 return Op; 2916 // When bitcasting from scalar to fixed-length vector, insert the scalar 2917 // into a one-element vector of the result type, and perform a vector 2918 // bitcast. 2919 if (!Op0VT.isVector()) { 2920 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2921 if (!isTypeLegal(BVT)) 2922 return SDValue(); 2923 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2924 DAG.getUNDEF(BVT), Op0, 2925 DAG.getConstant(0, DL, XLenVT))); 2926 } 2927 return SDValue(); 2928 } 2929 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2930 // thus: bitcast the vector to a one-element vector type whose element type 2931 // is the same as the result type, and extract the first element. 2932 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2933 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2934 if (!isTypeLegal(BVT)) 2935 return SDValue(); 2936 SDValue BVec = DAG.getBitcast(BVT, Op0); 2937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2938 DAG.getConstant(0, DL, XLenVT)); 2939 } 2940 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2941 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2942 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2943 return FPConv; 2944 } 2945 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2946 Subtarget.hasStdExtF()) { 2947 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2948 SDValue FPConv = 2949 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2950 return FPConv; 2951 } 2952 return SDValue(); 2953 } 2954 case ISD::INTRINSIC_WO_CHAIN: 2955 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2956 case ISD::INTRINSIC_W_CHAIN: 2957 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2958 case ISD::INTRINSIC_VOID: 2959 return LowerINTRINSIC_VOID(Op, DAG); 2960 case ISD::BSWAP: 2961 case ISD::BITREVERSE: { 2962 MVT VT = Op.getSimpleValueType(); 2963 SDLoc DL(Op); 2964 if (Subtarget.hasStdExtZbp()) { 2965 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2966 // Start with the maximum immediate value which is the bitwidth - 1. 2967 unsigned Imm = VT.getSizeInBits() - 1; 2968 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2969 if (Op.getOpcode() == ISD::BSWAP) 2970 Imm &= ~0x7U; 2971 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2972 DAG.getConstant(Imm, DL, VT)); 2973 } 2974 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 2975 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 2976 // Expand bitreverse to a bswap(rev8) followed by brev8. 2977 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 2978 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 2979 // as brev8 by an isel pattern. 2980 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 2981 DAG.getConstant(7, DL, VT)); 2982 } 2983 case ISD::FSHL: 2984 case ISD::FSHR: { 2985 MVT VT = Op.getSimpleValueType(); 2986 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2987 SDLoc DL(Op); 2988 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2989 // use log(XLen) bits. Mask the shift amount accordingly to prevent 2990 // accidentally setting the extra bit. 2991 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2992 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2993 DAG.getConstant(ShAmtWidth, DL, VT)); 2994 // fshl and fshr concatenate their operands in the same order. fsr and fsl 2995 // instruction use different orders. fshl will return its first operand for 2996 // shift of zero, fshr will return its second operand. fsl and fsr both 2997 // return rs1 so the ISD nodes need to have different operand orders. 2998 // Shift amount is in rs2. 2999 SDValue Op0 = Op.getOperand(0); 3000 SDValue Op1 = Op.getOperand(1); 3001 unsigned Opc = RISCVISD::FSL; 3002 if (Op.getOpcode() == ISD::FSHR) { 3003 std::swap(Op0, Op1); 3004 Opc = RISCVISD::FSR; 3005 } 3006 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3007 } 3008 case ISD::TRUNCATE: { 3009 SDLoc DL(Op); 3010 MVT VT = Op.getSimpleValueType(); 3011 // Only custom-lower vector truncates 3012 if (!VT.isVector()) 3013 return Op; 3014 3015 // Truncates to mask types are handled differently 3016 if (VT.getVectorElementType() == MVT::i1) 3017 return lowerVectorMaskTrunc(Op, DAG); 3018 3019 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3020 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3021 // truncate by one power of two at a time. 3022 MVT DstEltVT = VT.getVectorElementType(); 3023 3024 SDValue Src = Op.getOperand(0); 3025 MVT SrcVT = Src.getSimpleValueType(); 3026 MVT SrcEltVT = SrcVT.getVectorElementType(); 3027 3028 assert(DstEltVT.bitsLT(SrcEltVT) && 3029 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3030 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3031 "Unexpected vector truncate lowering"); 3032 3033 MVT ContainerVT = SrcVT; 3034 if (SrcVT.isFixedLengthVector()) { 3035 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3036 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3037 } 3038 3039 SDValue Result = Src; 3040 SDValue Mask, VL; 3041 std::tie(Mask, VL) = 3042 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3043 LLVMContext &Context = *DAG.getContext(); 3044 const ElementCount Count = ContainerVT.getVectorElementCount(); 3045 do { 3046 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3047 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3048 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3049 Mask, VL); 3050 } while (SrcEltVT != DstEltVT); 3051 3052 if (SrcVT.isFixedLengthVector()) 3053 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3054 3055 return Result; 3056 } 3057 case ISD::ANY_EXTEND: 3058 case ISD::ZERO_EXTEND: 3059 if (Op.getOperand(0).getValueType().isVector() && 3060 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3061 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3062 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3063 case ISD::SIGN_EXTEND: 3064 if (Op.getOperand(0).getValueType().isVector() && 3065 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3066 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3067 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3068 case ISD::SPLAT_VECTOR_PARTS: 3069 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3070 case ISD::INSERT_VECTOR_ELT: 3071 return lowerINSERT_VECTOR_ELT(Op, DAG); 3072 case ISD::EXTRACT_VECTOR_ELT: 3073 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3074 case ISD::VSCALE: { 3075 MVT VT = Op.getSimpleValueType(); 3076 SDLoc DL(Op); 3077 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3078 // We define our scalable vector types for lmul=1 to use a 64 bit known 3079 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3080 // vscale as VLENB / 8. 3081 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3082 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3083 report_fatal_error("Support for VLEN==32 is incomplete."); 3084 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3085 // We assume VLENB is a multiple of 8. We manually choose the best shift 3086 // here because SimplifyDemandedBits isn't always able to simplify it. 3087 uint64_t Val = Op.getConstantOperandVal(0); 3088 if (isPowerOf2_64(Val)) { 3089 uint64_t Log2 = Log2_64(Val); 3090 if (Log2 < 3) 3091 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3092 DAG.getConstant(3 - Log2, DL, VT)); 3093 if (Log2 > 3) 3094 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3095 DAG.getConstant(Log2 - 3, DL, VT)); 3096 return VLENB; 3097 } 3098 // If the multiplier is a multiple of 8, scale it down to avoid needing 3099 // to shift the VLENB value. 3100 if ((Val % 8) == 0) 3101 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3102 DAG.getConstant(Val / 8, DL, VT)); 3103 } 3104 3105 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3106 DAG.getConstant(3, DL, VT)); 3107 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3108 } 3109 case ISD::FPOWI: { 3110 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3111 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3112 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3113 Op.getOperand(1).getValueType() == MVT::i32) { 3114 SDLoc DL(Op); 3115 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3116 SDValue Powi = 3117 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3118 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3119 DAG.getIntPtrConstant(0, DL)); 3120 } 3121 return SDValue(); 3122 } 3123 case ISD::FP_EXTEND: { 3124 // RVV can only do fp_extend to types double the size as the source. We 3125 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3126 // via f32. 3127 SDLoc DL(Op); 3128 MVT VT = Op.getSimpleValueType(); 3129 SDValue Src = Op.getOperand(0); 3130 MVT SrcVT = Src.getSimpleValueType(); 3131 3132 // Prepare any fixed-length vector operands. 3133 MVT ContainerVT = VT; 3134 if (SrcVT.isFixedLengthVector()) { 3135 ContainerVT = getContainerForFixedLengthVector(VT); 3136 MVT SrcContainerVT = 3137 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3138 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3139 } 3140 3141 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3142 SrcVT.getVectorElementType() != MVT::f16) { 3143 // For scalable vectors, we only need to close the gap between 3144 // vXf16->vXf64. 3145 if (!VT.isFixedLengthVector()) 3146 return Op; 3147 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3148 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3149 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3150 } 3151 3152 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3153 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3154 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3155 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3156 3157 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3158 DL, DAG, Subtarget); 3159 if (VT.isFixedLengthVector()) 3160 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3161 return Extend; 3162 } 3163 case ISD::FP_ROUND: { 3164 // RVV can only do fp_round to types half the size as the source. We 3165 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3166 // conversion instruction. 3167 SDLoc DL(Op); 3168 MVT VT = Op.getSimpleValueType(); 3169 SDValue Src = Op.getOperand(0); 3170 MVT SrcVT = Src.getSimpleValueType(); 3171 3172 // Prepare any fixed-length vector operands. 3173 MVT ContainerVT = VT; 3174 if (VT.isFixedLengthVector()) { 3175 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3176 ContainerVT = 3177 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3178 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3179 } 3180 3181 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3182 SrcVT.getVectorElementType() != MVT::f64) { 3183 // For scalable vectors, we only need to close the gap between 3184 // vXf64<->vXf16. 3185 if (!VT.isFixedLengthVector()) 3186 return Op; 3187 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3188 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3189 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3190 } 3191 3192 SDValue Mask, VL; 3193 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3194 3195 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3196 SDValue IntermediateRound = 3197 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3198 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3199 DL, DAG, Subtarget); 3200 3201 if (VT.isFixedLengthVector()) 3202 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3203 return Round; 3204 } 3205 case ISD::FP_TO_SINT: 3206 case ISD::FP_TO_UINT: 3207 case ISD::SINT_TO_FP: 3208 case ISD::UINT_TO_FP: { 3209 // RVV can only do fp<->int conversions to types half/double the size as 3210 // the source. We custom-lower any conversions that do two hops into 3211 // sequences. 3212 MVT VT = Op.getSimpleValueType(); 3213 if (!VT.isVector()) 3214 return Op; 3215 SDLoc DL(Op); 3216 SDValue Src = Op.getOperand(0); 3217 MVT EltVT = VT.getVectorElementType(); 3218 MVT SrcVT = Src.getSimpleValueType(); 3219 MVT SrcEltVT = SrcVT.getVectorElementType(); 3220 unsigned EltSize = EltVT.getSizeInBits(); 3221 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3222 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3223 "Unexpected vector element types"); 3224 3225 bool IsInt2FP = SrcEltVT.isInteger(); 3226 // Widening conversions 3227 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3228 if (IsInt2FP) { 3229 // Do a regular integer sign/zero extension then convert to float. 3230 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3231 VT.getVectorElementCount()); 3232 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3233 ? ISD::ZERO_EXTEND 3234 : ISD::SIGN_EXTEND; 3235 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3236 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3237 } 3238 // FP2Int 3239 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3240 // Do one doubling fp_extend then complete the operation by converting 3241 // to int. 3242 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3243 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3244 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3245 } 3246 3247 // Narrowing conversions 3248 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3249 if (IsInt2FP) { 3250 // One narrowing int_to_fp, then an fp_round. 3251 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3252 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3253 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3254 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3255 } 3256 // FP2Int 3257 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3258 // representable by the integer, the result is poison. 3259 MVT IVecVT = 3260 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3261 VT.getVectorElementCount()); 3262 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3263 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3264 } 3265 3266 // Scalable vectors can exit here. Patterns will handle equally-sized 3267 // conversions halving/doubling ones. 3268 if (!VT.isFixedLengthVector()) 3269 return Op; 3270 3271 // For fixed-length vectors we lower to a custom "VL" node. 3272 unsigned RVVOpc = 0; 3273 switch (Op.getOpcode()) { 3274 default: 3275 llvm_unreachable("Impossible opcode"); 3276 case ISD::FP_TO_SINT: 3277 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3278 break; 3279 case ISD::FP_TO_UINT: 3280 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3281 break; 3282 case ISD::SINT_TO_FP: 3283 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3284 break; 3285 case ISD::UINT_TO_FP: 3286 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3287 break; 3288 } 3289 3290 MVT ContainerVT, SrcContainerVT; 3291 // Derive the reference container type from the larger vector type. 3292 if (SrcEltSize > EltSize) { 3293 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3294 ContainerVT = 3295 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3296 } else { 3297 ContainerVT = getContainerForFixedLengthVector(VT); 3298 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3299 } 3300 3301 SDValue Mask, VL; 3302 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3303 3304 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3305 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3306 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3307 } 3308 case ISD::FP_TO_SINT_SAT: 3309 case ISD::FP_TO_UINT_SAT: 3310 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3311 case ISD::FTRUNC: 3312 case ISD::FCEIL: 3313 case ISD::FFLOOR: 3314 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3315 case ISD::VECREDUCE_ADD: 3316 case ISD::VECREDUCE_UMAX: 3317 case ISD::VECREDUCE_SMAX: 3318 case ISD::VECREDUCE_UMIN: 3319 case ISD::VECREDUCE_SMIN: 3320 return lowerVECREDUCE(Op, DAG); 3321 case ISD::VECREDUCE_AND: 3322 case ISD::VECREDUCE_OR: 3323 case ISD::VECREDUCE_XOR: 3324 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3325 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3326 return lowerVECREDUCE(Op, DAG); 3327 case ISD::VECREDUCE_FADD: 3328 case ISD::VECREDUCE_SEQ_FADD: 3329 case ISD::VECREDUCE_FMIN: 3330 case ISD::VECREDUCE_FMAX: 3331 return lowerFPVECREDUCE(Op, DAG); 3332 case ISD::VP_REDUCE_ADD: 3333 case ISD::VP_REDUCE_UMAX: 3334 case ISD::VP_REDUCE_SMAX: 3335 case ISD::VP_REDUCE_UMIN: 3336 case ISD::VP_REDUCE_SMIN: 3337 case ISD::VP_REDUCE_FADD: 3338 case ISD::VP_REDUCE_SEQ_FADD: 3339 case ISD::VP_REDUCE_FMIN: 3340 case ISD::VP_REDUCE_FMAX: 3341 return lowerVPREDUCE(Op, DAG); 3342 case ISD::VP_REDUCE_AND: 3343 case ISD::VP_REDUCE_OR: 3344 case ISD::VP_REDUCE_XOR: 3345 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3346 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3347 return lowerVPREDUCE(Op, DAG); 3348 case ISD::INSERT_SUBVECTOR: 3349 return lowerINSERT_SUBVECTOR(Op, DAG); 3350 case ISD::EXTRACT_SUBVECTOR: 3351 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3352 case ISD::STEP_VECTOR: 3353 return lowerSTEP_VECTOR(Op, DAG); 3354 case ISD::VECTOR_REVERSE: 3355 return lowerVECTOR_REVERSE(Op, DAG); 3356 case ISD::BUILD_VECTOR: 3357 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3358 case ISD::SPLAT_VECTOR: 3359 if (Op.getValueType().getVectorElementType() == MVT::i1) 3360 return lowerVectorMaskSplat(Op, DAG); 3361 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3362 case ISD::VECTOR_SHUFFLE: 3363 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3364 case ISD::CONCAT_VECTORS: { 3365 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3366 // better than going through the stack, as the default expansion does. 3367 SDLoc DL(Op); 3368 MVT VT = Op.getSimpleValueType(); 3369 unsigned NumOpElts = 3370 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3371 SDValue Vec = DAG.getUNDEF(VT); 3372 for (const auto &OpIdx : enumerate(Op->ops())) { 3373 SDValue SubVec = OpIdx.value(); 3374 // Don't insert undef subvectors. 3375 if (SubVec.isUndef()) 3376 continue; 3377 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3378 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3379 } 3380 return Vec; 3381 } 3382 case ISD::LOAD: 3383 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3384 return V; 3385 if (Op.getValueType().isFixedLengthVector()) 3386 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3387 return Op; 3388 case ISD::STORE: 3389 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3390 return V; 3391 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3392 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3393 return Op; 3394 case ISD::MLOAD: 3395 case ISD::VP_LOAD: 3396 return lowerMaskedLoad(Op, DAG); 3397 case ISD::MSTORE: 3398 case ISD::VP_STORE: 3399 return lowerMaskedStore(Op, DAG); 3400 case ISD::SETCC: 3401 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3402 case ISD::ADD: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3404 case ISD::SUB: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3406 case ISD::MUL: 3407 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3408 case ISD::MULHS: 3409 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3410 case ISD::MULHU: 3411 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3412 case ISD::AND: 3413 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3414 RISCVISD::AND_VL); 3415 case ISD::OR: 3416 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3417 RISCVISD::OR_VL); 3418 case ISD::XOR: 3419 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3420 RISCVISD::XOR_VL); 3421 case ISD::SDIV: 3422 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3423 case ISD::SREM: 3424 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3425 case ISD::UDIV: 3426 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3427 case ISD::UREM: 3428 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3429 case ISD::SHL: 3430 case ISD::SRA: 3431 case ISD::SRL: 3432 if (Op.getSimpleValueType().isFixedLengthVector()) 3433 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3434 // This can be called for an i32 shift amount that needs to be promoted. 3435 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3436 "Unexpected custom legalisation"); 3437 return SDValue(); 3438 case ISD::SADDSAT: 3439 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3440 case ISD::UADDSAT: 3441 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3442 case ISD::SSUBSAT: 3443 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3444 case ISD::USUBSAT: 3445 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3446 case ISD::FADD: 3447 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3448 case ISD::FSUB: 3449 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3450 case ISD::FMUL: 3451 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3452 case ISD::FDIV: 3453 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3454 case ISD::FNEG: 3455 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3456 case ISD::FABS: 3457 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3458 case ISD::FSQRT: 3459 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3460 case ISD::FMA: 3461 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3462 case ISD::SMIN: 3463 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3464 case ISD::SMAX: 3465 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3466 case ISD::UMIN: 3467 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3468 case ISD::UMAX: 3469 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3470 case ISD::FMINNUM: 3471 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3472 case ISD::FMAXNUM: 3473 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3474 case ISD::ABS: 3475 return lowerABS(Op, DAG); 3476 case ISD::CTLZ_ZERO_UNDEF: 3477 case ISD::CTTZ_ZERO_UNDEF: 3478 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3479 case ISD::VSELECT: 3480 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3481 case ISD::FCOPYSIGN: 3482 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3483 case ISD::MGATHER: 3484 case ISD::VP_GATHER: 3485 return lowerMaskedGather(Op, DAG); 3486 case ISD::MSCATTER: 3487 case ISD::VP_SCATTER: 3488 return lowerMaskedScatter(Op, DAG); 3489 case ISD::FLT_ROUNDS_: 3490 return lowerGET_ROUNDING(Op, DAG); 3491 case ISD::SET_ROUNDING: 3492 return lowerSET_ROUNDING(Op, DAG); 3493 case ISD::VP_SELECT: 3494 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3495 case ISD::VP_MERGE: 3496 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3497 case ISD::VP_ADD: 3498 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3499 case ISD::VP_SUB: 3500 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3501 case ISD::VP_MUL: 3502 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3503 case ISD::VP_SDIV: 3504 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3505 case ISD::VP_UDIV: 3506 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3507 case ISD::VP_SREM: 3508 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3509 case ISD::VP_UREM: 3510 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3511 case ISD::VP_AND: 3512 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3513 case ISD::VP_OR: 3514 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3515 case ISD::VP_XOR: 3516 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3517 case ISD::VP_ASHR: 3518 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3519 case ISD::VP_LSHR: 3520 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3521 case ISD::VP_SHL: 3522 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3523 case ISD::VP_FADD: 3524 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3525 case ISD::VP_FSUB: 3526 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3527 case ISD::VP_FMUL: 3528 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3529 case ISD::VP_FDIV: 3530 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3531 } 3532 } 3533 3534 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3535 SelectionDAG &DAG, unsigned Flags) { 3536 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3537 } 3538 3539 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3540 SelectionDAG &DAG, unsigned Flags) { 3541 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3542 Flags); 3543 } 3544 3545 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3546 SelectionDAG &DAG, unsigned Flags) { 3547 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3548 N->getOffset(), Flags); 3549 } 3550 3551 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3552 SelectionDAG &DAG, unsigned Flags) { 3553 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3554 } 3555 3556 template <class NodeTy> 3557 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3558 bool IsLocal) const { 3559 SDLoc DL(N); 3560 EVT Ty = getPointerTy(DAG.getDataLayout()); 3561 3562 if (isPositionIndependent()) { 3563 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3564 if (IsLocal) 3565 // Use PC-relative addressing to access the symbol. This generates the 3566 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3567 // %pcrel_lo(auipc)). 3568 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3569 3570 // Use PC-relative addressing to access the GOT for this symbol, then load 3571 // the address from the GOT. This generates the pattern (PseudoLA sym), 3572 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3573 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3574 } 3575 3576 switch (getTargetMachine().getCodeModel()) { 3577 default: 3578 report_fatal_error("Unsupported code model for lowering"); 3579 case CodeModel::Small: { 3580 // Generate a sequence for accessing addresses within the first 2 GiB of 3581 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3582 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3583 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3584 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3585 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3586 } 3587 case CodeModel::Medium: { 3588 // Generate a sequence for accessing addresses within any 2GiB range within 3589 // the address space. This generates the pattern (PseudoLLA sym), which 3590 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3591 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3592 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3593 } 3594 } 3595 } 3596 3597 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3598 SelectionDAG &DAG) const { 3599 SDLoc DL(Op); 3600 EVT Ty = Op.getValueType(); 3601 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3602 int64_t Offset = N->getOffset(); 3603 MVT XLenVT = Subtarget.getXLenVT(); 3604 3605 const GlobalValue *GV = N->getGlobal(); 3606 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3607 SDValue Addr = getAddr(N, DAG, IsLocal); 3608 3609 // In order to maximise the opportunity for common subexpression elimination, 3610 // emit a separate ADD node for the global address offset instead of folding 3611 // it in the global address node. Later peephole optimisations may choose to 3612 // fold it back in when profitable. 3613 if (Offset != 0) 3614 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3615 DAG.getConstant(Offset, DL, XLenVT)); 3616 return Addr; 3617 } 3618 3619 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3620 SelectionDAG &DAG) const { 3621 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3622 3623 return getAddr(N, DAG); 3624 } 3625 3626 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3627 SelectionDAG &DAG) const { 3628 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3629 3630 return getAddr(N, DAG); 3631 } 3632 3633 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3634 SelectionDAG &DAG) const { 3635 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3636 3637 return getAddr(N, DAG); 3638 } 3639 3640 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3641 SelectionDAG &DAG, 3642 bool UseGOT) const { 3643 SDLoc DL(N); 3644 EVT Ty = getPointerTy(DAG.getDataLayout()); 3645 const GlobalValue *GV = N->getGlobal(); 3646 MVT XLenVT = Subtarget.getXLenVT(); 3647 3648 if (UseGOT) { 3649 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3650 // load the address from the GOT and add the thread pointer. This generates 3651 // the pattern (PseudoLA_TLS_IE sym), which expands to 3652 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3653 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3654 SDValue Load = 3655 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3656 3657 // Add the thread pointer. 3658 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3659 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3660 } 3661 3662 // Generate a sequence for accessing the address relative to the thread 3663 // pointer, with the appropriate adjustment for the thread pointer offset. 3664 // This generates the pattern 3665 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3666 SDValue AddrHi = 3667 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3668 SDValue AddrAdd = 3669 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3670 SDValue AddrLo = 3671 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3672 3673 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3674 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3675 SDValue MNAdd = SDValue( 3676 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3677 0); 3678 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3679 } 3680 3681 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3682 SelectionDAG &DAG) const { 3683 SDLoc DL(N); 3684 EVT Ty = getPointerTy(DAG.getDataLayout()); 3685 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3686 const GlobalValue *GV = N->getGlobal(); 3687 3688 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3689 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3690 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3691 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3692 SDValue Load = 3693 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3694 3695 // Prepare argument list to generate call. 3696 ArgListTy Args; 3697 ArgListEntry Entry; 3698 Entry.Node = Load; 3699 Entry.Ty = CallTy; 3700 Args.push_back(Entry); 3701 3702 // Setup call to __tls_get_addr. 3703 TargetLowering::CallLoweringInfo CLI(DAG); 3704 CLI.setDebugLoc(DL) 3705 .setChain(DAG.getEntryNode()) 3706 .setLibCallee(CallingConv::C, CallTy, 3707 DAG.getExternalSymbol("__tls_get_addr", Ty), 3708 std::move(Args)); 3709 3710 return LowerCallTo(CLI).first; 3711 } 3712 3713 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3714 SelectionDAG &DAG) const { 3715 SDLoc DL(Op); 3716 EVT Ty = Op.getValueType(); 3717 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3718 int64_t Offset = N->getOffset(); 3719 MVT XLenVT = Subtarget.getXLenVT(); 3720 3721 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3722 3723 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3724 CallingConv::GHC) 3725 report_fatal_error("In GHC calling convention TLS is not supported"); 3726 3727 SDValue Addr; 3728 switch (Model) { 3729 case TLSModel::LocalExec: 3730 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3731 break; 3732 case TLSModel::InitialExec: 3733 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3734 break; 3735 case TLSModel::LocalDynamic: 3736 case TLSModel::GeneralDynamic: 3737 Addr = getDynamicTLSAddr(N, DAG); 3738 break; 3739 } 3740 3741 // In order to maximise the opportunity for common subexpression elimination, 3742 // emit a separate ADD node for the global address offset instead of folding 3743 // it in the global address node. Later peephole optimisations may choose to 3744 // fold it back in when profitable. 3745 if (Offset != 0) 3746 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3747 DAG.getConstant(Offset, DL, XLenVT)); 3748 return Addr; 3749 } 3750 3751 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3752 SDValue CondV = Op.getOperand(0); 3753 SDValue TrueV = Op.getOperand(1); 3754 SDValue FalseV = Op.getOperand(2); 3755 SDLoc DL(Op); 3756 MVT VT = Op.getSimpleValueType(); 3757 MVT XLenVT = Subtarget.getXLenVT(); 3758 3759 // Lower vector SELECTs to VSELECTs by splatting the condition. 3760 if (VT.isVector()) { 3761 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3762 SDValue CondSplat = VT.isScalableVector() 3763 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3764 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3765 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3766 } 3767 3768 // If the result type is XLenVT and CondV is the output of a SETCC node 3769 // which also operated on XLenVT inputs, then merge the SETCC node into the 3770 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3771 // compare+branch instructions. i.e.: 3772 // (select (setcc lhs, rhs, cc), truev, falsev) 3773 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3774 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3775 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3776 SDValue LHS = CondV.getOperand(0); 3777 SDValue RHS = CondV.getOperand(1); 3778 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3779 ISD::CondCode CCVal = CC->get(); 3780 3781 // Special case for a select of 2 constants that have a diffence of 1. 3782 // Normally this is done by DAGCombine, but if the select is introduced by 3783 // type legalization or op legalization, we miss it. Restricting to SETLT 3784 // case for now because that is what signed saturating add/sub need. 3785 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3786 // but we would probably want to swap the true/false values if the condition 3787 // is SETGE/SETLE to avoid an XORI. 3788 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3789 CCVal == ISD::SETLT) { 3790 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3791 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3792 if (TrueVal - 1 == FalseVal) 3793 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3794 if (TrueVal + 1 == FalseVal) 3795 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3796 } 3797 3798 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3799 3800 SDValue TargetCC = DAG.getCondCode(CCVal); 3801 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3802 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3803 } 3804 3805 // Otherwise: 3806 // (select condv, truev, falsev) 3807 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3808 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3809 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3810 3811 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3812 3813 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3814 } 3815 3816 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3817 SDValue CondV = Op.getOperand(1); 3818 SDLoc DL(Op); 3819 MVT XLenVT = Subtarget.getXLenVT(); 3820 3821 if (CondV.getOpcode() == ISD::SETCC && 3822 CondV.getOperand(0).getValueType() == XLenVT) { 3823 SDValue LHS = CondV.getOperand(0); 3824 SDValue RHS = CondV.getOperand(1); 3825 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3826 3827 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3828 3829 SDValue TargetCC = DAG.getCondCode(CCVal); 3830 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3831 LHS, RHS, TargetCC, Op.getOperand(2)); 3832 } 3833 3834 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3835 CondV, DAG.getConstant(0, DL, XLenVT), 3836 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3837 } 3838 3839 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3840 MachineFunction &MF = DAG.getMachineFunction(); 3841 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3842 3843 SDLoc DL(Op); 3844 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3845 getPointerTy(MF.getDataLayout())); 3846 3847 // vastart just stores the address of the VarArgsFrameIndex slot into the 3848 // memory location argument. 3849 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3850 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3851 MachinePointerInfo(SV)); 3852 } 3853 3854 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3855 SelectionDAG &DAG) const { 3856 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3857 MachineFunction &MF = DAG.getMachineFunction(); 3858 MachineFrameInfo &MFI = MF.getFrameInfo(); 3859 MFI.setFrameAddressIsTaken(true); 3860 Register FrameReg = RI.getFrameRegister(MF); 3861 int XLenInBytes = Subtarget.getXLen() / 8; 3862 3863 EVT VT = Op.getValueType(); 3864 SDLoc DL(Op); 3865 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3866 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3867 while (Depth--) { 3868 int Offset = -(XLenInBytes * 2); 3869 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3870 DAG.getIntPtrConstant(Offset, DL)); 3871 FrameAddr = 3872 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3873 } 3874 return FrameAddr; 3875 } 3876 3877 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3878 SelectionDAG &DAG) const { 3879 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3880 MachineFunction &MF = DAG.getMachineFunction(); 3881 MachineFrameInfo &MFI = MF.getFrameInfo(); 3882 MFI.setReturnAddressIsTaken(true); 3883 MVT XLenVT = Subtarget.getXLenVT(); 3884 int XLenInBytes = Subtarget.getXLen() / 8; 3885 3886 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3887 return SDValue(); 3888 3889 EVT VT = Op.getValueType(); 3890 SDLoc DL(Op); 3891 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3892 if (Depth) { 3893 int Off = -XLenInBytes; 3894 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3895 SDValue Offset = DAG.getConstant(Off, DL, VT); 3896 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3897 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3898 MachinePointerInfo()); 3899 } 3900 3901 // Return the value of the return address register, marking it an implicit 3902 // live-in. 3903 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3904 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3905 } 3906 3907 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3908 SelectionDAG &DAG) const { 3909 SDLoc DL(Op); 3910 SDValue Lo = Op.getOperand(0); 3911 SDValue Hi = Op.getOperand(1); 3912 SDValue Shamt = Op.getOperand(2); 3913 EVT VT = Lo.getValueType(); 3914 3915 // if Shamt-XLEN < 0: // Shamt < XLEN 3916 // Lo = Lo << Shamt 3917 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3918 // else: 3919 // Lo = 0 3920 // Hi = Lo << (Shamt-XLEN) 3921 3922 SDValue Zero = DAG.getConstant(0, DL, VT); 3923 SDValue One = DAG.getConstant(1, DL, VT); 3924 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3925 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3926 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3927 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3928 3929 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3930 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3931 SDValue ShiftRightLo = 3932 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3933 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3934 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3935 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3936 3937 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3938 3939 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3940 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3941 3942 SDValue Parts[2] = {Lo, Hi}; 3943 return DAG.getMergeValues(Parts, DL); 3944 } 3945 3946 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3947 bool IsSRA) const { 3948 SDLoc DL(Op); 3949 SDValue Lo = Op.getOperand(0); 3950 SDValue Hi = Op.getOperand(1); 3951 SDValue Shamt = Op.getOperand(2); 3952 EVT VT = Lo.getValueType(); 3953 3954 // SRA expansion: 3955 // if Shamt-XLEN < 0: // Shamt < XLEN 3956 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3957 // Hi = Hi >>s Shamt 3958 // else: 3959 // Lo = Hi >>s (Shamt-XLEN); 3960 // Hi = Hi >>s (XLEN-1) 3961 // 3962 // SRL expansion: 3963 // if Shamt-XLEN < 0: // Shamt < XLEN 3964 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3965 // Hi = Hi >>u Shamt 3966 // else: 3967 // Lo = Hi >>u (Shamt-XLEN); 3968 // Hi = 0; 3969 3970 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3971 3972 SDValue Zero = DAG.getConstant(0, DL, VT); 3973 SDValue One = DAG.getConstant(1, DL, VT); 3974 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3975 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3976 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3977 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3978 3979 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3980 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3981 SDValue ShiftLeftHi = 3982 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3983 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3984 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3985 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3986 SDValue HiFalse = 3987 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3988 3989 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3990 3991 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3992 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3993 3994 SDValue Parts[2] = {Lo, Hi}; 3995 return DAG.getMergeValues(Parts, DL); 3996 } 3997 3998 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3999 // legal equivalently-sized i8 type, so we can use that as a go-between. 4000 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4001 SelectionDAG &DAG) const { 4002 SDLoc DL(Op); 4003 MVT VT = Op.getSimpleValueType(); 4004 SDValue SplatVal = Op.getOperand(0); 4005 // All-zeros or all-ones splats are handled specially. 4006 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4007 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4008 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4009 } 4010 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4011 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4012 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4013 } 4014 MVT XLenVT = Subtarget.getXLenVT(); 4015 assert(SplatVal.getValueType() == XLenVT && 4016 "Unexpected type for i1 splat value"); 4017 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4018 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4019 DAG.getConstant(1, DL, XLenVT)); 4020 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4021 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4022 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4023 } 4024 4025 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4026 // illegal (currently only vXi64 RV32). 4027 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4028 // them to VMV_V_X_VL. 4029 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4030 SelectionDAG &DAG) const { 4031 SDLoc DL(Op); 4032 MVT VecVT = Op.getSimpleValueType(); 4033 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4034 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4035 4036 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4037 SDValue Lo = Op.getOperand(0); 4038 SDValue Hi = Op.getOperand(1); 4039 4040 if (VecVT.isFixedLengthVector()) { 4041 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4042 SDLoc DL(Op); 4043 SDValue Mask, VL; 4044 std::tie(Mask, VL) = 4045 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4046 4047 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 4048 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4049 } 4050 4051 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4052 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4053 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4054 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4055 // node in order to try and match RVV vector/scalar instructions. 4056 if ((LoC >> 31) == HiC) 4057 return DAG.getNode( 4058 RISCVISD::VMV_V_X_VL, DL, VecVT, Lo, 4059 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32)); 4060 } 4061 4062 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4063 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4064 isa<ConstantSDNode>(Hi.getOperand(1)) && 4065 Hi.getConstantOperandVal(1) == 31) 4066 return DAG.getNode( 4067 RISCVISD::VMV_V_X_VL, DL, VecVT, Lo, 4068 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32)); 4069 4070 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4071 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 4072 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32)); 4073 } 4074 4075 // Custom-lower extensions from mask vectors by using a vselect either with 1 4076 // for zero/any-extension or -1 for sign-extension: 4077 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4078 // Note that any-extension is lowered identically to zero-extension. 4079 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4080 int64_t ExtTrueVal) const { 4081 SDLoc DL(Op); 4082 MVT VecVT = Op.getSimpleValueType(); 4083 SDValue Src = Op.getOperand(0); 4084 // Only custom-lower extensions from mask types 4085 assert(Src.getValueType().isVector() && 4086 Src.getValueType().getVectorElementType() == MVT::i1); 4087 4088 MVT XLenVT = Subtarget.getXLenVT(); 4089 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4090 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4091 4092 if (VecVT.isScalableVector()) { 4093 // Be careful not to introduce illegal scalar types at this stage, and be 4094 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4095 // illegal and must be expanded. Since we know that the constants are 4096 // sign-extended 32-bit values, we use VMV_V_X_VL directly. 4097 bool IsRV32E64 = 4098 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4099 4100 if (!IsRV32E64) { 4101 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4102 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4103 } else { 4104 SplatZero = 4105 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, SplatZero, 4106 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 4107 SplatTrueVal = 4108 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, SplatTrueVal, 4109 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 4110 } 4111 4112 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4113 } 4114 4115 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4116 MVT I1ContainerVT = 4117 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4118 4119 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4120 4121 SDValue Mask, VL; 4122 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4123 4124 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 4125 SplatTrueVal = 4126 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 4127 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4128 SplatTrueVal, SplatZero, VL); 4129 4130 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4131 } 4132 4133 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4134 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4135 MVT ExtVT = Op.getSimpleValueType(); 4136 // Only custom-lower extensions from fixed-length vector types. 4137 if (!ExtVT.isFixedLengthVector()) 4138 return Op; 4139 MVT VT = Op.getOperand(0).getSimpleValueType(); 4140 // Grab the canonical container type for the extended type. Infer the smaller 4141 // type from that to ensure the same number of vector elements, as we know 4142 // the LMUL will be sufficient to hold the smaller type. 4143 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4144 // Get the extended container type manually to ensure the same number of 4145 // vector elements between source and dest. 4146 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4147 ContainerExtVT.getVectorElementCount()); 4148 4149 SDValue Op1 = 4150 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4151 4152 SDLoc DL(Op); 4153 SDValue Mask, VL; 4154 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4155 4156 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4157 4158 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4159 } 4160 4161 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4162 // setcc operation: 4163 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4164 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4165 SelectionDAG &DAG) const { 4166 SDLoc DL(Op); 4167 EVT MaskVT = Op.getValueType(); 4168 // Only expect to custom-lower truncations to mask types 4169 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4170 "Unexpected type for vector mask lowering"); 4171 SDValue Src = Op.getOperand(0); 4172 MVT VecVT = Src.getSimpleValueType(); 4173 4174 // If this is a fixed vector, we need to convert it to a scalable vector. 4175 MVT ContainerVT = VecVT; 4176 if (VecVT.isFixedLengthVector()) { 4177 ContainerVT = getContainerForFixedLengthVector(VecVT); 4178 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4179 } 4180 4181 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4182 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4183 4184 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 4185 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 4186 4187 if (VecVT.isScalableVector()) { 4188 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4189 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4190 } 4191 4192 SDValue Mask, VL; 4193 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4194 4195 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4196 SDValue Trunc = 4197 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4198 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4199 DAG.getCondCode(ISD::SETNE), Mask, VL); 4200 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4201 } 4202 4203 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4204 // first position of a vector, and that vector is slid up to the insert index. 4205 // By limiting the active vector length to index+1 and merging with the 4206 // original vector (with an undisturbed tail policy for elements >= VL), we 4207 // achieve the desired result of leaving all elements untouched except the one 4208 // at VL-1, which is replaced with the desired value. 4209 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4210 SelectionDAG &DAG) const { 4211 SDLoc DL(Op); 4212 MVT VecVT = Op.getSimpleValueType(); 4213 SDValue Vec = Op.getOperand(0); 4214 SDValue Val = Op.getOperand(1); 4215 SDValue Idx = Op.getOperand(2); 4216 4217 if (VecVT.getVectorElementType() == MVT::i1) { 4218 // FIXME: For now we just promote to an i8 vector and insert into that, 4219 // but this is probably not optimal. 4220 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4221 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4222 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4223 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4224 } 4225 4226 MVT ContainerVT = VecVT; 4227 // If the operand is a fixed-length vector, convert to a scalable one. 4228 if (VecVT.isFixedLengthVector()) { 4229 ContainerVT = getContainerForFixedLengthVector(VecVT); 4230 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4231 } 4232 4233 MVT XLenVT = Subtarget.getXLenVT(); 4234 4235 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4236 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4237 // Even i64-element vectors on RV32 can be lowered without scalar 4238 // legalization if the most-significant 32 bits of the value are not affected 4239 // by the sign-extension of the lower 32 bits. 4240 // TODO: We could also catch sign extensions of a 32-bit value. 4241 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4242 const auto *CVal = cast<ConstantSDNode>(Val); 4243 if (isInt<32>(CVal->getSExtValue())) { 4244 IsLegalInsert = true; 4245 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4246 } 4247 } 4248 4249 SDValue Mask, VL; 4250 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4251 4252 SDValue ValInVec; 4253 4254 if (IsLegalInsert) { 4255 unsigned Opc = 4256 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4257 if (isNullConstant(Idx)) { 4258 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4259 if (!VecVT.isFixedLengthVector()) 4260 return Vec; 4261 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4262 } 4263 ValInVec = 4264 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4265 } else { 4266 // On RV32, i64-element vectors must be specially handled to place the 4267 // value at element 0, by using two vslide1up instructions in sequence on 4268 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4269 // this. 4270 SDValue One = DAG.getConstant(1, DL, XLenVT); 4271 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4272 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4273 MVT I32ContainerVT = 4274 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4275 SDValue I32Mask = 4276 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4277 // Limit the active VL to two. 4278 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4279 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4280 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4281 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4282 InsertI64VL); 4283 // First slide in the hi value, then the lo in underneath it. 4284 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4285 ValHi, I32Mask, InsertI64VL); 4286 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4287 ValLo, I32Mask, InsertI64VL); 4288 // Bitcast back to the right container type. 4289 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4290 } 4291 4292 // Now that the value is in a vector, slide it into position. 4293 SDValue InsertVL = 4294 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4295 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4296 ValInVec, Idx, Mask, InsertVL); 4297 if (!VecVT.isFixedLengthVector()) 4298 return Slideup; 4299 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4300 } 4301 4302 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4303 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4304 // types this is done using VMV_X_S to allow us to glean information about the 4305 // sign bits of the result. 4306 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4307 SelectionDAG &DAG) const { 4308 SDLoc DL(Op); 4309 SDValue Idx = Op.getOperand(1); 4310 SDValue Vec = Op.getOperand(0); 4311 EVT EltVT = Op.getValueType(); 4312 MVT VecVT = Vec.getSimpleValueType(); 4313 MVT XLenVT = Subtarget.getXLenVT(); 4314 4315 if (VecVT.getVectorElementType() == MVT::i1) { 4316 if (VecVT.isFixedLengthVector()) { 4317 unsigned NumElts = VecVT.getVectorNumElements(); 4318 if (NumElts >= 8) { 4319 MVT WideEltVT; 4320 unsigned WidenVecLen; 4321 SDValue ExtractElementIdx; 4322 SDValue ExtractBitIdx; 4323 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4324 MVT LargestEltVT = MVT::getIntegerVT( 4325 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4326 if (NumElts <= LargestEltVT.getSizeInBits()) { 4327 assert(isPowerOf2_32(NumElts) && 4328 "the number of elements should be power of 2"); 4329 WideEltVT = MVT::getIntegerVT(NumElts); 4330 WidenVecLen = 1; 4331 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4332 ExtractBitIdx = Idx; 4333 } else { 4334 WideEltVT = LargestEltVT; 4335 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4336 // extract element index = index / element width 4337 ExtractElementIdx = DAG.getNode( 4338 ISD::SRL, DL, XLenVT, Idx, 4339 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4340 // mask bit index = index % element width 4341 ExtractBitIdx = DAG.getNode( 4342 ISD::AND, DL, XLenVT, Idx, 4343 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4344 } 4345 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4346 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4347 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4348 Vec, ExtractElementIdx); 4349 // Extract the bit from GPR. 4350 SDValue ShiftRight = 4351 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4352 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4353 DAG.getConstant(1, DL, XLenVT)); 4354 } 4355 } 4356 // Otherwise, promote to an i8 vector and extract from that. 4357 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4358 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4359 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4360 } 4361 4362 // If this is a fixed vector, we need to convert it to a scalable vector. 4363 MVT ContainerVT = VecVT; 4364 if (VecVT.isFixedLengthVector()) { 4365 ContainerVT = getContainerForFixedLengthVector(VecVT); 4366 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4367 } 4368 4369 // If the index is 0, the vector is already in the right position. 4370 if (!isNullConstant(Idx)) { 4371 // Use a VL of 1 to avoid processing more elements than we need. 4372 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4373 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4374 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4375 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4376 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4377 } 4378 4379 if (!EltVT.isInteger()) { 4380 // Floating-point extracts are handled in TableGen. 4381 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4382 DAG.getConstant(0, DL, XLenVT)); 4383 } 4384 4385 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4386 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4387 } 4388 4389 // Some RVV intrinsics may claim that they want an integer operand to be 4390 // promoted or expanded. 4391 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4392 const RISCVSubtarget &Subtarget) { 4393 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4394 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4395 "Unexpected opcode"); 4396 4397 if (!Subtarget.hasVInstructions()) 4398 return SDValue(); 4399 4400 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4401 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4402 SDLoc DL(Op); 4403 4404 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4405 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4406 if (!II || !II->hasSplatOperand()) 4407 return SDValue(); 4408 4409 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4410 assert(SplatOp < Op.getNumOperands()); 4411 4412 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4413 SDValue &ScalarOp = Operands[SplatOp]; 4414 MVT OpVT = ScalarOp.getSimpleValueType(); 4415 MVT XLenVT = Subtarget.getXLenVT(); 4416 4417 // If this isn't a scalar, or its type is XLenVT we're done. 4418 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4419 return SDValue(); 4420 4421 // Simplest case is that the operand needs to be promoted to XLenVT. 4422 if (OpVT.bitsLT(XLenVT)) { 4423 // If the operand is a constant, sign extend to increase our chances 4424 // of being able to use a .vi instruction. ANY_EXTEND would become a 4425 // a zero extend and the simm5 check in isel would fail. 4426 // FIXME: Should we ignore the upper bits in isel instead? 4427 unsigned ExtOpc = 4428 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4429 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4430 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4431 } 4432 4433 // Use the previous operand to get the vXi64 VT. The result might be a mask 4434 // VT for compares. Using the previous operand assumes that the previous 4435 // operand will never have a smaller element size than a scalar operand and 4436 // that a widening operation never uses SEW=64. 4437 // NOTE: If this fails the below assert, we can probably just find the 4438 // element count from any operand or result and use it to construct the VT. 4439 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4440 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4441 4442 // The more complex case is when the scalar is larger than XLenVT. 4443 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4444 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4445 4446 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4447 // on the instruction to sign-extend since SEW>XLEN. 4448 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4449 if (isInt<32>(CVal->getSExtValue())) { 4450 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4451 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4452 } 4453 } 4454 4455 // We need to convert the scalar to a splat vector. 4456 // FIXME: Can we implicitly truncate the scalar if it is known to 4457 // be sign extended? 4458 SDValue VL = getVLOperand(Op); 4459 assert(VL.getValueType() == XLenVT); 4460 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4461 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4462 } 4463 4464 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4465 SelectionDAG &DAG) const { 4466 unsigned IntNo = Op.getConstantOperandVal(0); 4467 SDLoc DL(Op); 4468 MVT XLenVT = Subtarget.getXLenVT(); 4469 4470 switch (IntNo) { 4471 default: 4472 break; // Don't custom lower most intrinsics. 4473 case Intrinsic::thread_pointer: { 4474 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4475 return DAG.getRegister(RISCV::X4, PtrVT); 4476 } 4477 case Intrinsic::riscv_orc_b: 4478 case Intrinsic::riscv_brev8: { 4479 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4480 unsigned Opc = 4481 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4482 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4483 DAG.getConstant(7, DL, XLenVT)); 4484 } 4485 case Intrinsic::riscv_grev: 4486 case Intrinsic::riscv_gorc: { 4487 unsigned Opc = 4488 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4489 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4490 } 4491 case Intrinsic::riscv_zip: 4492 case Intrinsic::riscv_unzip: { 4493 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4494 // For i32 the immdiate is 15. For i64 the immediate is 31. 4495 unsigned Opc = 4496 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4497 unsigned BitWidth = Op.getValueSizeInBits(); 4498 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4499 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4500 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4501 } 4502 case Intrinsic::riscv_shfl: 4503 case Intrinsic::riscv_unshfl: { 4504 unsigned Opc = 4505 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4506 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4507 } 4508 case Intrinsic::riscv_bcompress: 4509 case Intrinsic::riscv_bdecompress: { 4510 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4511 : RISCVISD::BDECOMPRESS; 4512 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4513 } 4514 case Intrinsic::riscv_bfp: 4515 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4516 Op.getOperand(2)); 4517 case Intrinsic::riscv_fsl: 4518 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4519 Op.getOperand(2), Op.getOperand(3)); 4520 case Intrinsic::riscv_fsr: 4521 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4522 Op.getOperand(2), Op.getOperand(3)); 4523 case Intrinsic::riscv_vmv_x_s: 4524 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4525 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4526 Op.getOperand(1)); 4527 case Intrinsic::riscv_vmv_v_x: 4528 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4529 Op.getSimpleValueType(), DL, DAG, Subtarget); 4530 case Intrinsic::riscv_vfmv_v_f: 4531 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4532 Op.getOperand(1), Op.getOperand(2)); 4533 case Intrinsic::riscv_vmv_s_x: { 4534 SDValue Scalar = Op.getOperand(2); 4535 4536 if (Scalar.getValueType().bitsLE(XLenVT)) { 4537 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4538 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4539 Op.getOperand(1), Scalar, Op.getOperand(3)); 4540 } 4541 4542 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4543 4544 // This is an i64 value that lives in two scalar registers. We have to 4545 // insert this in a convoluted way. First we build vXi64 splat containing 4546 // the/ two values that we assemble using some bit math. Next we'll use 4547 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4548 // to merge element 0 from our splat into the source vector. 4549 // FIXME: This is probably not the best way to do this, but it is 4550 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4551 // point. 4552 // sw lo, (a0) 4553 // sw hi, 4(a0) 4554 // vlse vX, (a0) 4555 // 4556 // vid.v vVid 4557 // vmseq.vx mMask, vVid, 0 4558 // vmerge.vvm vDest, vSrc, vVal, mMask 4559 MVT VT = Op.getSimpleValueType(); 4560 SDValue Vec = Op.getOperand(1); 4561 SDValue VL = getVLOperand(Op); 4562 4563 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4564 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4565 DAG.getConstant(0, DL, MVT::i32), VL); 4566 4567 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4568 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4569 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4570 SDValue SelectCond = 4571 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4572 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4573 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4574 Vec, VL); 4575 } 4576 case Intrinsic::riscv_vslide1up: 4577 case Intrinsic::riscv_vslide1down: 4578 case Intrinsic::riscv_vslide1up_mask: 4579 case Intrinsic::riscv_vslide1down_mask: { 4580 // We need to special case these when the scalar is larger than XLen. 4581 unsigned NumOps = Op.getNumOperands(); 4582 bool IsMasked = NumOps == 7; 4583 unsigned OpOffset = IsMasked ? 1 : 0; 4584 SDValue Scalar = Op.getOperand(2 + OpOffset); 4585 if (Scalar.getValueType().bitsLE(XLenVT)) 4586 break; 4587 4588 // Splatting a sign extended constant is fine. 4589 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4590 if (isInt<32>(CVal->getSExtValue())) 4591 break; 4592 4593 MVT VT = Op.getSimpleValueType(); 4594 assert(VT.getVectorElementType() == MVT::i64 && 4595 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4596 4597 // Convert the vector source to the equivalent nxvXi32 vector. 4598 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4599 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4600 4601 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4602 DAG.getConstant(0, DL, XLenVT)); 4603 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4604 DAG.getConstant(1, DL, XLenVT)); 4605 4606 // Double the VL since we halved SEW. 4607 SDValue VL = getVLOperand(Op); 4608 SDValue I32VL = 4609 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4610 4611 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4612 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4613 4614 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4615 // instructions. 4616 if (IntNo == Intrinsic::riscv_vslide1up || 4617 IntNo == Intrinsic::riscv_vslide1up_mask) { 4618 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4619 I32Mask, I32VL); 4620 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4621 I32Mask, I32VL); 4622 } else { 4623 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4624 I32Mask, I32VL); 4625 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4626 I32Mask, I32VL); 4627 } 4628 4629 // Convert back to nxvXi64. 4630 Vec = DAG.getBitcast(VT, Vec); 4631 4632 if (!IsMasked) 4633 return Vec; 4634 4635 // Apply mask after the operation. 4636 SDValue Mask = Op.getOperand(NumOps - 3); 4637 SDValue MaskedOff = Op.getOperand(1); 4638 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4639 } 4640 } 4641 4642 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4643 } 4644 4645 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4646 SelectionDAG &DAG) const { 4647 unsigned IntNo = Op.getConstantOperandVal(1); 4648 switch (IntNo) { 4649 default: 4650 break; 4651 case Intrinsic::riscv_masked_strided_load: { 4652 SDLoc DL(Op); 4653 MVT XLenVT = Subtarget.getXLenVT(); 4654 4655 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4656 // the selection of the masked intrinsics doesn't do this for us. 4657 SDValue Mask = Op.getOperand(5); 4658 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4659 4660 MVT VT = Op->getSimpleValueType(0); 4661 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4662 4663 SDValue PassThru = Op.getOperand(2); 4664 if (!IsUnmasked) { 4665 MVT MaskVT = 4666 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4667 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4668 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4669 } 4670 4671 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4672 4673 SDValue IntID = DAG.getTargetConstant( 4674 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4675 XLenVT); 4676 4677 auto *Load = cast<MemIntrinsicSDNode>(Op); 4678 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4679 if (IsUnmasked) 4680 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4681 else 4682 Ops.push_back(PassThru); 4683 Ops.push_back(Op.getOperand(3)); // Ptr 4684 Ops.push_back(Op.getOperand(4)); // Stride 4685 if (!IsUnmasked) 4686 Ops.push_back(Mask); 4687 Ops.push_back(VL); 4688 if (!IsUnmasked) { 4689 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4690 Ops.push_back(Policy); 4691 } 4692 4693 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4694 SDValue Result = 4695 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4696 Load->getMemoryVT(), Load->getMemOperand()); 4697 SDValue Chain = Result.getValue(1); 4698 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4699 return DAG.getMergeValues({Result, Chain}, DL); 4700 } 4701 } 4702 4703 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4704 } 4705 4706 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4707 SelectionDAG &DAG) const { 4708 unsigned IntNo = Op.getConstantOperandVal(1); 4709 switch (IntNo) { 4710 default: 4711 break; 4712 case Intrinsic::riscv_masked_strided_store: { 4713 SDLoc DL(Op); 4714 MVT XLenVT = Subtarget.getXLenVT(); 4715 4716 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4717 // the selection of the masked intrinsics doesn't do this for us. 4718 SDValue Mask = Op.getOperand(5); 4719 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4720 4721 SDValue Val = Op.getOperand(2); 4722 MVT VT = Val.getSimpleValueType(); 4723 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4724 4725 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4726 if (!IsUnmasked) { 4727 MVT MaskVT = 4728 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4729 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4730 } 4731 4732 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4733 4734 SDValue IntID = DAG.getTargetConstant( 4735 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4736 XLenVT); 4737 4738 auto *Store = cast<MemIntrinsicSDNode>(Op); 4739 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4740 Ops.push_back(Val); 4741 Ops.push_back(Op.getOperand(3)); // Ptr 4742 Ops.push_back(Op.getOperand(4)); // Stride 4743 if (!IsUnmasked) 4744 Ops.push_back(Mask); 4745 Ops.push_back(VL); 4746 4747 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4748 Ops, Store->getMemoryVT(), 4749 Store->getMemOperand()); 4750 } 4751 } 4752 4753 return SDValue(); 4754 } 4755 4756 static MVT getLMUL1VT(MVT VT) { 4757 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4758 "Unexpected vector MVT"); 4759 return MVT::getScalableVectorVT( 4760 VT.getVectorElementType(), 4761 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4762 } 4763 4764 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4765 switch (ISDOpcode) { 4766 default: 4767 llvm_unreachable("Unhandled reduction"); 4768 case ISD::VECREDUCE_ADD: 4769 return RISCVISD::VECREDUCE_ADD_VL; 4770 case ISD::VECREDUCE_UMAX: 4771 return RISCVISD::VECREDUCE_UMAX_VL; 4772 case ISD::VECREDUCE_SMAX: 4773 return RISCVISD::VECREDUCE_SMAX_VL; 4774 case ISD::VECREDUCE_UMIN: 4775 return RISCVISD::VECREDUCE_UMIN_VL; 4776 case ISD::VECREDUCE_SMIN: 4777 return RISCVISD::VECREDUCE_SMIN_VL; 4778 case ISD::VECREDUCE_AND: 4779 return RISCVISD::VECREDUCE_AND_VL; 4780 case ISD::VECREDUCE_OR: 4781 return RISCVISD::VECREDUCE_OR_VL; 4782 case ISD::VECREDUCE_XOR: 4783 return RISCVISD::VECREDUCE_XOR_VL; 4784 } 4785 } 4786 4787 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4788 SelectionDAG &DAG, 4789 bool IsVP) const { 4790 SDLoc DL(Op); 4791 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4792 MVT VecVT = Vec.getSimpleValueType(); 4793 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4794 Op.getOpcode() == ISD::VECREDUCE_OR || 4795 Op.getOpcode() == ISD::VECREDUCE_XOR || 4796 Op.getOpcode() == ISD::VP_REDUCE_AND || 4797 Op.getOpcode() == ISD::VP_REDUCE_OR || 4798 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4799 "Unexpected reduction lowering"); 4800 4801 MVT XLenVT = Subtarget.getXLenVT(); 4802 assert(Op.getValueType() == XLenVT && 4803 "Expected reduction output to be legalized to XLenVT"); 4804 4805 MVT ContainerVT = VecVT; 4806 if (VecVT.isFixedLengthVector()) { 4807 ContainerVT = getContainerForFixedLengthVector(VecVT); 4808 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4809 } 4810 4811 SDValue Mask, VL; 4812 if (IsVP) { 4813 Mask = Op.getOperand(2); 4814 VL = Op.getOperand(3); 4815 } else { 4816 std::tie(Mask, VL) = 4817 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4818 } 4819 4820 unsigned BaseOpc; 4821 ISD::CondCode CC; 4822 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4823 4824 switch (Op.getOpcode()) { 4825 default: 4826 llvm_unreachable("Unhandled reduction"); 4827 case ISD::VECREDUCE_AND: 4828 case ISD::VP_REDUCE_AND: { 4829 // vcpop ~x == 0 4830 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4831 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4832 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4833 CC = ISD::SETEQ; 4834 BaseOpc = ISD::AND; 4835 break; 4836 } 4837 case ISD::VECREDUCE_OR: 4838 case ISD::VP_REDUCE_OR: 4839 // vcpop x != 0 4840 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4841 CC = ISD::SETNE; 4842 BaseOpc = ISD::OR; 4843 break; 4844 case ISD::VECREDUCE_XOR: 4845 case ISD::VP_REDUCE_XOR: { 4846 // ((vcpop x) & 1) != 0 4847 SDValue One = DAG.getConstant(1, DL, XLenVT); 4848 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4849 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4850 CC = ISD::SETNE; 4851 BaseOpc = ISD::XOR; 4852 break; 4853 } 4854 } 4855 4856 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4857 4858 if (!IsVP) 4859 return SetCC; 4860 4861 // Now include the start value in the operation. 4862 // Note that we must return the start value when no elements are operated 4863 // upon. The vcpop instructions we've emitted in each case above will return 4864 // 0 for an inactive vector, and so we've already received the neutral value: 4865 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4866 // can simply include the start value. 4867 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4868 } 4869 4870 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4871 SelectionDAG &DAG) const { 4872 SDLoc DL(Op); 4873 SDValue Vec = Op.getOperand(0); 4874 EVT VecEVT = Vec.getValueType(); 4875 4876 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4877 4878 // Due to ordering in legalize types we may have a vector type that needs to 4879 // be split. Do that manually so we can get down to a legal type. 4880 while (getTypeAction(*DAG.getContext(), VecEVT) == 4881 TargetLowering::TypeSplitVector) { 4882 SDValue Lo, Hi; 4883 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4884 VecEVT = Lo.getValueType(); 4885 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4886 } 4887 4888 // TODO: The type may need to be widened rather than split. Or widened before 4889 // it can be split. 4890 if (!isTypeLegal(VecEVT)) 4891 return SDValue(); 4892 4893 MVT VecVT = VecEVT.getSimpleVT(); 4894 MVT VecEltVT = VecVT.getVectorElementType(); 4895 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4896 4897 MVT ContainerVT = VecVT; 4898 if (VecVT.isFixedLengthVector()) { 4899 ContainerVT = getContainerForFixedLengthVector(VecVT); 4900 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4901 } 4902 4903 MVT M1VT = getLMUL1VT(ContainerVT); 4904 MVT XLenVT = Subtarget.getXLenVT(); 4905 4906 SDValue Mask, VL; 4907 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4908 4909 SDValue NeutralElem = 4910 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4911 SDValue IdentitySplat = lowerScalarSplat( 4912 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4913 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4914 IdentitySplat, Mask, VL); 4915 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4916 DAG.getConstant(0, DL, XLenVT)); 4917 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4918 } 4919 4920 // Given a reduction op, this function returns the matching reduction opcode, 4921 // the vector SDValue and the scalar SDValue required to lower this to a 4922 // RISCVISD node. 4923 static std::tuple<unsigned, SDValue, SDValue> 4924 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4925 SDLoc DL(Op); 4926 auto Flags = Op->getFlags(); 4927 unsigned Opcode = Op.getOpcode(); 4928 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4929 switch (Opcode) { 4930 default: 4931 llvm_unreachable("Unhandled reduction"); 4932 case ISD::VECREDUCE_FADD: { 4933 // Use positive zero if we can. It is cheaper to materialize. 4934 SDValue Zero = 4935 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4936 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4937 } 4938 case ISD::VECREDUCE_SEQ_FADD: 4939 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4940 Op.getOperand(0)); 4941 case ISD::VECREDUCE_FMIN: 4942 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4943 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4944 case ISD::VECREDUCE_FMAX: 4945 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4946 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4947 } 4948 } 4949 4950 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4951 SelectionDAG &DAG) const { 4952 SDLoc DL(Op); 4953 MVT VecEltVT = Op.getSimpleValueType(); 4954 4955 unsigned RVVOpcode; 4956 SDValue VectorVal, ScalarVal; 4957 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4958 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4959 MVT VecVT = VectorVal.getSimpleValueType(); 4960 4961 MVT ContainerVT = VecVT; 4962 if (VecVT.isFixedLengthVector()) { 4963 ContainerVT = getContainerForFixedLengthVector(VecVT); 4964 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4965 } 4966 4967 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4968 MVT XLenVT = Subtarget.getXLenVT(); 4969 4970 SDValue Mask, VL; 4971 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4972 4973 SDValue ScalarSplat = lowerScalarSplat( 4974 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4975 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4976 VectorVal, ScalarSplat, Mask, VL); 4977 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4978 DAG.getConstant(0, DL, XLenVT)); 4979 } 4980 4981 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4982 switch (ISDOpcode) { 4983 default: 4984 llvm_unreachable("Unhandled reduction"); 4985 case ISD::VP_REDUCE_ADD: 4986 return RISCVISD::VECREDUCE_ADD_VL; 4987 case ISD::VP_REDUCE_UMAX: 4988 return RISCVISD::VECREDUCE_UMAX_VL; 4989 case ISD::VP_REDUCE_SMAX: 4990 return RISCVISD::VECREDUCE_SMAX_VL; 4991 case ISD::VP_REDUCE_UMIN: 4992 return RISCVISD::VECREDUCE_UMIN_VL; 4993 case ISD::VP_REDUCE_SMIN: 4994 return RISCVISD::VECREDUCE_SMIN_VL; 4995 case ISD::VP_REDUCE_AND: 4996 return RISCVISD::VECREDUCE_AND_VL; 4997 case ISD::VP_REDUCE_OR: 4998 return RISCVISD::VECREDUCE_OR_VL; 4999 case ISD::VP_REDUCE_XOR: 5000 return RISCVISD::VECREDUCE_XOR_VL; 5001 case ISD::VP_REDUCE_FADD: 5002 return RISCVISD::VECREDUCE_FADD_VL; 5003 case ISD::VP_REDUCE_SEQ_FADD: 5004 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5005 case ISD::VP_REDUCE_FMAX: 5006 return RISCVISD::VECREDUCE_FMAX_VL; 5007 case ISD::VP_REDUCE_FMIN: 5008 return RISCVISD::VECREDUCE_FMIN_VL; 5009 } 5010 } 5011 5012 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5013 SelectionDAG &DAG) const { 5014 SDLoc DL(Op); 5015 SDValue Vec = Op.getOperand(1); 5016 EVT VecEVT = Vec.getValueType(); 5017 5018 // TODO: The type may need to be widened rather than split. Or widened before 5019 // it can be split. 5020 if (!isTypeLegal(VecEVT)) 5021 return SDValue(); 5022 5023 MVT VecVT = VecEVT.getSimpleVT(); 5024 MVT VecEltVT = VecVT.getVectorElementType(); 5025 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5026 5027 MVT ContainerVT = VecVT; 5028 if (VecVT.isFixedLengthVector()) { 5029 ContainerVT = getContainerForFixedLengthVector(VecVT); 5030 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5031 } 5032 5033 SDValue VL = Op.getOperand(3); 5034 SDValue Mask = Op.getOperand(2); 5035 5036 MVT M1VT = getLMUL1VT(ContainerVT); 5037 MVT XLenVT = Subtarget.getXLenVT(); 5038 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5039 5040 SDValue StartSplat = 5041 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 5042 DL, DAG, Subtarget); 5043 SDValue Reduction = 5044 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5045 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5046 DAG.getConstant(0, DL, XLenVT)); 5047 if (!VecVT.isInteger()) 5048 return Elt0; 5049 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5050 } 5051 5052 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5053 SelectionDAG &DAG) const { 5054 SDValue Vec = Op.getOperand(0); 5055 SDValue SubVec = Op.getOperand(1); 5056 MVT VecVT = Vec.getSimpleValueType(); 5057 MVT SubVecVT = SubVec.getSimpleValueType(); 5058 5059 SDLoc DL(Op); 5060 MVT XLenVT = Subtarget.getXLenVT(); 5061 unsigned OrigIdx = Op.getConstantOperandVal(2); 5062 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5063 5064 // We don't have the ability to slide mask vectors up indexed by their i1 5065 // elements; the smallest we can do is i8. Often we are able to bitcast to 5066 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5067 // into a scalable one, we might not necessarily have enough scalable 5068 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5069 if (SubVecVT.getVectorElementType() == MVT::i1 && 5070 (OrigIdx != 0 || !Vec.isUndef())) { 5071 if (VecVT.getVectorMinNumElements() >= 8 && 5072 SubVecVT.getVectorMinNumElements() >= 8) { 5073 assert(OrigIdx % 8 == 0 && "Invalid index"); 5074 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5075 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5076 "Unexpected mask vector lowering"); 5077 OrigIdx /= 8; 5078 SubVecVT = 5079 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5080 SubVecVT.isScalableVector()); 5081 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5082 VecVT.isScalableVector()); 5083 Vec = DAG.getBitcast(VecVT, Vec); 5084 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5085 } else { 5086 // We can't slide this mask vector up indexed by its i1 elements. 5087 // This poses a problem when we wish to insert a scalable vector which 5088 // can't be re-expressed as a larger type. Just choose the slow path and 5089 // extend to a larger type, then truncate back down. 5090 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5091 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5092 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5093 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5094 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5095 Op.getOperand(2)); 5096 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5097 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5098 } 5099 } 5100 5101 // If the subvector vector is a fixed-length type, we cannot use subregister 5102 // manipulation to simplify the codegen; we don't know which register of a 5103 // LMUL group contains the specific subvector as we only know the minimum 5104 // register size. Therefore we must slide the vector group up the full 5105 // amount. 5106 if (SubVecVT.isFixedLengthVector()) { 5107 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5108 return Op; 5109 MVT ContainerVT = VecVT; 5110 if (VecVT.isFixedLengthVector()) { 5111 ContainerVT = getContainerForFixedLengthVector(VecVT); 5112 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5113 } 5114 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5115 DAG.getUNDEF(ContainerVT), SubVec, 5116 DAG.getConstant(0, DL, XLenVT)); 5117 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5118 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5119 return DAG.getBitcast(Op.getValueType(), SubVec); 5120 } 5121 SDValue Mask = 5122 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5123 // Set the vector length to only the number of elements we care about. Note 5124 // that for slideup this includes the offset. 5125 SDValue VL = 5126 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5127 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5128 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5129 SubVec, SlideupAmt, Mask, VL); 5130 if (VecVT.isFixedLengthVector()) 5131 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5132 return DAG.getBitcast(Op.getValueType(), Slideup); 5133 } 5134 5135 unsigned SubRegIdx, RemIdx; 5136 std::tie(SubRegIdx, RemIdx) = 5137 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5138 VecVT, SubVecVT, OrigIdx, TRI); 5139 5140 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5141 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5142 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5143 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5144 5145 // 1. If the Idx has been completely eliminated and this subvector's size is 5146 // a vector register or a multiple thereof, or the surrounding elements are 5147 // undef, then this is a subvector insert which naturally aligns to a vector 5148 // register. These can easily be handled using subregister manipulation. 5149 // 2. If the subvector is smaller than a vector register, then the insertion 5150 // must preserve the undisturbed elements of the register. We do this by 5151 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5152 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5153 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5154 // LMUL=1 type back into the larger vector (resolving to another subregister 5155 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5156 // to avoid allocating a large register group to hold our subvector. 5157 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5158 return Op; 5159 5160 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5161 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5162 // (in our case undisturbed). This means we can set up a subvector insertion 5163 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5164 // size of the subvector. 5165 MVT InterSubVT = VecVT; 5166 SDValue AlignedExtract = Vec; 5167 unsigned AlignedIdx = OrigIdx - RemIdx; 5168 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5169 InterSubVT = getLMUL1VT(VecVT); 5170 // Extract a subvector equal to the nearest full vector register type. This 5171 // should resolve to a EXTRACT_SUBREG instruction. 5172 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5173 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5174 } 5175 5176 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5177 // For scalable vectors this must be further multiplied by vscale. 5178 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5179 5180 SDValue Mask, VL; 5181 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5182 5183 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5184 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5185 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5186 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5187 5188 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5189 DAG.getUNDEF(InterSubVT), SubVec, 5190 DAG.getConstant(0, DL, XLenVT)); 5191 5192 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5193 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5194 5195 // If required, insert this subvector back into the correct vector register. 5196 // This should resolve to an INSERT_SUBREG instruction. 5197 if (VecVT.bitsGT(InterSubVT)) 5198 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5199 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5200 5201 // We might have bitcast from a mask type: cast back to the original type if 5202 // required. 5203 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5204 } 5205 5206 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5207 SelectionDAG &DAG) const { 5208 SDValue Vec = Op.getOperand(0); 5209 MVT SubVecVT = Op.getSimpleValueType(); 5210 MVT VecVT = Vec.getSimpleValueType(); 5211 5212 SDLoc DL(Op); 5213 MVT XLenVT = Subtarget.getXLenVT(); 5214 unsigned OrigIdx = Op.getConstantOperandVal(1); 5215 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5216 5217 // We don't have the ability to slide mask vectors down indexed by their i1 5218 // elements; the smallest we can do is i8. Often we are able to bitcast to 5219 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5220 // from a scalable one, we might not necessarily have enough scalable 5221 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5222 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5223 if (VecVT.getVectorMinNumElements() >= 8 && 5224 SubVecVT.getVectorMinNumElements() >= 8) { 5225 assert(OrigIdx % 8 == 0 && "Invalid index"); 5226 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5227 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5228 "Unexpected mask vector lowering"); 5229 OrigIdx /= 8; 5230 SubVecVT = 5231 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5232 SubVecVT.isScalableVector()); 5233 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5234 VecVT.isScalableVector()); 5235 Vec = DAG.getBitcast(VecVT, Vec); 5236 } else { 5237 // We can't slide this mask vector down, indexed by its i1 elements. 5238 // This poses a problem when we wish to extract a scalable vector which 5239 // can't be re-expressed as a larger type. Just choose the slow path and 5240 // extend to a larger type, then truncate back down. 5241 // TODO: We could probably improve this when extracting certain fixed 5242 // from fixed, where we can extract as i8 and shift the correct element 5243 // right to reach the desired subvector? 5244 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5245 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5246 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5247 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5248 Op.getOperand(1)); 5249 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5250 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5251 } 5252 } 5253 5254 // If the subvector vector is a fixed-length type, we cannot use subregister 5255 // manipulation to simplify the codegen; we don't know which register of a 5256 // LMUL group contains the specific subvector as we only know the minimum 5257 // register size. Therefore we must slide the vector group down the full 5258 // amount. 5259 if (SubVecVT.isFixedLengthVector()) { 5260 // With an index of 0 this is a cast-like subvector, which can be performed 5261 // with subregister operations. 5262 if (OrigIdx == 0) 5263 return Op; 5264 MVT ContainerVT = VecVT; 5265 if (VecVT.isFixedLengthVector()) { 5266 ContainerVT = getContainerForFixedLengthVector(VecVT); 5267 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5268 } 5269 SDValue Mask = 5270 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5271 // Set the vector length to only the number of elements we care about. This 5272 // avoids sliding down elements we're going to discard straight away. 5273 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5274 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5275 SDValue Slidedown = 5276 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5277 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5278 // Now we can use a cast-like subvector extract to get the result. 5279 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5280 DAG.getConstant(0, DL, XLenVT)); 5281 return DAG.getBitcast(Op.getValueType(), Slidedown); 5282 } 5283 5284 unsigned SubRegIdx, RemIdx; 5285 std::tie(SubRegIdx, RemIdx) = 5286 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5287 VecVT, SubVecVT, OrigIdx, TRI); 5288 5289 // If the Idx has been completely eliminated then this is a subvector extract 5290 // which naturally aligns to a vector register. These can easily be handled 5291 // using subregister manipulation. 5292 if (RemIdx == 0) 5293 return Op; 5294 5295 // Else we must shift our vector register directly to extract the subvector. 5296 // Do this using VSLIDEDOWN. 5297 5298 // If the vector type is an LMUL-group type, extract a subvector equal to the 5299 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5300 // instruction. 5301 MVT InterSubVT = VecVT; 5302 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5303 InterSubVT = getLMUL1VT(VecVT); 5304 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5305 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5306 } 5307 5308 // Slide this vector register down by the desired number of elements in order 5309 // to place the desired subvector starting at element 0. 5310 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5311 // For scalable vectors this must be further multiplied by vscale. 5312 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5313 5314 SDValue Mask, VL; 5315 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5316 SDValue Slidedown = 5317 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5318 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5319 5320 // Now the vector is in the right position, extract our final subvector. This 5321 // should resolve to a COPY. 5322 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5323 DAG.getConstant(0, DL, XLenVT)); 5324 5325 // We might have bitcast from a mask type: cast back to the original type if 5326 // required. 5327 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5328 } 5329 5330 // Lower step_vector to the vid instruction. Any non-identity step value must 5331 // be accounted for my manual expansion. 5332 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5333 SelectionDAG &DAG) const { 5334 SDLoc DL(Op); 5335 MVT VT = Op.getSimpleValueType(); 5336 MVT XLenVT = Subtarget.getXLenVT(); 5337 SDValue Mask, VL; 5338 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5339 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5340 uint64_t StepValImm = Op.getConstantOperandVal(0); 5341 if (StepValImm != 1) { 5342 if (isPowerOf2_64(StepValImm)) { 5343 SDValue StepVal = 5344 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5345 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5346 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5347 } else { 5348 SDValue StepVal = lowerScalarSplat( 5349 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5350 DL, DAG, Subtarget); 5351 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5352 } 5353 } 5354 return StepVec; 5355 } 5356 5357 // Implement vector_reverse using vrgather.vv with indices determined by 5358 // subtracting the id of each element from (VLMAX-1). This will convert 5359 // the indices like so: 5360 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5361 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5362 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5363 SelectionDAG &DAG) const { 5364 SDLoc DL(Op); 5365 MVT VecVT = Op.getSimpleValueType(); 5366 unsigned EltSize = VecVT.getScalarSizeInBits(); 5367 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5368 5369 unsigned MaxVLMAX = 0; 5370 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5371 if (VectorBitsMax != 0) 5372 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5373 5374 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5375 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5376 5377 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5378 // to use vrgatherei16.vv. 5379 // TODO: It's also possible to use vrgatherei16.vv for other types to 5380 // decrease register width for the index calculation. 5381 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5382 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5383 // Reverse each half, then reassemble them in reverse order. 5384 // NOTE: It's also possible that after splitting that VLMAX no longer 5385 // requires vrgatherei16.vv. 5386 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5387 SDValue Lo, Hi; 5388 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5389 EVT LoVT, HiVT; 5390 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5391 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5392 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5393 // Reassemble the low and high pieces reversed. 5394 // FIXME: This is a CONCAT_VECTORS. 5395 SDValue Res = 5396 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5397 DAG.getIntPtrConstant(0, DL)); 5398 return DAG.getNode( 5399 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5400 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5401 } 5402 5403 // Just promote the int type to i16 which will double the LMUL. 5404 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5405 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5406 } 5407 5408 MVT XLenVT = Subtarget.getXLenVT(); 5409 SDValue Mask, VL; 5410 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5411 5412 // Calculate VLMAX-1 for the desired SEW. 5413 unsigned MinElts = VecVT.getVectorMinNumElements(); 5414 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5415 DAG.getConstant(MinElts, DL, XLenVT)); 5416 SDValue VLMinus1 = 5417 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5418 5419 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5420 bool IsRV32E64 = 5421 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5422 SDValue SplatVL; 5423 if (!IsRV32E64) 5424 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5425 else 5426 SplatVL = 5427 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, VLMinus1, 5428 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5429 5430 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5431 SDValue Indices = 5432 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5433 5434 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5435 } 5436 5437 SDValue 5438 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5439 SelectionDAG &DAG) const { 5440 SDLoc DL(Op); 5441 auto *Load = cast<LoadSDNode>(Op); 5442 5443 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5444 Load->getMemoryVT(), 5445 *Load->getMemOperand()) && 5446 "Expecting a correctly-aligned load"); 5447 5448 MVT VT = Op.getSimpleValueType(); 5449 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5450 5451 SDValue VL = 5452 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5453 5454 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5455 SDValue NewLoad = DAG.getMemIntrinsicNode( 5456 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5457 Load->getMemoryVT(), Load->getMemOperand()); 5458 5459 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5460 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5461 } 5462 5463 SDValue 5464 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5465 SelectionDAG &DAG) const { 5466 SDLoc DL(Op); 5467 auto *Store = cast<StoreSDNode>(Op); 5468 5469 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5470 Store->getMemoryVT(), 5471 *Store->getMemOperand()) && 5472 "Expecting a correctly-aligned store"); 5473 5474 SDValue StoreVal = Store->getValue(); 5475 MVT VT = StoreVal.getSimpleValueType(); 5476 5477 // If the size less than a byte, we need to pad with zeros to make a byte. 5478 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5479 VT = MVT::v8i1; 5480 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5481 DAG.getConstant(0, DL, VT), StoreVal, 5482 DAG.getIntPtrConstant(0, DL)); 5483 } 5484 5485 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5486 5487 SDValue VL = 5488 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5489 5490 SDValue NewValue = 5491 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5492 return DAG.getMemIntrinsicNode( 5493 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5494 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5495 Store->getMemoryVT(), Store->getMemOperand()); 5496 } 5497 5498 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5499 SelectionDAG &DAG) const { 5500 SDLoc DL(Op); 5501 MVT VT = Op.getSimpleValueType(); 5502 5503 const auto *MemSD = cast<MemSDNode>(Op); 5504 EVT MemVT = MemSD->getMemoryVT(); 5505 MachineMemOperand *MMO = MemSD->getMemOperand(); 5506 SDValue Chain = MemSD->getChain(); 5507 SDValue BasePtr = MemSD->getBasePtr(); 5508 5509 SDValue Mask, PassThru, VL; 5510 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5511 Mask = VPLoad->getMask(); 5512 PassThru = DAG.getUNDEF(VT); 5513 VL = VPLoad->getVectorLength(); 5514 } else { 5515 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5516 Mask = MLoad->getMask(); 5517 PassThru = MLoad->getPassThru(); 5518 } 5519 5520 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5521 5522 MVT XLenVT = Subtarget.getXLenVT(); 5523 5524 MVT ContainerVT = VT; 5525 if (VT.isFixedLengthVector()) { 5526 ContainerVT = getContainerForFixedLengthVector(VT); 5527 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5528 if (!IsUnmasked) { 5529 MVT MaskVT = 5530 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5531 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5532 } 5533 } 5534 5535 if (!VL) 5536 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5537 5538 unsigned IntID = 5539 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5540 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5541 if (IsUnmasked) 5542 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5543 else 5544 Ops.push_back(PassThru); 5545 Ops.push_back(BasePtr); 5546 if (!IsUnmasked) 5547 Ops.push_back(Mask); 5548 Ops.push_back(VL); 5549 if (!IsUnmasked) 5550 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5551 5552 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5553 5554 SDValue Result = 5555 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5556 Chain = Result.getValue(1); 5557 5558 if (VT.isFixedLengthVector()) 5559 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5560 5561 return DAG.getMergeValues({Result, Chain}, DL); 5562 } 5563 5564 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5565 SelectionDAG &DAG) const { 5566 SDLoc DL(Op); 5567 5568 const auto *MemSD = cast<MemSDNode>(Op); 5569 EVT MemVT = MemSD->getMemoryVT(); 5570 MachineMemOperand *MMO = MemSD->getMemOperand(); 5571 SDValue Chain = MemSD->getChain(); 5572 SDValue BasePtr = MemSD->getBasePtr(); 5573 SDValue Val, Mask, VL; 5574 5575 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5576 Val = VPStore->getValue(); 5577 Mask = VPStore->getMask(); 5578 VL = VPStore->getVectorLength(); 5579 } else { 5580 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5581 Val = MStore->getValue(); 5582 Mask = MStore->getMask(); 5583 } 5584 5585 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5586 5587 MVT VT = Val.getSimpleValueType(); 5588 MVT XLenVT = Subtarget.getXLenVT(); 5589 5590 MVT ContainerVT = VT; 5591 if (VT.isFixedLengthVector()) { 5592 ContainerVT = getContainerForFixedLengthVector(VT); 5593 5594 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5595 if (!IsUnmasked) { 5596 MVT MaskVT = 5597 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5598 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5599 } 5600 } 5601 5602 if (!VL) 5603 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5604 5605 unsigned IntID = 5606 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5607 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5608 Ops.push_back(Val); 5609 Ops.push_back(BasePtr); 5610 if (!IsUnmasked) 5611 Ops.push_back(Mask); 5612 Ops.push_back(VL); 5613 5614 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5615 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5616 } 5617 5618 SDValue 5619 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5620 SelectionDAG &DAG) const { 5621 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5622 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5623 5624 MVT VT = Op.getSimpleValueType(); 5625 5626 SDValue Op1 = 5627 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5628 SDValue Op2 = 5629 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5630 5631 SDLoc DL(Op); 5632 SDValue VL = 5633 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5634 5635 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5636 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5637 5638 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5639 Op.getOperand(2), Mask, VL); 5640 5641 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5642 } 5643 5644 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5645 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5646 MVT VT = Op.getSimpleValueType(); 5647 5648 if (VT.getVectorElementType() == MVT::i1) 5649 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5650 5651 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5652 } 5653 5654 SDValue 5655 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5656 SelectionDAG &DAG) const { 5657 unsigned Opc; 5658 switch (Op.getOpcode()) { 5659 default: llvm_unreachable("Unexpected opcode!"); 5660 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5661 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5662 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5663 } 5664 5665 return lowerToScalableOp(Op, DAG, Opc); 5666 } 5667 5668 // Lower vector ABS to smax(X, sub(0, X)). 5669 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5670 SDLoc DL(Op); 5671 MVT VT = Op.getSimpleValueType(); 5672 SDValue X = Op.getOperand(0); 5673 5674 assert(VT.isFixedLengthVector() && "Unexpected type"); 5675 5676 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5677 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5678 5679 SDValue Mask, VL; 5680 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5681 5682 SDValue SplatZero = 5683 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5684 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5685 SDValue NegX = 5686 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5687 SDValue Max = 5688 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5689 5690 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5691 } 5692 5693 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5694 SDValue Op, SelectionDAG &DAG) const { 5695 SDLoc DL(Op); 5696 MVT VT = Op.getSimpleValueType(); 5697 SDValue Mag = Op.getOperand(0); 5698 SDValue Sign = Op.getOperand(1); 5699 assert(Mag.getValueType() == Sign.getValueType() && 5700 "Can only handle COPYSIGN with matching types."); 5701 5702 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5703 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5704 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5705 5706 SDValue Mask, VL; 5707 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5708 5709 SDValue CopySign = 5710 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5711 5712 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5713 } 5714 5715 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5716 SDValue Op, SelectionDAG &DAG) const { 5717 MVT VT = Op.getSimpleValueType(); 5718 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5719 5720 MVT I1ContainerVT = 5721 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5722 5723 SDValue CC = 5724 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5725 SDValue Op1 = 5726 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5727 SDValue Op2 = 5728 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5729 5730 SDLoc DL(Op); 5731 SDValue Mask, VL; 5732 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5733 5734 SDValue Select = 5735 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5736 5737 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5738 } 5739 5740 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5741 unsigned NewOpc, 5742 bool HasMask) const { 5743 MVT VT = Op.getSimpleValueType(); 5744 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5745 5746 // Create list of operands by converting existing ones to scalable types. 5747 SmallVector<SDValue, 6> Ops; 5748 for (const SDValue &V : Op->op_values()) { 5749 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5750 5751 // Pass through non-vector operands. 5752 if (!V.getValueType().isVector()) { 5753 Ops.push_back(V); 5754 continue; 5755 } 5756 5757 // "cast" fixed length vector to a scalable vector. 5758 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5759 "Only fixed length vectors are supported!"); 5760 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5761 } 5762 5763 SDLoc DL(Op); 5764 SDValue Mask, VL; 5765 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5766 if (HasMask) 5767 Ops.push_back(Mask); 5768 Ops.push_back(VL); 5769 5770 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5771 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5772 } 5773 5774 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5775 // * Operands of each node are assumed to be in the same order. 5776 // * The EVL operand is promoted from i32 to i64 on RV64. 5777 // * Fixed-length vectors are converted to their scalable-vector container 5778 // types. 5779 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5780 unsigned RISCVISDOpc) const { 5781 SDLoc DL(Op); 5782 MVT VT = Op.getSimpleValueType(); 5783 SmallVector<SDValue, 4> Ops; 5784 5785 for (const auto &OpIdx : enumerate(Op->ops())) { 5786 SDValue V = OpIdx.value(); 5787 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5788 // Pass through operands which aren't fixed-length vectors. 5789 if (!V.getValueType().isFixedLengthVector()) { 5790 Ops.push_back(V); 5791 continue; 5792 } 5793 // "cast" fixed length vector to a scalable vector. 5794 MVT OpVT = V.getSimpleValueType(); 5795 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5796 assert(useRVVForFixedLengthVectorVT(OpVT) && 5797 "Only fixed length vectors are supported!"); 5798 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5799 } 5800 5801 if (!VT.isFixedLengthVector()) 5802 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5803 5804 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5805 5806 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5807 5808 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5809 } 5810 5811 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5812 unsigned MaskOpc, 5813 unsigned VecOpc) const { 5814 MVT VT = Op.getSimpleValueType(); 5815 if (VT.getVectorElementType() != MVT::i1) 5816 return lowerVPOp(Op, DAG, VecOpc); 5817 5818 // It is safe to drop mask parameter as masked-off elements are undef. 5819 SDValue Op1 = Op->getOperand(0); 5820 SDValue Op2 = Op->getOperand(1); 5821 SDValue VL = Op->getOperand(3); 5822 5823 MVT ContainerVT = VT; 5824 const bool IsFixed = VT.isFixedLengthVector(); 5825 if (IsFixed) { 5826 ContainerVT = getContainerForFixedLengthVector(VT); 5827 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5828 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5829 } 5830 5831 SDLoc DL(Op); 5832 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5833 if (!IsFixed) 5834 return Val; 5835 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5836 } 5837 5838 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5839 // matched to a RVV indexed load. The RVV indexed load instructions only 5840 // support the "unsigned unscaled" addressing mode; indices are implicitly 5841 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5842 // signed or scaled indexing is extended to the XLEN value type and scaled 5843 // accordingly. 5844 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5845 SelectionDAG &DAG) const { 5846 SDLoc DL(Op); 5847 MVT VT = Op.getSimpleValueType(); 5848 5849 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5850 EVT MemVT = MemSD->getMemoryVT(); 5851 MachineMemOperand *MMO = MemSD->getMemOperand(); 5852 SDValue Chain = MemSD->getChain(); 5853 SDValue BasePtr = MemSD->getBasePtr(); 5854 5855 ISD::LoadExtType LoadExtType; 5856 SDValue Index, Mask, PassThru, VL; 5857 5858 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5859 Index = VPGN->getIndex(); 5860 Mask = VPGN->getMask(); 5861 PassThru = DAG.getUNDEF(VT); 5862 VL = VPGN->getVectorLength(); 5863 // VP doesn't support extending loads. 5864 LoadExtType = ISD::NON_EXTLOAD; 5865 } else { 5866 // Else it must be a MGATHER. 5867 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5868 Index = MGN->getIndex(); 5869 Mask = MGN->getMask(); 5870 PassThru = MGN->getPassThru(); 5871 LoadExtType = MGN->getExtensionType(); 5872 } 5873 5874 MVT IndexVT = Index.getSimpleValueType(); 5875 MVT XLenVT = Subtarget.getXLenVT(); 5876 5877 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5878 "Unexpected VTs!"); 5879 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5880 // Targets have to explicitly opt-in for extending vector loads. 5881 assert(LoadExtType == ISD::NON_EXTLOAD && 5882 "Unexpected extending MGATHER/VP_GATHER"); 5883 (void)LoadExtType; 5884 5885 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5886 // the selection of the masked intrinsics doesn't do this for us. 5887 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5888 5889 MVT ContainerVT = VT; 5890 if (VT.isFixedLengthVector()) { 5891 // We need to use the larger of the result and index type to determine the 5892 // scalable type to use so we don't increase LMUL for any operand/result. 5893 if (VT.bitsGE(IndexVT)) { 5894 ContainerVT = getContainerForFixedLengthVector(VT); 5895 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5896 ContainerVT.getVectorElementCount()); 5897 } else { 5898 IndexVT = getContainerForFixedLengthVector(IndexVT); 5899 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5900 IndexVT.getVectorElementCount()); 5901 } 5902 5903 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5904 5905 if (!IsUnmasked) { 5906 MVT MaskVT = 5907 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5908 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5909 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5910 } 5911 } 5912 5913 if (!VL) 5914 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5915 5916 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5917 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5918 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 5919 VL); 5920 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 5921 TrueMask, VL); 5922 } 5923 5924 unsigned IntID = 5925 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5926 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5927 if (IsUnmasked) 5928 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5929 else 5930 Ops.push_back(PassThru); 5931 Ops.push_back(BasePtr); 5932 Ops.push_back(Index); 5933 if (!IsUnmasked) 5934 Ops.push_back(Mask); 5935 Ops.push_back(VL); 5936 if (!IsUnmasked) 5937 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5938 5939 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5940 SDValue Result = 5941 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5942 Chain = Result.getValue(1); 5943 5944 if (VT.isFixedLengthVector()) 5945 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5946 5947 return DAG.getMergeValues({Result, Chain}, DL); 5948 } 5949 5950 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5951 // matched to a RVV indexed store. The RVV indexed store instructions only 5952 // support the "unsigned unscaled" addressing mode; indices are implicitly 5953 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5954 // signed or scaled indexing is extended to the XLEN value type and scaled 5955 // accordingly. 5956 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5957 SelectionDAG &DAG) const { 5958 SDLoc DL(Op); 5959 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5960 EVT MemVT = MemSD->getMemoryVT(); 5961 MachineMemOperand *MMO = MemSD->getMemOperand(); 5962 SDValue Chain = MemSD->getChain(); 5963 SDValue BasePtr = MemSD->getBasePtr(); 5964 5965 bool IsTruncatingStore = false; 5966 SDValue Index, Mask, Val, VL; 5967 5968 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5969 Index = VPSN->getIndex(); 5970 Mask = VPSN->getMask(); 5971 Val = VPSN->getValue(); 5972 VL = VPSN->getVectorLength(); 5973 // VP doesn't support truncating stores. 5974 IsTruncatingStore = false; 5975 } else { 5976 // Else it must be a MSCATTER. 5977 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5978 Index = MSN->getIndex(); 5979 Mask = MSN->getMask(); 5980 Val = MSN->getValue(); 5981 IsTruncatingStore = MSN->isTruncatingStore(); 5982 } 5983 5984 MVT VT = Val.getSimpleValueType(); 5985 MVT IndexVT = Index.getSimpleValueType(); 5986 MVT XLenVT = Subtarget.getXLenVT(); 5987 5988 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5989 "Unexpected VTs!"); 5990 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5991 // Targets have to explicitly opt-in for extending vector loads and 5992 // truncating vector stores. 5993 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5994 (void)IsTruncatingStore; 5995 5996 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5997 // the selection of the masked intrinsics doesn't do this for us. 5998 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5999 6000 MVT ContainerVT = VT; 6001 if (VT.isFixedLengthVector()) { 6002 // We need to use the larger of the value and index type to determine the 6003 // scalable type to use so we don't increase LMUL for any operand/result. 6004 if (VT.bitsGE(IndexVT)) { 6005 ContainerVT = getContainerForFixedLengthVector(VT); 6006 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6007 ContainerVT.getVectorElementCount()); 6008 } else { 6009 IndexVT = getContainerForFixedLengthVector(IndexVT); 6010 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6011 IndexVT.getVectorElementCount()); 6012 } 6013 6014 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6015 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6016 6017 if (!IsUnmasked) { 6018 MVT MaskVT = 6019 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6020 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6021 } 6022 } 6023 6024 if (!VL) 6025 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6026 6027 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6028 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6029 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6030 VL); 6031 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6032 TrueMask, VL); 6033 } 6034 6035 unsigned IntID = 6036 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6037 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6038 Ops.push_back(Val); 6039 Ops.push_back(BasePtr); 6040 Ops.push_back(Index); 6041 if (!IsUnmasked) 6042 Ops.push_back(Mask); 6043 Ops.push_back(VL); 6044 6045 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6046 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6047 } 6048 6049 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6050 SelectionDAG &DAG) const { 6051 const MVT XLenVT = Subtarget.getXLenVT(); 6052 SDLoc DL(Op); 6053 SDValue Chain = Op->getOperand(0); 6054 SDValue SysRegNo = DAG.getTargetConstant( 6055 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6056 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6057 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6058 6059 // Encoding used for rounding mode in RISCV differs from that used in 6060 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6061 // table, which consists of a sequence of 4-bit fields, each representing 6062 // corresponding FLT_ROUNDS mode. 6063 static const int Table = 6064 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6065 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6066 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6067 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6068 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6069 6070 SDValue Shift = 6071 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6072 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6073 DAG.getConstant(Table, DL, XLenVT), Shift); 6074 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6075 DAG.getConstant(7, DL, XLenVT)); 6076 6077 return DAG.getMergeValues({Masked, Chain}, DL); 6078 } 6079 6080 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6081 SelectionDAG &DAG) const { 6082 const MVT XLenVT = Subtarget.getXLenVT(); 6083 SDLoc DL(Op); 6084 SDValue Chain = Op->getOperand(0); 6085 SDValue RMValue = Op->getOperand(1); 6086 SDValue SysRegNo = DAG.getTargetConstant( 6087 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6088 6089 // Encoding used for rounding mode in RISCV differs from that used in 6090 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6091 // a table, which consists of a sequence of 4-bit fields, each representing 6092 // corresponding RISCV mode. 6093 static const unsigned Table = 6094 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6095 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6096 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6097 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6098 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6099 6100 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6101 DAG.getConstant(2, DL, XLenVT)); 6102 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6103 DAG.getConstant(Table, DL, XLenVT), Shift); 6104 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6105 DAG.getConstant(0x7, DL, XLenVT)); 6106 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6107 RMValue); 6108 } 6109 6110 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6111 switch (IntNo) { 6112 default: 6113 llvm_unreachable("Unexpected Intrinsic"); 6114 case Intrinsic::riscv_grev: 6115 return RISCVISD::GREVW; 6116 case Intrinsic::riscv_gorc: 6117 return RISCVISD::GORCW; 6118 case Intrinsic::riscv_bcompress: 6119 return RISCVISD::BCOMPRESSW; 6120 case Intrinsic::riscv_bdecompress: 6121 return RISCVISD::BDECOMPRESSW; 6122 case Intrinsic::riscv_bfp: 6123 return RISCVISD::BFPW; 6124 case Intrinsic::riscv_fsl: 6125 return RISCVISD::FSLW; 6126 case Intrinsic::riscv_fsr: 6127 return RISCVISD::FSRW; 6128 } 6129 } 6130 6131 // Converts the given intrinsic to a i64 operation with any extension. 6132 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6133 unsigned IntNo) { 6134 SDLoc DL(N); 6135 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6136 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6137 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6138 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6139 // ReplaceNodeResults requires we maintain the same type for the return value. 6140 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6141 } 6142 6143 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6144 // form of the given Opcode. 6145 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6146 switch (Opcode) { 6147 default: 6148 llvm_unreachable("Unexpected opcode"); 6149 case ISD::SHL: 6150 return RISCVISD::SLLW; 6151 case ISD::SRA: 6152 return RISCVISD::SRAW; 6153 case ISD::SRL: 6154 return RISCVISD::SRLW; 6155 case ISD::SDIV: 6156 return RISCVISD::DIVW; 6157 case ISD::UDIV: 6158 return RISCVISD::DIVUW; 6159 case ISD::UREM: 6160 return RISCVISD::REMUW; 6161 case ISD::ROTL: 6162 return RISCVISD::ROLW; 6163 case ISD::ROTR: 6164 return RISCVISD::RORW; 6165 case RISCVISD::GREV: 6166 return RISCVISD::GREVW; 6167 case RISCVISD::GORC: 6168 return RISCVISD::GORCW; 6169 } 6170 } 6171 6172 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6173 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6174 // otherwise be promoted to i64, making it difficult to select the 6175 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6176 // type i8/i16/i32 is lost. 6177 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6178 unsigned ExtOpc = ISD::ANY_EXTEND) { 6179 SDLoc DL(N); 6180 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6181 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6182 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6183 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6184 // ReplaceNodeResults requires we maintain the same type for the return value. 6185 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6186 } 6187 6188 // Converts the given 32-bit operation to a i64 operation with signed extension 6189 // semantic to reduce the signed extension instructions. 6190 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6191 SDLoc DL(N); 6192 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6193 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6194 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6195 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6196 DAG.getValueType(MVT::i32)); 6197 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6198 } 6199 6200 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6201 SmallVectorImpl<SDValue> &Results, 6202 SelectionDAG &DAG) const { 6203 SDLoc DL(N); 6204 switch (N->getOpcode()) { 6205 default: 6206 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6207 case ISD::STRICT_FP_TO_SINT: 6208 case ISD::STRICT_FP_TO_UINT: 6209 case ISD::FP_TO_SINT: 6210 case ISD::FP_TO_UINT: { 6211 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6212 "Unexpected custom legalisation"); 6213 bool IsStrict = N->isStrictFPOpcode(); 6214 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6215 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6216 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6217 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6218 TargetLowering::TypeSoftenFloat) { 6219 if (!isTypeLegal(Op0.getValueType())) 6220 return; 6221 if (IsStrict) { 6222 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6223 : RISCVISD::STRICT_FCVT_WU_RV64; 6224 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6225 SDValue Res = DAG.getNode( 6226 Opc, DL, VTs, N->getOperand(0), Op0, 6227 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6228 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6229 Results.push_back(Res.getValue(1)); 6230 return; 6231 } 6232 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6233 SDValue Res = 6234 DAG.getNode(Opc, DL, MVT::i64, Op0, 6235 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6236 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6237 return; 6238 } 6239 // If the FP type needs to be softened, emit a library call using the 'si' 6240 // version. If we left it to default legalization we'd end up with 'di'. If 6241 // the FP type doesn't need to be softened just let generic type 6242 // legalization promote the result type. 6243 RTLIB::Libcall LC; 6244 if (IsSigned) 6245 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6246 else 6247 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6248 MakeLibCallOptions CallOptions; 6249 EVT OpVT = Op0.getValueType(); 6250 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6251 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6252 SDValue Result; 6253 std::tie(Result, Chain) = 6254 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6255 Results.push_back(Result); 6256 if (IsStrict) 6257 Results.push_back(Chain); 6258 break; 6259 } 6260 case ISD::READCYCLECOUNTER: { 6261 assert(!Subtarget.is64Bit() && 6262 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6263 6264 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6265 SDValue RCW = 6266 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6267 6268 Results.push_back( 6269 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6270 Results.push_back(RCW.getValue(2)); 6271 break; 6272 } 6273 case ISD::MUL: { 6274 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6275 unsigned XLen = Subtarget.getXLen(); 6276 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6277 if (Size > XLen) { 6278 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6279 SDValue LHS = N->getOperand(0); 6280 SDValue RHS = N->getOperand(1); 6281 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6282 6283 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6284 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6285 // We need exactly one side to be unsigned. 6286 if (LHSIsU == RHSIsU) 6287 return; 6288 6289 auto MakeMULPair = [&](SDValue S, SDValue U) { 6290 MVT XLenVT = Subtarget.getXLenVT(); 6291 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6292 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6293 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6294 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6295 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6296 }; 6297 6298 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6299 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6300 6301 // The other operand should be signed, but still prefer MULH when 6302 // possible. 6303 if (RHSIsU && LHSIsS && !RHSIsS) 6304 Results.push_back(MakeMULPair(LHS, RHS)); 6305 else if (LHSIsU && RHSIsS && !LHSIsS) 6306 Results.push_back(MakeMULPair(RHS, LHS)); 6307 6308 return; 6309 } 6310 LLVM_FALLTHROUGH; 6311 } 6312 case ISD::ADD: 6313 case ISD::SUB: 6314 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6315 "Unexpected custom legalisation"); 6316 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6317 break; 6318 case ISD::SHL: 6319 case ISD::SRA: 6320 case ISD::SRL: 6321 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6322 "Unexpected custom legalisation"); 6323 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6324 Results.push_back(customLegalizeToWOp(N, DAG)); 6325 break; 6326 } 6327 6328 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6329 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6330 // shift amount. 6331 if (N->getOpcode() == ISD::SHL) { 6332 SDLoc DL(N); 6333 SDValue NewOp0 = 6334 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6335 SDValue NewOp1 = 6336 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6337 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6338 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6339 DAG.getValueType(MVT::i32)); 6340 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6341 } 6342 6343 break; 6344 case ISD::ROTL: 6345 case ISD::ROTR: 6346 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6347 "Unexpected custom legalisation"); 6348 Results.push_back(customLegalizeToWOp(N, DAG)); 6349 break; 6350 case ISD::CTTZ: 6351 case ISD::CTTZ_ZERO_UNDEF: 6352 case ISD::CTLZ: 6353 case ISD::CTLZ_ZERO_UNDEF: { 6354 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6355 "Unexpected custom legalisation"); 6356 6357 SDValue NewOp0 = 6358 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6359 bool IsCTZ = 6360 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6361 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6362 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6363 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6364 return; 6365 } 6366 case ISD::SDIV: 6367 case ISD::UDIV: 6368 case ISD::UREM: { 6369 MVT VT = N->getSimpleValueType(0); 6370 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6371 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6372 "Unexpected custom legalisation"); 6373 // Don't promote division/remainder by constant since we should expand those 6374 // to multiply by magic constant. 6375 // FIXME: What if the expansion is disabled for minsize. 6376 if (N->getOperand(1).getOpcode() == ISD::Constant) 6377 return; 6378 6379 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6380 // the upper 32 bits. For other types we need to sign or zero extend 6381 // based on the opcode. 6382 unsigned ExtOpc = ISD::ANY_EXTEND; 6383 if (VT != MVT::i32) 6384 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6385 : ISD::ZERO_EXTEND; 6386 6387 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6388 break; 6389 } 6390 case ISD::UADDO: 6391 case ISD::USUBO: { 6392 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6393 "Unexpected custom legalisation"); 6394 bool IsAdd = N->getOpcode() == ISD::UADDO; 6395 // Create an ADDW or SUBW. 6396 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6397 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6398 SDValue Res = 6399 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6400 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6401 DAG.getValueType(MVT::i32)); 6402 6403 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6404 // Since the inputs are sign extended from i32, this is equivalent to 6405 // comparing the lower 32 bits. 6406 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6407 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6408 IsAdd ? ISD::SETULT : ISD::SETUGT); 6409 6410 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6411 Results.push_back(Overflow); 6412 return; 6413 } 6414 case ISD::UADDSAT: 6415 case ISD::USUBSAT: { 6416 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6417 "Unexpected custom legalisation"); 6418 if (Subtarget.hasStdExtZbb()) { 6419 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6420 // sign extend allows overflow of the lower 32 bits to be detected on 6421 // the promoted size. 6422 SDValue LHS = 6423 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6424 SDValue RHS = 6425 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6426 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6427 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6428 return; 6429 } 6430 6431 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6432 // promotion for UADDO/USUBO. 6433 Results.push_back(expandAddSubSat(N, DAG)); 6434 return; 6435 } 6436 case ISD::BITCAST: { 6437 EVT VT = N->getValueType(0); 6438 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6439 SDValue Op0 = N->getOperand(0); 6440 EVT Op0VT = Op0.getValueType(); 6441 MVT XLenVT = Subtarget.getXLenVT(); 6442 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6443 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6444 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6445 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6446 Subtarget.hasStdExtF()) { 6447 SDValue FPConv = 6448 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6449 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6450 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6451 isTypeLegal(Op0VT)) { 6452 // Custom-legalize bitcasts from fixed-length vector types to illegal 6453 // scalar types in order to improve codegen. Bitcast the vector to a 6454 // one-element vector type whose element type is the same as the result 6455 // type, and extract the first element. 6456 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6457 if (isTypeLegal(BVT)) { 6458 SDValue BVec = DAG.getBitcast(BVT, Op0); 6459 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6460 DAG.getConstant(0, DL, XLenVT))); 6461 } 6462 } 6463 break; 6464 } 6465 case RISCVISD::GREV: 6466 case RISCVISD::GORC: { 6467 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6468 "Unexpected custom legalisation"); 6469 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6470 // This is similar to customLegalizeToWOp, except that we pass the second 6471 // operand (a TargetConstant) straight through: it is already of type 6472 // XLenVT. 6473 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6474 SDValue NewOp0 = 6475 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6476 SDValue NewOp1 = 6477 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6478 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6479 // ReplaceNodeResults requires we maintain the same type for the return 6480 // value. 6481 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6482 break; 6483 } 6484 case RISCVISD::SHFL: { 6485 // There is no SHFLIW instruction, but we can just promote the operation. 6486 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6487 "Unexpected custom legalisation"); 6488 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6489 SDValue NewOp0 = 6490 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6491 SDValue NewOp1 = 6492 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6493 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6494 // ReplaceNodeResults requires we maintain the same type for the return 6495 // value. 6496 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6497 break; 6498 } 6499 case ISD::BSWAP: 6500 case ISD::BITREVERSE: { 6501 MVT VT = N->getSimpleValueType(0); 6502 MVT XLenVT = Subtarget.getXLenVT(); 6503 assert((VT == MVT::i8 || VT == MVT::i16 || 6504 (VT == MVT::i32 && Subtarget.is64Bit())) && 6505 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6506 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6507 unsigned Imm = VT.getSizeInBits() - 1; 6508 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6509 if (N->getOpcode() == ISD::BSWAP) 6510 Imm &= ~0x7U; 6511 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6512 SDValue GREVI = 6513 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6514 // ReplaceNodeResults requires we maintain the same type for the return 6515 // value. 6516 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6517 break; 6518 } 6519 case ISD::FSHL: 6520 case ISD::FSHR: { 6521 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6522 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6523 SDValue NewOp0 = 6524 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6525 SDValue NewOp1 = 6526 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6527 SDValue NewShAmt = 6528 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6529 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6530 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6531 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6532 DAG.getConstant(0x1f, DL, MVT::i64)); 6533 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6534 // instruction use different orders. fshl will return its first operand for 6535 // shift of zero, fshr will return its second operand. fsl and fsr both 6536 // return rs1 so the ISD nodes need to have different operand orders. 6537 // Shift amount is in rs2. 6538 unsigned Opc = RISCVISD::FSLW; 6539 if (N->getOpcode() == ISD::FSHR) { 6540 std::swap(NewOp0, NewOp1); 6541 Opc = RISCVISD::FSRW; 6542 } 6543 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6544 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6545 break; 6546 } 6547 case ISD::EXTRACT_VECTOR_ELT: { 6548 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6549 // type is illegal (currently only vXi64 RV32). 6550 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6551 // transferred to the destination register. We issue two of these from the 6552 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6553 // first element. 6554 SDValue Vec = N->getOperand(0); 6555 SDValue Idx = N->getOperand(1); 6556 6557 // The vector type hasn't been legalized yet so we can't issue target 6558 // specific nodes if it needs legalization. 6559 // FIXME: We would manually legalize if it's important. 6560 if (!isTypeLegal(Vec.getValueType())) 6561 return; 6562 6563 MVT VecVT = Vec.getSimpleValueType(); 6564 6565 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6566 VecVT.getVectorElementType() == MVT::i64 && 6567 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6568 6569 // If this is a fixed vector, we need to convert it to a scalable vector. 6570 MVT ContainerVT = VecVT; 6571 if (VecVT.isFixedLengthVector()) { 6572 ContainerVT = getContainerForFixedLengthVector(VecVT); 6573 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6574 } 6575 6576 MVT XLenVT = Subtarget.getXLenVT(); 6577 6578 // Use a VL of 1 to avoid processing more elements than we need. 6579 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6580 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6581 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6582 6583 // Unless the index is known to be 0, we must slide the vector down to get 6584 // the desired element into index 0. 6585 if (!isNullConstant(Idx)) { 6586 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6587 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6588 } 6589 6590 // Extract the lower XLEN bits of the correct vector element. 6591 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6592 6593 // To extract the upper XLEN bits of the vector element, shift the first 6594 // element right by 32 bits and re-extract the lower XLEN bits. 6595 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6596 DAG.getConstant(32, DL, XLenVT), VL); 6597 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6598 ThirtyTwoV, Mask, VL); 6599 6600 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6601 6602 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6603 break; 6604 } 6605 case ISD::INTRINSIC_WO_CHAIN: { 6606 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6607 switch (IntNo) { 6608 default: 6609 llvm_unreachable( 6610 "Don't know how to custom type legalize this intrinsic!"); 6611 case Intrinsic::riscv_grev: 6612 case Intrinsic::riscv_gorc: 6613 case Intrinsic::riscv_bcompress: 6614 case Intrinsic::riscv_bdecompress: 6615 case Intrinsic::riscv_bfp: { 6616 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6617 "Unexpected custom legalisation"); 6618 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6619 break; 6620 } 6621 case Intrinsic::riscv_fsl: 6622 case Intrinsic::riscv_fsr: { 6623 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6624 "Unexpected custom legalisation"); 6625 SDValue NewOp1 = 6626 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6627 SDValue NewOp2 = 6628 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6629 SDValue NewOp3 = 6630 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6631 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6632 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6633 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6634 break; 6635 } 6636 case Intrinsic::riscv_orc_b: { 6637 // Lower to the GORCI encoding for orc.b with the operand extended. 6638 SDValue NewOp = 6639 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6640 // If Zbp is enabled, use GORCIW which will sign extend the result. 6641 unsigned Opc = 6642 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6643 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6644 DAG.getConstant(7, DL, MVT::i64)); 6645 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6646 return; 6647 } 6648 case Intrinsic::riscv_shfl: 6649 case Intrinsic::riscv_unshfl: { 6650 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6651 "Unexpected custom legalisation"); 6652 SDValue NewOp1 = 6653 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6654 SDValue NewOp2 = 6655 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6656 unsigned Opc = 6657 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6658 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6659 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6660 // will be shuffled the same way as the lower 32 bit half, but the two 6661 // halves won't cross. 6662 if (isa<ConstantSDNode>(NewOp2)) { 6663 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6664 DAG.getConstant(0xf, DL, MVT::i64)); 6665 Opc = 6666 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6667 } 6668 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6669 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6670 break; 6671 } 6672 case Intrinsic::riscv_vmv_x_s: { 6673 EVT VT = N->getValueType(0); 6674 MVT XLenVT = Subtarget.getXLenVT(); 6675 if (VT.bitsLT(XLenVT)) { 6676 // Simple case just extract using vmv.x.s and truncate. 6677 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6678 Subtarget.getXLenVT(), N->getOperand(1)); 6679 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6680 return; 6681 } 6682 6683 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6684 "Unexpected custom legalization"); 6685 6686 // We need to do the move in two steps. 6687 SDValue Vec = N->getOperand(1); 6688 MVT VecVT = Vec.getSimpleValueType(); 6689 6690 // First extract the lower XLEN bits of the element. 6691 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6692 6693 // To extract the upper XLEN bits of the vector element, shift the first 6694 // element right by 32 bits and re-extract the lower XLEN bits. 6695 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6696 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6697 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6698 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6699 DAG.getConstant(32, DL, XLenVT), VL); 6700 SDValue LShr32 = 6701 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6702 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6703 6704 Results.push_back( 6705 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6706 break; 6707 } 6708 } 6709 break; 6710 } 6711 case ISD::VECREDUCE_ADD: 6712 case ISD::VECREDUCE_AND: 6713 case ISD::VECREDUCE_OR: 6714 case ISD::VECREDUCE_XOR: 6715 case ISD::VECREDUCE_SMAX: 6716 case ISD::VECREDUCE_UMAX: 6717 case ISD::VECREDUCE_SMIN: 6718 case ISD::VECREDUCE_UMIN: 6719 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6720 Results.push_back(V); 6721 break; 6722 case ISD::VP_REDUCE_ADD: 6723 case ISD::VP_REDUCE_AND: 6724 case ISD::VP_REDUCE_OR: 6725 case ISD::VP_REDUCE_XOR: 6726 case ISD::VP_REDUCE_SMAX: 6727 case ISD::VP_REDUCE_UMAX: 6728 case ISD::VP_REDUCE_SMIN: 6729 case ISD::VP_REDUCE_UMIN: 6730 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6731 Results.push_back(V); 6732 break; 6733 case ISD::FLT_ROUNDS_: { 6734 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6735 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6736 Results.push_back(Res.getValue(0)); 6737 Results.push_back(Res.getValue(1)); 6738 break; 6739 } 6740 } 6741 } 6742 6743 // A structure to hold one of the bit-manipulation patterns below. Together, a 6744 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6745 // (or (and (shl x, 1), 0xAAAAAAAA), 6746 // (and (srl x, 1), 0x55555555)) 6747 struct RISCVBitmanipPat { 6748 SDValue Op; 6749 unsigned ShAmt; 6750 bool IsSHL; 6751 6752 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6753 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6754 } 6755 }; 6756 6757 // Matches patterns of the form 6758 // (and (shl x, C2), (C1 << C2)) 6759 // (and (srl x, C2), C1) 6760 // (shl (and x, C1), C2) 6761 // (srl (and x, (C1 << C2)), C2) 6762 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6763 // The expected masks for each shift amount are specified in BitmanipMasks where 6764 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6765 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6766 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6767 // XLen is 64. 6768 static Optional<RISCVBitmanipPat> 6769 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6770 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6771 "Unexpected number of masks"); 6772 Optional<uint64_t> Mask; 6773 // Optionally consume a mask around the shift operation. 6774 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6775 Mask = Op.getConstantOperandVal(1); 6776 Op = Op.getOperand(0); 6777 } 6778 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6779 return None; 6780 bool IsSHL = Op.getOpcode() == ISD::SHL; 6781 6782 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6783 return None; 6784 uint64_t ShAmt = Op.getConstantOperandVal(1); 6785 6786 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6787 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6788 return None; 6789 // If we don't have enough masks for 64 bit, then we must be trying to 6790 // match SHFL so we're only allowed to shift 1/4 of the width. 6791 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6792 return None; 6793 6794 SDValue Src = Op.getOperand(0); 6795 6796 // The expected mask is shifted left when the AND is found around SHL 6797 // patterns. 6798 // ((x >> 1) & 0x55555555) 6799 // ((x << 1) & 0xAAAAAAAA) 6800 bool SHLExpMask = IsSHL; 6801 6802 if (!Mask) { 6803 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6804 // the mask is all ones: consume that now. 6805 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6806 Mask = Src.getConstantOperandVal(1); 6807 Src = Src.getOperand(0); 6808 // The expected mask is now in fact shifted left for SRL, so reverse the 6809 // decision. 6810 // ((x & 0xAAAAAAAA) >> 1) 6811 // ((x & 0x55555555) << 1) 6812 SHLExpMask = !SHLExpMask; 6813 } else { 6814 // Use a default shifted mask of all-ones if there's no AND, truncated 6815 // down to the expected width. This simplifies the logic later on. 6816 Mask = maskTrailingOnes<uint64_t>(Width); 6817 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6818 } 6819 } 6820 6821 unsigned MaskIdx = Log2_32(ShAmt); 6822 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6823 6824 if (SHLExpMask) 6825 ExpMask <<= ShAmt; 6826 6827 if (Mask != ExpMask) 6828 return None; 6829 6830 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6831 } 6832 6833 // Matches any of the following bit-manipulation patterns: 6834 // (and (shl x, 1), (0x55555555 << 1)) 6835 // (and (srl x, 1), 0x55555555) 6836 // (shl (and x, 0x55555555), 1) 6837 // (srl (and x, (0x55555555 << 1)), 1) 6838 // where the shift amount and mask may vary thus: 6839 // [1] = 0x55555555 / 0xAAAAAAAA 6840 // [2] = 0x33333333 / 0xCCCCCCCC 6841 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6842 // [8] = 0x00FF00FF / 0xFF00FF00 6843 // [16] = 0x0000FFFF / 0xFFFFFFFF 6844 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6845 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6846 // These are the unshifted masks which we use to match bit-manipulation 6847 // patterns. They may be shifted left in certain circumstances. 6848 static const uint64_t BitmanipMasks[] = { 6849 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6850 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6851 6852 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6853 } 6854 6855 // Match the following pattern as a GREVI(W) operation 6856 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6857 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6858 const RISCVSubtarget &Subtarget) { 6859 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6860 EVT VT = Op.getValueType(); 6861 6862 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6863 auto LHS = matchGREVIPat(Op.getOperand(0)); 6864 auto RHS = matchGREVIPat(Op.getOperand(1)); 6865 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6866 SDLoc DL(Op); 6867 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6868 DAG.getConstant(LHS->ShAmt, DL, VT)); 6869 } 6870 } 6871 return SDValue(); 6872 } 6873 6874 // Matches any the following pattern as a GORCI(W) operation 6875 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6876 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6877 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6878 // Note that with the variant of 3., 6879 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6880 // the inner pattern will first be matched as GREVI and then the outer 6881 // pattern will be matched to GORC via the first rule above. 6882 // 4. (or (rotl/rotr x, bitwidth/2), x) 6883 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6884 const RISCVSubtarget &Subtarget) { 6885 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6886 EVT VT = Op.getValueType(); 6887 6888 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6889 SDLoc DL(Op); 6890 SDValue Op0 = Op.getOperand(0); 6891 SDValue Op1 = Op.getOperand(1); 6892 6893 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6894 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6895 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6896 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6897 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6898 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6899 if ((Reverse.getOpcode() == ISD::ROTL || 6900 Reverse.getOpcode() == ISD::ROTR) && 6901 Reverse.getOperand(0) == X && 6902 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6903 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6904 if (RotAmt == (VT.getSizeInBits() / 2)) 6905 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6906 DAG.getConstant(RotAmt, DL, VT)); 6907 } 6908 return SDValue(); 6909 }; 6910 6911 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6912 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6913 return V; 6914 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6915 return V; 6916 6917 // OR is commutable so canonicalize its OR operand to the left 6918 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6919 std::swap(Op0, Op1); 6920 if (Op0.getOpcode() != ISD::OR) 6921 return SDValue(); 6922 SDValue OrOp0 = Op0.getOperand(0); 6923 SDValue OrOp1 = Op0.getOperand(1); 6924 auto LHS = matchGREVIPat(OrOp0); 6925 // OR is commutable so swap the operands and try again: x might have been 6926 // on the left 6927 if (!LHS) { 6928 std::swap(OrOp0, OrOp1); 6929 LHS = matchGREVIPat(OrOp0); 6930 } 6931 auto RHS = matchGREVIPat(Op1); 6932 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6933 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6934 DAG.getConstant(LHS->ShAmt, DL, VT)); 6935 } 6936 } 6937 return SDValue(); 6938 } 6939 6940 // Matches any of the following bit-manipulation patterns: 6941 // (and (shl x, 1), (0x22222222 << 1)) 6942 // (and (srl x, 1), 0x22222222) 6943 // (shl (and x, 0x22222222), 1) 6944 // (srl (and x, (0x22222222 << 1)), 1) 6945 // where the shift amount and mask may vary thus: 6946 // [1] = 0x22222222 / 0x44444444 6947 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6948 // [4] = 0x00F000F0 / 0x0F000F00 6949 // [8] = 0x0000FF00 / 0x00FF0000 6950 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6951 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6952 // These are the unshifted masks which we use to match bit-manipulation 6953 // patterns. They may be shifted left in certain circumstances. 6954 static const uint64_t BitmanipMasks[] = { 6955 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6956 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6957 6958 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6959 } 6960 6961 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6962 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6963 const RISCVSubtarget &Subtarget) { 6964 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6965 EVT VT = Op.getValueType(); 6966 6967 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6968 return SDValue(); 6969 6970 SDValue Op0 = Op.getOperand(0); 6971 SDValue Op1 = Op.getOperand(1); 6972 6973 // Or is commutable so canonicalize the second OR to the LHS. 6974 if (Op0.getOpcode() != ISD::OR) 6975 std::swap(Op0, Op1); 6976 if (Op0.getOpcode() != ISD::OR) 6977 return SDValue(); 6978 6979 // We found an inner OR, so our operands are the operands of the inner OR 6980 // and the other operand of the outer OR. 6981 SDValue A = Op0.getOperand(0); 6982 SDValue B = Op0.getOperand(1); 6983 SDValue C = Op1; 6984 6985 auto Match1 = matchSHFLPat(A); 6986 auto Match2 = matchSHFLPat(B); 6987 6988 // If neither matched, we failed. 6989 if (!Match1 && !Match2) 6990 return SDValue(); 6991 6992 // We had at least one match. if one failed, try the remaining C operand. 6993 if (!Match1) { 6994 std::swap(A, C); 6995 Match1 = matchSHFLPat(A); 6996 if (!Match1) 6997 return SDValue(); 6998 } else if (!Match2) { 6999 std::swap(B, C); 7000 Match2 = matchSHFLPat(B); 7001 if (!Match2) 7002 return SDValue(); 7003 } 7004 assert(Match1 && Match2); 7005 7006 // Make sure our matches pair up. 7007 if (!Match1->formsPairWith(*Match2)) 7008 return SDValue(); 7009 7010 // All the remains is to make sure C is an AND with the same input, that masks 7011 // out the bits that are being shuffled. 7012 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7013 C.getOperand(0) != Match1->Op) 7014 return SDValue(); 7015 7016 uint64_t Mask = C.getConstantOperandVal(1); 7017 7018 static const uint64_t BitmanipMasks[] = { 7019 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7020 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7021 }; 7022 7023 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7024 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7025 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7026 7027 if (Mask != ExpMask) 7028 return SDValue(); 7029 7030 SDLoc DL(Op); 7031 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7032 DAG.getConstant(Match1->ShAmt, DL, VT)); 7033 } 7034 7035 // Optimize (add (shl x, c0), (shl y, c1)) -> 7036 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7037 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7038 const RISCVSubtarget &Subtarget) { 7039 // Perform this optimization only in the zba extension. 7040 if (!Subtarget.hasStdExtZba()) 7041 return SDValue(); 7042 7043 // Skip for vector types and larger types. 7044 EVT VT = N->getValueType(0); 7045 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7046 return SDValue(); 7047 7048 // The two operand nodes must be SHL and have no other use. 7049 SDValue N0 = N->getOperand(0); 7050 SDValue N1 = N->getOperand(1); 7051 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7052 !N0->hasOneUse() || !N1->hasOneUse()) 7053 return SDValue(); 7054 7055 // Check c0 and c1. 7056 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7057 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7058 if (!N0C || !N1C) 7059 return SDValue(); 7060 int64_t C0 = N0C->getSExtValue(); 7061 int64_t C1 = N1C->getSExtValue(); 7062 if (C0 <= 0 || C1 <= 0) 7063 return SDValue(); 7064 7065 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7066 int64_t Bits = std::min(C0, C1); 7067 int64_t Diff = std::abs(C0 - C1); 7068 if (Diff != 1 && Diff != 2 && Diff != 3) 7069 return SDValue(); 7070 7071 // Build nodes. 7072 SDLoc DL(N); 7073 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7074 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7075 SDValue NA0 = 7076 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7077 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7078 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7079 } 7080 7081 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7082 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7083 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7084 // not undo itself, but they are redundant. 7085 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7086 SDValue Src = N->getOperand(0); 7087 7088 if (Src.getOpcode() != N->getOpcode()) 7089 return SDValue(); 7090 7091 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7092 !isa<ConstantSDNode>(Src.getOperand(1))) 7093 return SDValue(); 7094 7095 unsigned ShAmt1 = N->getConstantOperandVal(1); 7096 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7097 Src = Src.getOperand(0); 7098 7099 unsigned CombinedShAmt; 7100 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7101 CombinedShAmt = ShAmt1 | ShAmt2; 7102 else 7103 CombinedShAmt = ShAmt1 ^ ShAmt2; 7104 7105 if (CombinedShAmt == 0) 7106 return Src; 7107 7108 SDLoc DL(N); 7109 return DAG.getNode( 7110 N->getOpcode(), DL, N->getValueType(0), Src, 7111 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7112 } 7113 7114 // Combine a constant select operand into its use: 7115 // 7116 // (and (select cond, -1, c), x) 7117 // -> (select cond, x, (and x, c)) [AllOnes=1] 7118 // (or (select cond, 0, c), x) 7119 // -> (select cond, x, (or x, c)) [AllOnes=0] 7120 // (xor (select cond, 0, c), x) 7121 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7122 // (add (select cond, 0, c), x) 7123 // -> (select cond, x, (add x, c)) [AllOnes=0] 7124 // (sub x, (select cond, 0, c)) 7125 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7126 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7127 SelectionDAG &DAG, bool AllOnes) { 7128 EVT VT = N->getValueType(0); 7129 7130 // Skip vectors. 7131 if (VT.isVector()) 7132 return SDValue(); 7133 7134 if ((Slct.getOpcode() != ISD::SELECT && 7135 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7136 !Slct.hasOneUse()) 7137 return SDValue(); 7138 7139 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7140 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7141 }; 7142 7143 bool SwapSelectOps; 7144 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7145 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7146 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7147 SDValue NonConstantVal; 7148 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7149 SwapSelectOps = false; 7150 NonConstantVal = FalseVal; 7151 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7152 SwapSelectOps = true; 7153 NonConstantVal = TrueVal; 7154 } else 7155 return SDValue(); 7156 7157 // Slct is now know to be the desired identity constant when CC is true. 7158 TrueVal = OtherOp; 7159 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7160 // Unless SwapSelectOps says the condition should be false. 7161 if (SwapSelectOps) 7162 std::swap(TrueVal, FalseVal); 7163 7164 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7165 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7166 {Slct.getOperand(0), Slct.getOperand(1), 7167 Slct.getOperand(2), TrueVal, FalseVal}); 7168 7169 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7170 {Slct.getOperand(0), TrueVal, FalseVal}); 7171 } 7172 7173 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7174 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7175 bool AllOnes) { 7176 SDValue N0 = N->getOperand(0); 7177 SDValue N1 = N->getOperand(1); 7178 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7179 return Result; 7180 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7181 return Result; 7182 return SDValue(); 7183 } 7184 7185 // Transform (add (mul x, c0), c1) -> 7186 // (add (mul (add x, c1/c0), c0), c1%c0). 7187 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7188 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7189 // to an infinite loop in DAGCombine if transformed. 7190 // Or transform (add (mul x, c0), c1) -> 7191 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7192 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7193 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7194 // lead to an infinite loop in DAGCombine if transformed. 7195 // Or transform (add (mul x, c0), c1) -> 7196 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7197 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7198 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7199 // lead to an infinite loop in DAGCombine if transformed. 7200 // Or transform (add (mul x, c0), c1) -> 7201 // (mul (add x, c1/c0), c0). 7202 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7203 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7204 const RISCVSubtarget &Subtarget) { 7205 // Skip for vector types and larger types. 7206 EVT VT = N->getValueType(0); 7207 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7208 return SDValue(); 7209 // The first operand node must be a MUL and has no other use. 7210 SDValue N0 = N->getOperand(0); 7211 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7212 return SDValue(); 7213 // Check if c0 and c1 match above conditions. 7214 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7215 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7216 if (!N0C || !N1C) 7217 return SDValue(); 7218 int64_t C0 = N0C->getSExtValue(); 7219 int64_t C1 = N1C->getSExtValue(); 7220 int64_t CA, CB; 7221 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7222 return SDValue(); 7223 // Search for proper CA (non-zero) and CB that both are simm12. 7224 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7225 !isInt<12>(C0 * (C1 / C0))) { 7226 CA = C1 / C0; 7227 CB = C1 % C0; 7228 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7229 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7230 CA = C1 / C0 + 1; 7231 CB = C1 % C0 - C0; 7232 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7233 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7234 CA = C1 / C0 - 1; 7235 CB = C1 % C0 + C0; 7236 } else 7237 return SDValue(); 7238 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7239 SDLoc DL(N); 7240 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7241 DAG.getConstant(CA, DL, VT)); 7242 SDValue New1 = 7243 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7244 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7245 } 7246 7247 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7248 const RISCVSubtarget &Subtarget) { 7249 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7250 return V; 7251 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7252 return V; 7253 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7254 // (select lhs, rhs, cc, x, (add x, y)) 7255 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7256 } 7257 7258 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7259 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7260 // (select lhs, rhs, cc, x, (sub x, y)) 7261 SDValue N0 = N->getOperand(0); 7262 SDValue N1 = N->getOperand(1); 7263 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7264 } 7265 7266 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7267 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7268 // (select lhs, rhs, cc, x, (and x, y)) 7269 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7270 } 7271 7272 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7273 const RISCVSubtarget &Subtarget) { 7274 if (Subtarget.hasStdExtZbp()) { 7275 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7276 return GREV; 7277 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7278 return GORC; 7279 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7280 return SHFL; 7281 } 7282 7283 // fold (or (select cond, 0, y), x) -> 7284 // (select cond, x, (or x, y)) 7285 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7286 } 7287 7288 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7289 // fold (xor (select cond, 0, y), x) -> 7290 // (select cond, x, (xor x, y)) 7291 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7292 } 7293 7294 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7295 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7296 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7297 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7298 // ADDW/SUBW/MULW. 7299 static SDValue performANY_EXTENDCombine(SDNode *N, 7300 TargetLowering::DAGCombinerInfo &DCI, 7301 const RISCVSubtarget &Subtarget) { 7302 if (!Subtarget.is64Bit()) 7303 return SDValue(); 7304 7305 SelectionDAG &DAG = DCI.DAG; 7306 7307 SDValue Src = N->getOperand(0); 7308 EVT VT = N->getValueType(0); 7309 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7310 return SDValue(); 7311 7312 // The opcode must be one that can implicitly sign_extend. 7313 // FIXME: Additional opcodes. 7314 switch (Src.getOpcode()) { 7315 default: 7316 return SDValue(); 7317 case ISD::MUL: 7318 if (!Subtarget.hasStdExtM()) 7319 return SDValue(); 7320 LLVM_FALLTHROUGH; 7321 case ISD::ADD: 7322 case ISD::SUB: 7323 break; 7324 } 7325 7326 // Only handle cases where the result is used by a CopyToReg. That likely 7327 // means the value is a liveout of the basic block. This helps prevent 7328 // infinite combine loops like PR51206. 7329 if (none_of(N->uses(), 7330 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7331 return SDValue(); 7332 7333 SmallVector<SDNode *, 4> SetCCs; 7334 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7335 UE = Src.getNode()->use_end(); 7336 UI != UE; ++UI) { 7337 SDNode *User = *UI; 7338 if (User == N) 7339 continue; 7340 if (UI.getUse().getResNo() != Src.getResNo()) 7341 continue; 7342 // All i32 setccs are legalized by sign extending operands. 7343 if (User->getOpcode() == ISD::SETCC) { 7344 SetCCs.push_back(User); 7345 continue; 7346 } 7347 // We don't know if we can extend this user. 7348 break; 7349 } 7350 7351 // If we don't have any SetCCs, this isn't worthwhile. 7352 if (SetCCs.empty()) 7353 return SDValue(); 7354 7355 SDLoc DL(N); 7356 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7357 DCI.CombineTo(N, SExt); 7358 7359 // Promote all the setccs. 7360 for (SDNode *SetCC : SetCCs) { 7361 SmallVector<SDValue, 4> Ops; 7362 7363 for (unsigned j = 0; j != 2; ++j) { 7364 SDValue SOp = SetCC->getOperand(j); 7365 if (SOp == Src) 7366 Ops.push_back(SExt); 7367 else 7368 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7369 } 7370 7371 Ops.push_back(SetCC->getOperand(2)); 7372 DCI.CombineTo(SetCC, 7373 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7374 } 7375 return SDValue(N, 0); 7376 } 7377 7378 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7379 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7380 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7381 bool Commute = false) { 7382 assert((N->getOpcode() == RISCVISD::ADD_VL || 7383 N->getOpcode() == RISCVISD::SUB_VL) && 7384 "Unexpected opcode"); 7385 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7386 SDValue Op0 = N->getOperand(0); 7387 SDValue Op1 = N->getOperand(1); 7388 if (Commute) 7389 std::swap(Op0, Op1); 7390 7391 MVT VT = N->getSimpleValueType(0); 7392 7393 // Determine the narrow size for a widening add/sub. 7394 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7395 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7396 VT.getVectorElementCount()); 7397 7398 SDValue Mask = N->getOperand(2); 7399 SDValue VL = N->getOperand(3); 7400 7401 SDLoc DL(N); 7402 7403 // If the RHS is a sext or zext, we can form a widening op. 7404 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7405 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7406 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7407 unsigned ExtOpc = Op1.getOpcode(); 7408 Op1 = Op1.getOperand(0); 7409 // Re-introduce narrower extends if needed. 7410 if (Op1.getValueType() != NarrowVT) 7411 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7412 7413 unsigned WOpc; 7414 if (ExtOpc == RISCVISD::VSEXT_VL) 7415 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7416 else 7417 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7418 7419 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7420 } 7421 7422 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7423 // sext/zext? 7424 7425 return SDValue(); 7426 } 7427 7428 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7429 // vwsub(u).vv/vx. 7430 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7431 SDValue Op0 = N->getOperand(0); 7432 SDValue Op1 = N->getOperand(1); 7433 SDValue Mask = N->getOperand(2); 7434 SDValue VL = N->getOperand(3); 7435 7436 MVT VT = N->getSimpleValueType(0); 7437 MVT NarrowVT = Op1.getSimpleValueType(); 7438 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7439 7440 unsigned VOpc; 7441 switch (N->getOpcode()) { 7442 default: llvm_unreachable("Unexpected opcode"); 7443 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7444 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7445 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7446 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7447 } 7448 7449 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7450 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7451 7452 SDLoc DL(N); 7453 7454 // If the LHS is a sext or zext, we can narrow this op to the same size as 7455 // the RHS. 7456 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7457 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7458 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7459 unsigned ExtOpc = Op0.getOpcode(); 7460 Op0 = Op0.getOperand(0); 7461 // Re-introduce narrower extends if needed. 7462 if (Op0.getValueType() != NarrowVT) 7463 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7464 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7465 } 7466 7467 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7468 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7469 7470 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7471 // to commute and use a vwadd(u).vx instead. 7472 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7473 Op0.getOperand(1) == VL) { 7474 Op0 = Op0.getOperand(0); 7475 7476 // See if have enough sign bits or zero bits in the scalar to use a 7477 // widening add/sub by splatting to smaller element size. 7478 unsigned EltBits = VT.getScalarSizeInBits(); 7479 unsigned ScalarBits = Op0.getValueSizeInBits(); 7480 // Make sure we're getting all element bits from the scalar register. 7481 // FIXME: Support implicit sign extension of vmv.v.x? 7482 if (ScalarBits < EltBits) 7483 return SDValue(); 7484 7485 if (IsSigned) { 7486 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7487 return SDValue(); 7488 } else { 7489 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7490 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7491 return SDValue(); 7492 } 7493 7494 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op0, VL); 7495 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7496 } 7497 7498 return SDValue(); 7499 } 7500 7501 // Try to form VWMUL, VWMULU or VWMULSU. 7502 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7503 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7504 bool Commute) { 7505 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7506 SDValue Op0 = N->getOperand(0); 7507 SDValue Op1 = N->getOperand(1); 7508 if (Commute) 7509 std::swap(Op0, Op1); 7510 7511 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7512 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7513 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7514 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7515 return SDValue(); 7516 7517 SDValue Mask = N->getOperand(2); 7518 SDValue VL = N->getOperand(3); 7519 7520 // Make sure the mask and VL match. 7521 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7522 return SDValue(); 7523 7524 MVT VT = N->getSimpleValueType(0); 7525 7526 // Determine the narrow size for a widening multiply. 7527 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7528 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7529 VT.getVectorElementCount()); 7530 7531 SDLoc DL(N); 7532 7533 // See if the other operand is the same opcode. 7534 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7535 if (!Op1.hasOneUse()) 7536 return SDValue(); 7537 7538 // Make sure the mask and VL match. 7539 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7540 return SDValue(); 7541 7542 Op1 = Op1.getOperand(0); 7543 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7544 // The operand is a splat of a scalar. 7545 7546 // The VL must be the same. 7547 if (Op1.getOperand(1) != VL) 7548 return SDValue(); 7549 7550 // Get the scalar value. 7551 Op1 = Op1.getOperand(0); 7552 7553 // See if have enough sign bits or zero bits in the scalar to use a 7554 // widening multiply by splatting to smaller element size. 7555 unsigned EltBits = VT.getScalarSizeInBits(); 7556 unsigned ScalarBits = Op1.getValueSizeInBits(); 7557 // Make sure we're getting all element bits from the scalar register. 7558 // FIXME: Support implicit sign extension of vmv.v.x? 7559 if (ScalarBits < EltBits) 7560 return SDValue(); 7561 7562 if (IsSignExt) { 7563 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 7564 return SDValue(); 7565 } else { 7566 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7567 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7568 return SDValue(); 7569 } 7570 7571 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7572 } else 7573 return SDValue(); 7574 7575 Op0 = Op0.getOperand(0); 7576 7577 // Re-introduce narrower extends if needed. 7578 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7579 if (Op0.getValueType() != NarrowVT) 7580 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7581 if (Op1.getValueType() != NarrowVT) 7582 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7583 7584 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7585 if (!IsVWMULSU) 7586 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7587 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7588 } 7589 7590 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7591 switch (Op.getOpcode()) { 7592 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7593 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7594 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7595 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7596 case ISD::FROUND: return RISCVFPRndMode::RMM; 7597 } 7598 7599 return RISCVFPRndMode::Invalid; 7600 } 7601 7602 // Fold 7603 // (fp_to_int (froundeven X)) -> fcvt X, rne 7604 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7605 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7606 // (fp_to_int (fceil X)) -> fcvt X, rup 7607 // (fp_to_int (fround X)) -> fcvt X, rmm 7608 static SDValue performFP_TO_INTCombine(SDNode *N, 7609 TargetLowering::DAGCombinerInfo &DCI, 7610 const RISCVSubtarget &Subtarget) { 7611 SelectionDAG &DAG = DCI.DAG; 7612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7613 MVT XLenVT = Subtarget.getXLenVT(); 7614 7615 // Only handle XLen or i32 types. Other types narrower than XLen will 7616 // eventually be legalized to XLenVT. 7617 EVT VT = N->getValueType(0); 7618 if (VT != MVT::i32 && VT != XLenVT) 7619 return SDValue(); 7620 7621 SDValue Src = N->getOperand(0); 7622 7623 // Ensure the FP type is also legal. 7624 if (!TLI.isTypeLegal(Src.getValueType())) 7625 return SDValue(); 7626 7627 // Don't do this for f16 with Zfhmin and not Zfh. 7628 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7629 return SDValue(); 7630 7631 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7632 if (FRM == RISCVFPRndMode::Invalid) 7633 return SDValue(); 7634 7635 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7636 7637 unsigned Opc; 7638 if (VT == XLenVT) 7639 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7640 else 7641 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7642 7643 SDLoc DL(N); 7644 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7645 DAG.getTargetConstant(FRM, DL, XLenVT)); 7646 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7647 } 7648 7649 // Fold 7650 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7651 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7652 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7653 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7654 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7655 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7656 TargetLowering::DAGCombinerInfo &DCI, 7657 const RISCVSubtarget &Subtarget) { 7658 SelectionDAG &DAG = DCI.DAG; 7659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7660 MVT XLenVT = Subtarget.getXLenVT(); 7661 7662 // Only handle XLen types. Other types narrower than XLen will eventually be 7663 // legalized to XLenVT. 7664 EVT DstVT = N->getValueType(0); 7665 if (DstVT != XLenVT) 7666 return SDValue(); 7667 7668 SDValue Src = N->getOperand(0); 7669 7670 // Ensure the FP type is also legal. 7671 if (!TLI.isTypeLegal(Src.getValueType())) 7672 return SDValue(); 7673 7674 // Don't do this for f16 with Zfhmin and not Zfh. 7675 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7676 return SDValue(); 7677 7678 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7679 7680 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7681 if (FRM == RISCVFPRndMode::Invalid) 7682 return SDValue(); 7683 7684 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7685 7686 unsigned Opc; 7687 if (SatVT == DstVT) 7688 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7689 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7690 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7691 else 7692 return SDValue(); 7693 // FIXME: Support other SatVTs by clamping before or after the conversion. 7694 7695 Src = Src.getOperand(0); 7696 7697 SDLoc DL(N); 7698 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7699 DAG.getTargetConstant(FRM, DL, XLenVT)); 7700 7701 // RISCV FP-to-int conversions saturate to the destination register size, but 7702 // don't produce 0 for nan. 7703 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7704 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7705 } 7706 7707 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7708 DAGCombinerInfo &DCI) const { 7709 SelectionDAG &DAG = DCI.DAG; 7710 7711 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7712 // bits are demanded. N will be added to the Worklist if it was not deleted. 7713 // Caller should return SDValue(N, 0) if this returns true. 7714 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7715 SDValue Op = N->getOperand(OpNo); 7716 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7717 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7718 return false; 7719 7720 if (N->getOpcode() != ISD::DELETED_NODE) 7721 DCI.AddToWorklist(N); 7722 return true; 7723 }; 7724 7725 switch (N->getOpcode()) { 7726 default: 7727 break; 7728 case RISCVISD::SplitF64: { 7729 SDValue Op0 = N->getOperand(0); 7730 // If the input to SplitF64 is just BuildPairF64 then the operation is 7731 // redundant. Instead, use BuildPairF64's operands directly. 7732 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7733 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7734 7735 SDLoc DL(N); 7736 7737 // It's cheaper to materialise two 32-bit integers than to load a double 7738 // from the constant pool and transfer it to integer registers through the 7739 // stack. 7740 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7741 APInt V = C->getValueAPF().bitcastToAPInt(); 7742 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7743 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7744 return DCI.CombineTo(N, Lo, Hi); 7745 } 7746 7747 // This is a target-specific version of a DAGCombine performed in 7748 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7749 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7750 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7751 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7752 !Op0.getNode()->hasOneUse()) 7753 break; 7754 SDValue NewSplitF64 = 7755 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7756 Op0.getOperand(0)); 7757 SDValue Lo = NewSplitF64.getValue(0); 7758 SDValue Hi = NewSplitF64.getValue(1); 7759 APInt SignBit = APInt::getSignMask(32); 7760 if (Op0.getOpcode() == ISD::FNEG) { 7761 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7762 DAG.getConstant(SignBit, DL, MVT::i32)); 7763 return DCI.CombineTo(N, Lo, NewHi); 7764 } 7765 assert(Op0.getOpcode() == ISD::FABS); 7766 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7767 DAG.getConstant(~SignBit, DL, MVT::i32)); 7768 return DCI.CombineTo(N, Lo, NewHi); 7769 } 7770 case RISCVISD::SLLW: 7771 case RISCVISD::SRAW: 7772 case RISCVISD::SRLW: 7773 case RISCVISD::ROLW: 7774 case RISCVISD::RORW: { 7775 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7776 if (SimplifyDemandedLowBitsHelper(0, 32) || 7777 SimplifyDemandedLowBitsHelper(1, 5)) 7778 return SDValue(N, 0); 7779 break; 7780 } 7781 case RISCVISD::CLZW: 7782 case RISCVISD::CTZW: { 7783 // Only the lower 32 bits of the first operand are read 7784 if (SimplifyDemandedLowBitsHelper(0, 32)) 7785 return SDValue(N, 0); 7786 break; 7787 } 7788 case RISCVISD::GREV: 7789 case RISCVISD::GORC: { 7790 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7791 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7792 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7793 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7794 return SDValue(N, 0); 7795 7796 return combineGREVI_GORCI(N, DAG); 7797 } 7798 case RISCVISD::GREVW: 7799 case RISCVISD::GORCW: { 7800 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7801 if (SimplifyDemandedLowBitsHelper(0, 32) || 7802 SimplifyDemandedLowBitsHelper(1, 5)) 7803 return SDValue(N, 0); 7804 7805 return combineGREVI_GORCI(N, DAG); 7806 } 7807 case RISCVISD::SHFL: 7808 case RISCVISD::UNSHFL: { 7809 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7810 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7811 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7812 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7813 return SDValue(N, 0); 7814 7815 break; 7816 } 7817 case RISCVISD::SHFLW: 7818 case RISCVISD::UNSHFLW: { 7819 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7820 if (SimplifyDemandedLowBitsHelper(0, 32) || 7821 SimplifyDemandedLowBitsHelper(1, 4)) 7822 return SDValue(N, 0); 7823 7824 break; 7825 } 7826 case RISCVISD::BCOMPRESSW: 7827 case RISCVISD::BDECOMPRESSW: { 7828 // Only the lower 32 bits of LHS and RHS are read. 7829 if (SimplifyDemandedLowBitsHelper(0, 32) || 7830 SimplifyDemandedLowBitsHelper(1, 32)) 7831 return SDValue(N, 0); 7832 7833 break; 7834 } 7835 case RISCVISD::FMV_X_ANYEXTH: 7836 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7837 SDLoc DL(N); 7838 SDValue Op0 = N->getOperand(0); 7839 MVT VT = N->getSimpleValueType(0); 7840 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7841 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7842 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7843 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7844 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7845 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7846 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7847 assert(Op0.getOperand(0).getValueType() == VT && 7848 "Unexpected value type!"); 7849 return Op0.getOperand(0); 7850 } 7851 7852 // This is a target-specific version of a DAGCombine performed in 7853 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7854 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7855 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7856 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7857 !Op0.getNode()->hasOneUse()) 7858 break; 7859 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7860 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7861 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7862 if (Op0.getOpcode() == ISD::FNEG) 7863 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7864 DAG.getConstant(SignBit, DL, VT)); 7865 7866 assert(Op0.getOpcode() == ISD::FABS); 7867 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7868 DAG.getConstant(~SignBit, DL, VT)); 7869 } 7870 case ISD::ADD: 7871 return performADDCombine(N, DAG, Subtarget); 7872 case ISD::SUB: 7873 return performSUBCombine(N, DAG); 7874 case ISD::AND: 7875 return performANDCombine(N, DAG); 7876 case ISD::OR: 7877 return performORCombine(N, DAG, Subtarget); 7878 case ISD::XOR: 7879 return performXORCombine(N, DAG); 7880 case ISD::ANY_EXTEND: 7881 return performANY_EXTENDCombine(N, DCI, Subtarget); 7882 case ISD::ZERO_EXTEND: 7883 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7884 // type legalization. This is safe because fp_to_uint produces poison if 7885 // it overflows. 7886 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7887 SDValue Src = N->getOperand(0); 7888 if (Src.getOpcode() == ISD::FP_TO_UINT && 7889 isTypeLegal(Src.getOperand(0).getValueType())) 7890 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7891 Src.getOperand(0)); 7892 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7893 isTypeLegal(Src.getOperand(1).getValueType())) { 7894 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7895 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7896 Src.getOperand(0), Src.getOperand(1)); 7897 DCI.CombineTo(N, Res); 7898 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7899 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7900 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7901 } 7902 } 7903 return SDValue(); 7904 case RISCVISD::SELECT_CC: { 7905 // Transform 7906 SDValue LHS = N->getOperand(0); 7907 SDValue RHS = N->getOperand(1); 7908 SDValue TrueV = N->getOperand(3); 7909 SDValue FalseV = N->getOperand(4); 7910 7911 // If the True and False values are the same, we don't need a select_cc. 7912 if (TrueV == FalseV) 7913 return TrueV; 7914 7915 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7916 if (!ISD::isIntEqualitySetCC(CCVal)) 7917 break; 7918 7919 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7920 // (select_cc X, Y, lt, trueV, falseV) 7921 // Sometimes the setcc is introduced after select_cc has been formed. 7922 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7923 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7924 // If we're looking for eq 0 instead of ne 0, we need to invert the 7925 // condition. 7926 bool Invert = CCVal == ISD::SETEQ; 7927 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7928 if (Invert) 7929 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7930 7931 SDLoc DL(N); 7932 RHS = LHS.getOperand(1); 7933 LHS = LHS.getOperand(0); 7934 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7935 7936 SDValue TargetCC = DAG.getCondCode(CCVal); 7937 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7938 {LHS, RHS, TargetCC, TrueV, FalseV}); 7939 } 7940 7941 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7942 // (select_cc X, Y, eq/ne, trueV, falseV) 7943 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7944 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7945 {LHS.getOperand(0), LHS.getOperand(1), 7946 N->getOperand(2), TrueV, FalseV}); 7947 // (select_cc X, 1, setne, trueV, falseV) -> 7948 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7949 // This can occur when legalizing some floating point comparisons. 7950 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7951 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7952 SDLoc DL(N); 7953 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7954 SDValue TargetCC = DAG.getCondCode(CCVal); 7955 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7956 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7957 {LHS, RHS, TargetCC, TrueV, FalseV}); 7958 } 7959 7960 break; 7961 } 7962 case RISCVISD::BR_CC: { 7963 SDValue LHS = N->getOperand(1); 7964 SDValue RHS = N->getOperand(2); 7965 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7966 if (!ISD::isIntEqualitySetCC(CCVal)) 7967 break; 7968 7969 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7970 // (br_cc X, Y, lt, dest) 7971 // Sometimes the setcc is introduced after br_cc has been formed. 7972 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7973 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7974 // If we're looking for eq 0 instead of ne 0, we need to invert the 7975 // condition. 7976 bool Invert = CCVal == ISD::SETEQ; 7977 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7978 if (Invert) 7979 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7980 7981 SDLoc DL(N); 7982 RHS = LHS.getOperand(1); 7983 LHS = LHS.getOperand(0); 7984 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7985 7986 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7987 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7988 N->getOperand(4)); 7989 } 7990 7991 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7992 // (br_cc X, Y, eq/ne, trueV, falseV) 7993 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7994 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7995 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7996 N->getOperand(3), N->getOperand(4)); 7997 7998 // (br_cc X, 1, setne, br_cc) -> 7999 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8000 // This can occur when legalizing some floating point comparisons. 8001 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8002 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8003 SDLoc DL(N); 8004 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8005 SDValue TargetCC = DAG.getCondCode(CCVal); 8006 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8007 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8008 N->getOperand(0), LHS, RHS, TargetCC, 8009 N->getOperand(4)); 8010 } 8011 break; 8012 } 8013 case ISD::FP_TO_SINT: 8014 case ISD::FP_TO_UINT: 8015 return performFP_TO_INTCombine(N, DCI, Subtarget); 8016 case ISD::FP_TO_SINT_SAT: 8017 case ISD::FP_TO_UINT_SAT: 8018 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8019 case ISD::FCOPYSIGN: { 8020 EVT VT = N->getValueType(0); 8021 if (!VT.isVector()) 8022 break; 8023 // There is a form of VFSGNJ which injects the negated sign of its second 8024 // operand. Try and bubble any FNEG up after the extend/round to produce 8025 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8026 // TRUNC=1. 8027 SDValue In2 = N->getOperand(1); 8028 // Avoid cases where the extend/round has multiple uses, as duplicating 8029 // those is typically more expensive than removing a fneg. 8030 if (!In2.hasOneUse()) 8031 break; 8032 if (In2.getOpcode() != ISD::FP_EXTEND && 8033 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8034 break; 8035 In2 = In2.getOperand(0); 8036 if (In2.getOpcode() != ISD::FNEG) 8037 break; 8038 SDLoc DL(N); 8039 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8040 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8041 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8042 } 8043 case ISD::MGATHER: 8044 case ISD::MSCATTER: 8045 case ISD::VP_GATHER: 8046 case ISD::VP_SCATTER: { 8047 if (!DCI.isBeforeLegalize()) 8048 break; 8049 SDValue Index, ScaleOp; 8050 bool IsIndexScaled = false; 8051 bool IsIndexSigned = false; 8052 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8053 Index = VPGSN->getIndex(); 8054 ScaleOp = VPGSN->getScale(); 8055 IsIndexScaled = VPGSN->isIndexScaled(); 8056 IsIndexSigned = VPGSN->isIndexSigned(); 8057 } else { 8058 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8059 Index = MGSN->getIndex(); 8060 ScaleOp = MGSN->getScale(); 8061 IsIndexScaled = MGSN->isIndexScaled(); 8062 IsIndexSigned = MGSN->isIndexSigned(); 8063 } 8064 EVT IndexVT = Index.getValueType(); 8065 MVT XLenVT = Subtarget.getXLenVT(); 8066 // RISCV indexed loads only support the "unsigned unscaled" addressing 8067 // mode, so anything else must be manually legalized. 8068 bool NeedsIdxLegalization = 8069 IsIndexScaled || 8070 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8071 if (!NeedsIdxLegalization) 8072 break; 8073 8074 SDLoc DL(N); 8075 8076 // Any index legalization should first promote to XLenVT, so we don't lose 8077 // bits when scaling. This may create an illegal index type so we let 8078 // LLVM's legalization take care of the splitting. 8079 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8080 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8081 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8082 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8083 DL, IndexVT, Index); 8084 } 8085 8086 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8087 if (IsIndexScaled && Scale != 1) { 8088 // Manually scale the indices by the element size. 8089 // TODO: Sanitize the scale operand here? 8090 // TODO: For VP nodes, should we use VP_SHL here? 8091 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8092 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8093 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8094 } 8095 8096 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8097 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8098 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8099 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8100 VPGN->getScale(), VPGN->getMask(), 8101 VPGN->getVectorLength()}, 8102 VPGN->getMemOperand(), NewIndexTy); 8103 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8104 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8105 {VPSN->getChain(), VPSN->getValue(), 8106 VPSN->getBasePtr(), Index, VPSN->getScale(), 8107 VPSN->getMask(), VPSN->getVectorLength()}, 8108 VPSN->getMemOperand(), NewIndexTy); 8109 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8110 return DAG.getMaskedGather( 8111 N->getVTList(), MGN->getMemoryVT(), DL, 8112 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8113 MGN->getBasePtr(), Index, MGN->getScale()}, 8114 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8115 const auto *MSN = cast<MaskedScatterSDNode>(N); 8116 return DAG.getMaskedScatter( 8117 N->getVTList(), MSN->getMemoryVT(), DL, 8118 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8119 Index, MSN->getScale()}, 8120 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8121 } 8122 case RISCVISD::SRA_VL: 8123 case RISCVISD::SRL_VL: 8124 case RISCVISD::SHL_VL: { 8125 SDValue ShAmt = N->getOperand(1); 8126 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8127 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8128 SDLoc DL(N); 8129 SDValue VL = N->getOperand(3); 8130 EVT VT = N->getValueType(0); 8131 ShAmt = 8132 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 8133 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8134 N->getOperand(2), N->getOperand(3)); 8135 } 8136 break; 8137 } 8138 case ISD::SRA: 8139 case ISD::SRL: 8140 case ISD::SHL: { 8141 SDValue ShAmt = N->getOperand(1); 8142 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8143 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8144 SDLoc DL(N); 8145 EVT VT = N->getValueType(0); 8146 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), 8147 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, 8148 Subtarget.getXLenVT())); 8149 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8150 } 8151 break; 8152 } 8153 case RISCVISD::ADD_VL: 8154 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8155 return V; 8156 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8157 case RISCVISD::SUB_VL: 8158 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8159 case RISCVISD::VWADD_W_VL: 8160 case RISCVISD::VWADDU_W_VL: 8161 case RISCVISD::VWSUB_W_VL: 8162 case RISCVISD::VWSUBU_W_VL: 8163 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8164 case RISCVISD::MUL_VL: 8165 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8166 return V; 8167 // Mul is commutative. 8168 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8169 case ISD::STORE: { 8170 auto *Store = cast<StoreSDNode>(N); 8171 SDValue Val = Store->getValue(); 8172 // Combine store of vmv.x.s to vse with VL of 1. 8173 // FIXME: Support FP. 8174 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8175 SDValue Src = Val.getOperand(0); 8176 EVT VecVT = Src.getValueType(); 8177 EVT MemVT = Store->getMemoryVT(); 8178 // The memory VT and the element type must match. 8179 if (VecVT.getVectorElementType() == MemVT) { 8180 SDLoc DL(N); 8181 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8182 return DAG.getStoreVP( 8183 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8184 DAG.getConstant(1, DL, MaskVT), 8185 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8186 Store->getMemOperand(), Store->getAddressingMode(), 8187 Store->isTruncatingStore(), /*IsCompress*/ false); 8188 } 8189 } 8190 8191 break; 8192 } 8193 } 8194 8195 return SDValue(); 8196 } 8197 8198 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8199 const SDNode *N, CombineLevel Level) const { 8200 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8201 // materialised in fewer instructions than `(OP _, c1)`: 8202 // 8203 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8204 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8205 SDValue N0 = N->getOperand(0); 8206 EVT Ty = N0.getValueType(); 8207 if (Ty.isScalarInteger() && 8208 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8209 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8210 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8211 if (C1 && C2) { 8212 const APInt &C1Int = C1->getAPIntValue(); 8213 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8214 8215 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8216 // and the combine should happen, to potentially allow further combines 8217 // later. 8218 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8219 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8220 return true; 8221 8222 // We can materialise `c1` in an add immediate, so it's "free", and the 8223 // combine should be prevented. 8224 if (C1Int.getMinSignedBits() <= 64 && 8225 isLegalAddImmediate(C1Int.getSExtValue())) 8226 return false; 8227 8228 // Neither constant will fit into an immediate, so find materialisation 8229 // costs. 8230 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8231 Subtarget.getFeatureBits(), 8232 /*CompressionCost*/true); 8233 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8234 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8235 /*CompressionCost*/true); 8236 8237 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8238 // combine should be prevented. 8239 if (C1Cost < ShiftedC1Cost) 8240 return false; 8241 } 8242 } 8243 return true; 8244 } 8245 8246 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8247 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8248 TargetLoweringOpt &TLO) const { 8249 // Delay this optimization as late as possible. 8250 if (!TLO.LegalOps) 8251 return false; 8252 8253 EVT VT = Op.getValueType(); 8254 if (VT.isVector()) 8255 return false; 8256 8257 // Only handle AND for now. 8258 if (Op.getOpcode() != ISD::AND) 8259 return false; 8260 8261 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8262 if (!C) 8263 return false; 8264 8265 const APInt &Mask = C->getAPIntValue(); 8266 8267 // Clear all non-demanded bits initially. 8268 APInt ShrunkMask = Mask & DemandedBits; 8269 8270 // Try to make a smaller immediate by setting undemanded bits. 8271 8272 APInt ExpandedMask = Mask | ~DemandedBits; 8273 8274 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8275 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8276 }; 8277 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8278 if (NewMask == Mask) 8279 return true; 8280 SDLoc DL(Op); 8281 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8282 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8283 return TLO.CombineTo(Op, NewOp); 8284 }; 8285 8286 // If the shrunk mask fits in sign extended 12 bits, let the target 8287 // independent code apply it. 8288 if (ShrunkMask.isSignedIntN(12)) 8289 return false; 8290 8291 // Preserve (and X, 0xffff) when zext.h is supported. 8292 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8293 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8294 if (IsLegalMask(NewMask)) 8295 return UseMask(NewMask); 8296 } 8297 8298 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8299 if (VT == MVT::i64) { 8300 APInt NewMask = APInt(64, 0xffffffff); 8301 if (IsLegalMask(NewMask)) 8302 return UseMask(NewMask); 8303 } 8304 8305 // For the remaining optimizations, we need to be able to make a negative 8306 // number through a combination of mask and undemanded bits. 8307 if (!ExpandedMask.isNegative()) 8308 return false; 8309 8310 // What is the fewest number of bits we need to represent the negative number. 8311 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8312 8313 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8314 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8315 APInt NewMask = ShrunkMask; 8316 if (MinSignedBits <= 12) 8317 NewMask.setBitsFrom(11); 8318 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8319 NewMask.setBitsFrom(31); 8320 else 8321 return false; 8322 8323 // Check that our new mask is a subset of the demanded mask. 8324 assert(IsLegalMask(NewMask)); 8325 return UseMask(NewMask); 8326 } 8327 8328 static void computeGREV(APInt &Src, unsigned ShAmt) { 8329 ShAmt &= Src.getBitWidth() - 1; 8330 uint64_t x = Src.getZExtValue(); 8331 if (ShAmt & 1) 8332 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8333 if (ShAmt & 2) 8334 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8335 if (ShAmt & 4) 8336 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8337 if (ShAmt & 8) 8338 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8339 if (ShAmt & 16) 8340 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8341 if (ShAmt & 32) 8342 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8343 Src = x; 8344 } 8345 8346 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8347 KnownBits &Known, 8348 const APInt &DemandedElts, 8349 const SelectionDAG &DAG, 8350 unsigned Depth) const { 8351 unsigned BitWidth = Known.getBitWidth(); 8352 unsigned Opc = Op.getOpcode(); 8353 assert((Opc >= ISD::BUILTIN_OP_END || 8354 Opc == ISD::INTRINSIC_WO_CHAIN || 8355 Opc == ISD::INTRINSIC_W_CHAIN || 8356 Opc == ISD::INTRINSIC_VOID) && 8357 "Should use MaskedValueIsZero if you don't know whether Op" 8358 " is a target node!"); 8359 8360 Known.resetAll(); 8361 switch (Opc) { 8362 default: break; 8363 case RISCVISD::SELECT_CC: { 8364 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8365 // If we don't know any bits, early out. 8366 if (Known.isUnknown()) 8367 break; 8368 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8369 8370 // Only known if known in both the LHS and RHS. 8371 Known = KnownBits::commonBits(Known, Known2); 8372 break; 8373 } 8374 case RISCVISD::REMUW: { 8375 KnownBits Known2; 8376 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8377 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8378 // We only care about the lower 32 bits. 8379 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8380 // Restore the original width by sign extending. 8381 Known = Known.sext(BitWidth); 8382 break; 8383 } 8384 case RISCVISD::DIVUW: { 8385 KnownBits Known2; 8386 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8387 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8388 // We only care about the lower 32 bits. 8389 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8390 // Restore the original width by sign extending. 8391 Known = Known.sext(BitWidth); 8392 break; 8393 } 8394 case RISCVISD::CTZW: { 8395 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8396 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8397 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8398 Known.Zero.setBitsFrom(LowBits); 8399 break; 8400 } 8401 case RISCVISD::CLZW: { 8402 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8403 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8404 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8405 Known.Zero.setBitsFrom(LowBits); 8406 break; 8407 } 8408 case RISCVISD::GREV: 8409 case RISCVISD::GREVW: { 8410 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8411 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8412 if (Opc == RISCVISD::GREVW) 8413 Known = Known.trunc(32); 8414 unsigned ShAmt = C->getZExtValue(); 8415 computeGREV(Known.Zero, ShAmt); 8416 computeGREV(Known.One, ShAmt); 8417 if (Opc == RISCVISD::GREVW) 8418 Known = Known.sext(BitWidth); 8419 } 8420 break; 8421 } 8422 case RISCVISD::READ_VLENB: { 8423 // If we know the minimum VLen from Zvl extensions, we can use that to 8424 // determine the trailing zeros of VLENB. 8425 // FIXME: Limit to 128 bit vectors until we have more testing. 8426 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8427 if (MinVLenB > 0) 8428 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8429 // We assume VLENB is no more than 65536 / 8 bytes. 8430 Known.Zero.setBitsFrom(14); 8431 break; 8432 } 8433 case ISD::INTRINSIC_W_CHAIN: 8434 case ISD::INTRINSIC_WO_CHAIN: { 8435 unsigned IntNo = 8436 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8437 switch (IntNo) { 8438 default: 8439 // We can't do anything for most intrinsics. 8440 break; 8441 case Intrinsic::riscv_vsetvli: 8442 case Intrinsic::riscv_vsetvlimax: 8443 case Intrinsic::riscv_vsetvli_opt: 8444 case Intrinsic::riscv_vsetvlimax_opt: 8445 // Assume that VL output is positive and would fit in an int32_t. 8446 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8447 if (BitWidth >= 32) 8448 Known.Zero.setBitsFrom(31); 8449 break; 8450 } 8451 break; 8452 } 8453 } 8454 } 8455 8456 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8457 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8458 unsigned Depth) const { 8459 switch (Op.getOpcode()) { 8460 default: 8461 break; 8462 case RISCVISD::SELECT_CC: { 8463 unsigned Tmp = 8464 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8465 if (Tmp == 1) return 1; // Early out. 8466 unsigned Tmp2 = 8467 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8468 return std::min(Tmp, Tmp2); 8469 } 8470 case RISCVISD::SLLW: 8471 case RISCVISD::SRAW: 8472 case RISCVISD::SRLW: 8473 case RISCVISD::DIVW: 8474 case RISCVISD::DIVUW: 8475 case RISCVISD::REMUW: 8476 case RISCVISD::ROLW: 8477 case RISCVISD::RORW: 8478 case RISCVISD::GREVW: 8479 case RISCVISD::GORCW: 8480 case RISCVISD::FSLW: 8481 case RISCVISD::FSRW: 8482 case RISCVISD::SHFLW: 8483 case RISCVISD::UNSHFLW: 8484 case RISCVISD::BCOMPRESSW: 8485 case RISCVISD::BDECOMPRESSW: 8486 case RISCVISD::BFPW: 8487 case RISCVISD::FCVT_W_RV64: 8488 case RISCVISD::FCVT_WU_RV64: 8489 case RISCVISD::STRICT_FCVT_W_RV64: 8490 case RISCVISD::STRICT_FCVT_WU_RV64: 8491 // TODO: As the result is sign-extended, this is conservatively correct. A 8492 // more precise answer could be calculated for SRAW depending on known 8493 // bits in the shift amount. 8494 return 33; 8495 case RISCVISD::SHFL: 8496 case RISCVISD::UNSHFL: { 8497 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8498 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8499 // will stay within the upper 32 bits. If there were more than 32 sign bits 8500 // before there will be at least 33 sign bits after. 8501 if (Op.getValueType() == MVT::i64 && 8502 isa<ConstantSDNode>(Op.getOperand(1)) && 8503 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8504 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8505 if (Tmp > 32) 8506 return 33; 8507 } 8508 break; 8509 } 8510 case RISCVISD::VMV_X_S: { 8511 // The number of sign bits of the scalar result is computed by obtaining the 8512 // element type of the input vector operand, subtracting its width from the 8513 // XLEN, and then adding one (sign bit within the element type). If the 8514 // element type is wider than XLen, the least-significant XLEN bits are 8515 // taken. 8516 unsigned XLen = Subtarget.getXLen(); 8517 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8518 if (EltBits <= XLen) 8519 return XLen - EltBits + 1; 8520 break; 8521 } 8522 } 8523 8524 return 1; 8525 } 8526 8527 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8528 MachineBasicBlock *BB) { 8529 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8530 8531 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8532 // Should the count have wrapped while it was being read, we need to try 8533 // again. 8534 // ... 8535 // read: 8536 // rdcycleh x3 # load high word of cycle 8537 // rdcycle x2 # load low word of cycle 8538 // rdcycleh x4 # load high word of cycle 8539 // bne x3, x4, read # check if high word reads match, otherwise try again 8540 // ... 8541 8542 MachineFunction &MF = *BB->getParent(); 8543 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8544 MachineFunction::iterator It = ++BB->getIterator(); 8545 8546 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8547 MF.insert(It, LoopMBB); 8548 8549 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8550 MF.insert(It, DoneMBB); 8551 8552 // Transfer the remainder of BB and its successor edges to DoneMBB. 8553 DoneMBB->splice(DoneMBB->begin(), BB, 8554 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8555 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8556 8557 BB->addSuccessor(LoopMBB); 8558 8559 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8560 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8561 Register LoReg = MI.getOperand(0).getReg(); 8562 Register HiReg = MI.getOperand(1).getReg(); 8563 DebugLoc DL = MI.getDebugLoc(); 8564 8565 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8566 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8567 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8568 .addReg(RISCV::X0); 8569 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8570 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8571 .addReg(RISCV::X0); 8572 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8573 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8574 .addReg(RISCV::X0); 8575 8576 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8577 .addReg(HiReg) 8578 .addReg(ReadAgainReg) 8579 .addMBB(LoopMBB); 8580 8581 LoopMBB->addSuccessor(LoopMBB); 8582 LoopMBB->addSuccessor(DoneMBB); 8583 8584 MI.eraseFromParent(); 8585 8586 return DoneMBB; 8587 } 8588 8589 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8590 MachineBasicBlock *BB) { 8591 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8592 8593 MachineFunction &MF = *BB->getParent(); 8594 DebugLoc DL = MI.getDebugLoc(); 8595 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8596 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8597 Register LoReg = MI.getOperand(0).getReg(); 8598 Register HiReg = MI.getOperand(1).getReg(); 8599 Register SrcReg = MI.getOperand(2).getReg(); 8600 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8601 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8602 8603 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8604 RI); 8605 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8606 MachineMemOperand *MMOLo = 8607 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8608 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8609 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8610 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8611 .addFrameIndex(FI) 8612 .addImm(0) 8613 .addMemOperand(MMOLo); 8614 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8615 .addFrameIndex(FI) 8616 .addImm(4) 8617 .addMemOperand(MMOHi); 8618 MI.eraseFromParent(); // The pseudo instruction is gone now. 8619 return BB; 8620 } 8621 8622 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8623 MachineBasicBlock *BB) { 8624 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8625 "Unexpected instruction"); 8626 8627 MachineFunction &MF = *BB->getParent(); 8628 DebugLoc DL = MI.getDebugLoc(); 8629 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8630 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8631 Register DstReg = MI.getOperand(0).getReg(); 8632 Register LoReg = MI.getOperand(1).getReg(); 8633 Register HiReg = MI.getOperand(2).getReg(); 8634 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8635 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8636 8637 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8638 MachineMemOperand *MMOLo = 8639 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8640 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8641 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8642 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8643 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8644 .addFrameIndex(FI) 8645 .addImm(0) 8646 .addMemOperand(MMOLo); 8647 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8648 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8649 .addFrameIndex(FI) 8650 .addImm(4) 8651 .addMemOperand(MMOHi); 8652 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8653 MI.eraseFromParent(); // The pseudo instruction is gone now. 8654 return BB; 8655 } 8656 8657 static bool isSelectPseudo(MachineInstr &MI) { 8658 switch (MI.getOpcode()) { 8659 default: 8660 return false; 8661 case RISCV::Select_GPR_Using_CC_GPR: 8662 case RISCV::Select_FPR16_Using_CC_GPR: 8663 case RISCV::Select_FPR32_Using_CC_GPR: 8664 case RISCV::Select_FPR64_Using_CC_GPR: 8665 return true; 8666 } 8667 } 8668 8669 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8670 unsigned RelOpcode, unsigned EqOpcode, 8671 const RISCVSubtarget &Subtarget) { 8672 DebugLoc DL = MI.getDebugLoc(); 8673 Register DstReg = MI.getOperand(0).getReg(); 8674 Register Src1Reg = MI.getOperand(1).getReg(); 8675 Register Src2Reg = MI.getOperand(2).getReg(); 8676 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8677 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8678 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8679 8680 // Save the current FFLAGS. 8681 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8682 8683 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8684 .addReg(Src1Reg) 8685 .addReg(Src2Reg); 8686 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8687 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8688 8689 // Restore the FFLAGS. 8690 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8691 .addReg(SavedFFlags, RegState::Kill); 8692 8693 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8694 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8695 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8696 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8697 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8698 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8699 8700 // Erase the pseudoinstruction. 8701 MI.eraseFromParent(); 8702 return BB; 8703 } 8704 8705 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8706 MachineBasicBlock *BB, 8707 const RISCVSubtarget &Subtarget) { 8708 // To "insert" Select_* instructions, we actually have to insert the triangle 8709 // control-flow pattern. The incoming instructions know the destination vreg 8710 // to set, the condition code register to branch on, the true/false values to 8711 // select between, and the condcode to use to select the appropriate branch. 8712 // 8713 // We produce the following control flow: 8714 // HeadMBB 8715 // | \ 8716 // | IfFalseMBB 8717 // | / 8718 // TailMBB 8719 // 8720 // When we find a sequence of selects we attempt to optimize their emission 8721 // by sharing the control flow. Currently we only handle cases where we have 8722 // multiple selects with the exact same condition (same LHS, RHS and CC). 8723 // The selects may be interleaved with other instructions if the other 8724 // instructions meet some requirements we deem safe: 8725 // - They are debug instructions. Otherwise, 8726 // - They do not have side-effects, do not access memory and their inputs do 8727 // not depend on the results of the select pseudo-instructions. 8728 // The TrueV/FalseV operands of the selects cannot depend on the result of 8729 // previous selects in the sequence. 8730 // These conditions could be further relaxed. See the X86 target for a 8731 // related approach and more information. 8732 Register LHS = MI.getOperand(1).getReg(); 8733 Register RHS = MI.getOperand(2).getReg(); 8734 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8735 8736 SmallVector<MachineInstr *, 4> SelectDebugValues; 8737 SmallSet<Register, 4> SelectDests; 8738 SelectDests.insert(MI.getOperand(0).getReg()); 8739 8740 MachineInstr *LastSelectPseudo = &MI; 8741 8742 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8743 SequenceMBBI != E; ++SequenceMBBI) { 8744 if (SequenceMBBI->isDebugInstr()) 8745 continue; 8746 else if (isSelectPseudo(*SequenceMBBI)) { 8747 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8748 SequenceMBBI->getOperand(2).getReg() != RHS || 8749 SequenceMBBI->getOperand(3).getImm() != CC || 8750 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8751 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8752 break; 8753 LastSelectPseudo = &*SequenceMBBI; 8754 SequenceMBBI->collectDebugValues(SelectDebugValues); 8755 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8756 } else { 8757 if (SequenceMBBI->hasUnmodeledSideEffects() || 8758 SequenceMBBI->mayLoadOrStore()) 8759 break; 8760 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8761 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8762 })) 8763 break; 8764 } 8765 } 8766 8767 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8768 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8769 DebugLoc DL = MI.getDebugLoc(); 8770 MachineFunction::iterator I = ++BB->getIterator(); 8771 8772 MachineBasicBlock *HeadMBB = BB; 8773 MachineFunction *F = BB->getParent(); 8774 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8775 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8776 8777 F->insert(I, IfFalseMBB); 8778 F->insert(I, TailMBB); 8779 8780 // Transfer debug instructions associated with the selects to TailMBB. 8781 for (MachineInstr *DebugInstr : SelectDebugValues) { 8782 TailMBB->push_back(DebugInstr->removeFromParent()); 8783 } 8784 8785 // Move all instructions after the sequence to TailMBB. 8786 TailMBB->splice(TailMBB->end(), HeadMBB, 8787 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8788 // Update machine-CFG edges by transferring all successors of the current 8789 // block to the new block which will contain the Phi nodes for the selects. 8790 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8791 // Set the successors for HeadMBB. 8792 HeadMBB->addSuccessor(IfFalseMBB); 8793 HeadMBB->addSuccessor(TailMBB); 8794 8795 // Insert appropriate branch. 8796 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8797 .addReg(LHS) 8798 .addReg(RHS) 8799 .addMBB(TailMBB); 8800 8801 // IfFalseMBB just falls through to TailMBB. 8802 IfFalseMBB->addSuccessor(TailMBB); 8803 8804 // Create PHIs for all of the select pseudo-instructions. 8805 auto SelectMBBI = MI.getIterator(); 8806 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8807 auto InsertionPoint = TailMBB->begin(); 8808 while (SelectMBBI != SelectEnd) { 8809 auto Next = std::next(SelectMBBI); 8810 if (isSelectPseudo(*SelectMBBI)) { 8811 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8812 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8813 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8814 .addReg(SelectMBBI->getOperand(4).getReg()) 8815 .addMBB(HeadMBB) 8816 .addReg(SelectMBBI->getOperand(5).getReg()) 8817 .addMBB(IfFalseMBB); 8818 SelectMBBI->eraseFromParent(); 8819 } 8820 SelectMBBI = Next; 8821 } 8822 8823 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8824 return TailMBB; 8825 } 8826 8827 MachineBasicBlock * 8828 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8829 MachineBasicBlock *BB) const { 8830 switch (MI.getOpcode()) { 8831 default: 8832 llvm_unreachable("Unexpected instr type to insert"); 8833 case RISCV::ReadCycleWide: 8834 assert(!Subtarget.is64Bit() && 8835 "ReadCycleWrite is only to be used on riscv32"); 8836 return emitReadCycleWidePseudo(MI, BB); 8837 case RISCV::Select_GPR_Using_CC_GPR: 8838 case RISCV::Select_FPR16_Using_CC_GPR: 8839 case RISCV::Select_FPR32_Using_CC_GPR: 8840 case RISCV::Select_FPR64_Using_CC_GPR: 8841 return emitSelectPseudo(MI, BB, Subtarget); 8842 case RISCV::BuildPairF64Pseudo: 8843 return emitBuildPairF64Pseudo(MI, BB); 8844 case RISCV::SplitF64Pseudo: 8845 return emitSplitF64Pseudo(MI, BB); 8846 case RISCV::PseudoQuietFLE_H: 8847 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 8848 case RISCV::PseudoQuietFLT_H: 8849 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 8850 case RISCV::PseudoQuietFLE_S: 8851 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 8852 case RISCV::PseudoQuietFLT_S: 8853 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 8854 case RISCV::PseudoQuietFLE_D: 8855 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 8856 case RISCV::PseudoQuietFLT_D: 8857 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 8858 } 8859 } 8860 8861 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8862 SDNode *Node) const { 8863 // Add FRM dependency to any instructions with dynamic rounding mode. 8864 unsigned Opc = MI.getOpcode(); 8865 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8866 if (Idx < 0) 8867 return; 8868 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8869 return; 8870 // If the instruction already reads FRM, don't add another read. 8871 if (MI.readsRegister(RISCV::FRM)) 8872 return; 8873 MI.addOperand( 8874 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8875 } 8876 8877 // Calling Convention Implementation. 8878 // The expectations for frontend ABI lowering vary from target to target. 8879 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8880 // details, but this is a longer term goal. For now, we simply try to keep the 8881 // role of the frontend as simple and well-defined as possible. The rules can 8882 // be summarised as: 8883 // * Never split up large scalar arguments. We handle them here. 8884 // * If a hardfloat calling convention is being used, and the struct may be 8885 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8886 // available, then pass as two separate arguments. If either the GPRs or FPRs 8887 // are exhausted, then pass according to the rule below. 8888 // * If a struct could never be passed in registers or directly in a stack 8889 // slot (as it is larger than 2*XLEN and the floating point rules don't 8890 // apply), then pass it using a pointer with the byval attribute. 8891 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8892 // word-sized array or a 2*XLEN scalar (depending on alignment). 8893 // * The frontend can determine whether a struct is returned by reference or 8894 // not based on its size and fields. If it will be returned by reference, the 8895 // frontend must modify the prototype so a pointer with the sret annotation is 8896 // passed as the first argument. This is not necessary for large scalar 8897 // returns. 8898 // * Struct return values and varargs should be coerced to structs containing 8899 // register-size fields in the same situations they would be for fixed 8900 // arguments. 8901 8902 static const MCPhysReg ArgGPRs[] = { 8903 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8904 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8905 }; 8906 static const MCPhysReg ArgFPR16s[] = { 8907 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8908 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8909 }; 8910 static const MCPhysReg ArgFPR32s[] = { 8911 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8912 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8913 }; 8914 static const MCPhysReg ArgFPR64s[] = { 8915 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8916 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8917 }; 8918 // This is an interim calling convention and it may be changed in the future. 8919 static const MCPhysReg ArgVRs[] = { 8920 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8921 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8922 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8923 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8924 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8925 RISCV::V20M2, RISCV::V22M2}; 8926 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8927 RISCV::V20M4}; 8928 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8929 8930 // Pass a 2*XLEN argument that has been split into two XLEN values through 8931 // registers or the stack as necessary. 8932 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8933 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8934 MVT ValVT2, MVT LocVT2, 8935 ISD::ArgFlagsTy ArgFlags2) { 8936 unsigned XLenInBytes = XLen / 8; 8937 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8938 // At least one half can be passed via register. 8939 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8940 VA1.getLocVT(), CCValAssign::Full)); 8941 } else { 8942 // Both halves must be passed on the stack, with proper alignment. 8943 Align StackAlign = 8944 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8945 State.addLoc( 8946 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8947 State.AllocateStack(XLenInBytes, StackAlign), 8948 VA1.getLocVT(), CCValAssign::Full)); 8949 State.addLoc(CCValAssign::getMem( 8950 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8951 LocVT2, CCValAssign::Full)); 8952 return false; 8953 } 8954 8955 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8956 // The second half can also be passed via register. 8957 State.addLoc( 8958 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8959 } else { 8960 // The second half is passed via the stack, without additional alignment. 8961 State.addLoc(CCValAssign::getMem( 8962 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8963 LocVT2, CCValAssign::Full)); 8964 } 8965 8966 return false; 8967 } 8968 8969 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8970 Optional<unsigned> FirstMaskArgument, 8971 CCState &State, const RISCVTargetLowering &TLI) { 8972 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8973 if (RC == &RISCV::VRRegClass) { 8974 // Assign the first mask argument to V0. 8975 // This is an interim calling convention and it may be changed in the 8976 // future. 8977 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8978 return State.AllocateReg(RISCV::V0); 8979 return State.AllocateReg(ArgVRs); 8980 } 8981 if (RC == &RISCV::VRM2RegClass) 8982 return State.AllocateReg(ArgVRM2s); 8983 if (RC == &RISCV::VRM4RegClass) 8984 return State.AllocateReg(ArgVRM4s); 8985 if (RC == &RISCV::VRM8RegClass) 8986 return State.AllocateReg(ArgVRM8s); 8987 llvm_unreachable("Unhandled register class for ValueType"); 8988 } 8989 8990 // Implements the RISC-V calling convention. Returns true upon failure. 8991 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8992 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8993 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8994 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8995 Optional<unsigned> FirstMaskArgument) { 8996 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8997 assert(XLen == 32 || XLen == 64); 8998 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8999 9000 // Any return value split in to more than two values can't be returned 9001 // directly. Vectors are returned via the available vector registers. 9002 if (!LocVT.isVector() && IsRet && ValNo > 1) 9003 return true; 9004 9005 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9006 // variadic argument, or if no F16/F32 argument registers are available. 9007 bool UseGPRForF16_F32 = true; 9008 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9009 // variadic argument, or if no F64 argument registers are available. 9010 bool UseGPRForF64 = true; 9011 9012 switch (ABI) { 9013 default: 9014 llvm_unreachable("Unexpected ABI"); 9015 case RISCVABI::ABI_ILP32: 9016 case RISCVABI::ABI_LP64: 9017 break; 9018 case RISCVABI::ABI_ILP32F: 9019 case RISCVABI::ABI_LP64F: 9020 UseGPRForF16_F32 = !IsFixed; 9021 break; 9022 case RISCVABI::ABI_ILP32D: 9023 case RISCVABI::ABI_LP64D: 9024 UseGPRForF16_F32 = !IsFixed; 9025 UseGPRForF64 = !IsFixed; 9026 break; 9027 } 9028 9029 // FPR16, FPR32, and FPR64 alias each other. 9030 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9031 UseGPRForF16_F32 = true; 9032 UseGPRForF64 = true; 9033 } 9034 9035 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9036 // similar local variables rather than directly checking against the target 9037 // ABI. 9038 9039 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9040 LocVT = XLenVT; 9041 LocInfo = CCValAssign::BCvt; 9042 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9043 LocVT = MVT::i64; 9044 LocInfo = CCValAssign::BCvt; 9045 } 9046 9047 // If this is a variadic argument, the RISC-V calling convention requires 9048 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9049 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9050 // be used regardless of whether the original argument was split during 9051 // legalisation or not. The argument will not be passed by registers if the 9052 // original type is larger than 2*XLEN, so the register alignment rule does 9053 // not apply. 9054 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9055 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9056 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9057 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9058 // Skip 'odd' register if necessary. 9059 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9060 State.AllocateReg(ArgGPRs); 9061 } 9062 9063 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9064 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9065 State.getPendingArgFlags(); 9066 9067 assert(PendingLocs.size() == PendingArgFlags.size() && 9068 "PendingLocs and PendingArgFlags out of sync"); 9069 9070 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9071 // registers are exhausted. 9072 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9073 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9074 "Can't lower f64 if it is split"); 9075 // Depending on available argument GPRS, f64 may be passed in a pair of 9076 // GPRs, split between a GPR and the stack, or passed completely on the 9077 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9078 // cases. 9079 Register Reg = State.AllocateReg(ArgGPRs); 9080 LocVT = MVT::i32; 9081 if (!Reg) { 9082 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9083 State.addLoc( 9084 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9085 return false; 9086 } 9087 if (!State.AllocateReg(ArgGPRs)) 9088 State.AllocateStack(4, Align(4)); 9089 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9090 return false; 9091 } 9092 9093 // Fixed-length vectors are located in the corresponding scalable-vector 9094 // container types. 9095 if (ValVT.isFixedLengthVector()) 9096 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9097 9098 // Split arguments might be passed indirectly, so keep track of the pending 9099 // values. Split vectors are passed via a mix of registers and indirectly, so 9100 // treat them as we would any other argument. 9101 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9102 LocVT = XLenVT; 9103 LocInfo = CCValAssign::Indirect; 9104 PendingLocs.push_back( 9105 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9106 PendingArgFlags.push_back(ArgFlags); 9107 if (!ArgFlags.isSplitEnd()) { 9108 return false; 9109 } 9110 } 9111 9112 // If the split argument only had two elements, it should be passed directly 9113 // in registers or on the stack. 9114 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9115 PendingLocs.size() <= 2) { 9116 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9117 // Apply the normal calling convention rules to the first half of the 9118 // split argument. 9119 CCValAssign VA = PendingLocs[0]; 9120 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9121 PendingLocs.clear(); 9122 PendingArgFlags.clear(); 9123 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9124 ArgFlags); 9125 } 9126 9127 // Allocate to a register if possible, or else a stack slot. 9128 Register Reg; 9129 unsigned StoreSizeBytes = XLen / 8; 9130 Align StackAlign = Align(XLen / 8); 9131 9132 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9133 Reg = State.AllocateReg(ArgFPR16s); 9134 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9135 Reg = State.AllocateReg(ArgFPR32s); 9136 else if (ValVT == MVT::f64 && !UseGPRForF64) 9137 Reg = State.AllocateReg(ArgFPR64s); 9138 else if (ValVT.isVector()) { 9139 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9140 if (!Reg) { 9141 // For return values, the vector must be passed fully via registers or 9142 // via the stack. 9143 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9144 // but we're using all of them. 9145 if (IsRet) 9146 return true; 9147 // Try using a GPR to pass the address 9148 if ((Reg = State.AllocateReg(ArgGPRs))) { 9149 LocVT = XLenVT; 9150 LocInfo = CCValAssign::Indirect; 9151 } else if (ValVT.isScalableVector()) { 9152 LocVT = XLenVT; 9153 LocInfo = CCValAssign::Indirect; 9154 } else { 9155 // Pass fixed-length vectors on the stack. 9156 LocVT = ValVT; 9157 StoreSizeBytes = ValVT.getStoreSize(); 9158 // Align vectors to their element sizes, being careful for vXi1 9159 // vectors. 9160 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9161 } 9162 } 9163 } else { 9164 Reg = State.AllocateReg(ArgGPRs); 9165 } 9166 9167 unsigned StackOffset = 9168 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9169 9170 // If we reach this point and PendingLocs is non-empty, we must be at the 9171 // end of a split argument that must be passed indirectly. 9172 if (!PendingLocs.empty()) { 9173 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9174 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9175 9176 for (auto &It : PendingLocs) { 9177 if (Reg) 9178 It.convertToReg(Reg); 9179 else 9180 It.convertToMem(StackOffset); 9181 State.addLoc(It); 9182 } 9183 PendingLocs.clear(); 9184 PendingArgFlags.clear(); 9185 return false; 9186 } 9187 9188 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9189 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9190 "Expected an XLenVT or vector types at this stage"); 9191 9192 if (Reg) { 9193 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9194 return false; 9195 } 9196 9197 // When a floating-point value is passed on the stack, no bit-conversion is 9198 // needed. 9199 if (ValVT.isFloatingPoint()) { 9200 LocVT = ValVT; 9201 LocInfo = CCValAssign::Full; 9202 } 9203 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9204 return false; 9205 } 9206 9207 template <typename ArgTy> 9208 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9209 for (const auto &ArgIdx : enumerate(Args)) { 9210 MVT ArgVT = ArgIdx.value().VT; 9211 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9212 return ArgIdx.index(); 9213 } 9214 return None; 9215 } 9216 9217 void RISCVTargetLowering::analyzeInputArgs( 9218 MachineFunction &MF, CCState &CCInfo, 9219 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9220 RISCVCCAssignFn Fn) const { 9221 unsigned NumArgs = Ins.size(); 9222 FunctionType *FType = MF.getFunction().getFunctionType(); 9223 9224 Optional<unsigned> FirstMaskArgument; 9225 if (Subtarget.hasVInstructions()) 9226 FirstMaskArgument = preAssignMask(Ins); 9227 9228 for (unsigned i = 0; i != NumArgs; ++i) { 9229 MVT ArgVT = Ins[i].VT; 9230 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9231 9232 Type *ArgTy = nullptr; 9233 if (IsRet) 9234 ArgTy = FType->getReturnType(); 9235 else if (Ins[i].isOrigArg()) 9236 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9237 9238 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9239 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9240 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9241 FirstMaskArgument)) { 9242 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9243 << EVT(ArgVT).getEVTString() << '\n'); 9244 llvm_unreachable(nullptr); 9245 } 9246 } 9247 } 9248 9249 void RISCVTargetLowering::analyzeOutputArgs( 9250 MachineFunction &MF, CCState &CCInfo, 9251 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9252 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9253 unsigned NumArgs = Outs.size(); 9254 9255 Optional<unsigned> FirstMaskArgument; 9256 if (Subtarget.hasVInstructions()) 9257 FirstMaskArgument = preAssignMask(Outs); 9258 9259 for (unsigned i = 0; i != NumArgs; i++) { 9260 MVT ArgVT = Outs[i].VT; 9261 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9262 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9263 9264 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9265 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9266 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9267 FirstMaskArgument)) { 9268 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9269 << EVT(ArgVT).getEVTString() << "\n"); 9270 llvm_unreachable(nullptr); 9271 } 9272 } 9273 } 9274 9275 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9276 // values. 9277 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9278 const CCValAssign &VA, const SDLoc &DL, 9279 const RISCVSubtarget &Subtarget) { 9280 switch (VA.getLocInfo()) { 9281 default: 9282 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9283 case CCValAssign::Full: 9284 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9285 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9286 break; 9287 case CCValAssign::BCvt: 9288 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9289 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9290 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9291 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9292 else 9293 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9294 break; 9295 } 9296 return Val; 9297 } 9298 9299 // The caller is responsible for loading the full value if the argument is 9300 // passed with CCValAssign::Indirect. 9301 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9302 const CCValAssign &VA, const SDLoc &DL, 9303 const RISCVTargetLowering &TLI) { 9304 MachineFunction &MF = DAG.getMachineFunction(); 9305 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9306 EVT LocVT = VA.getLocVT(); 9307 SDValue Val; 9308 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9309 Register VReg = RegInfo.createVirtualRegister(RC); 9310 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9311 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9312 9313 if (VA.getLocInfo() == CCValAssign::Indirect) 9314 return Val; 9315 9316 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9317 } 9318 9319 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9320 const CCValAssign &VA, const SDLoc &DL, 9321 const RISCVSubtarget &Subtarget) { 9322 EVT LocVT = VA.getLocVT(); 9323 9324 switch (VA.getLocInfo()) { 9325 default: 9326 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9327 case CCValAssign::Full: 9328 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9329 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9330 break; 9331 case CCValAssign::BCvt: 9332 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9333 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9334 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9335 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9336 else 9337 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9338 break; 9339 } 9340 return Val; 9341 } 9342 9343 // The caller is responsible for loading the full value if the argument is 9344 // passed with CCValAssign::Indirect. 9345 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9346 const CCValAssign &VA, const SDLoc &DL) { 9347 MachineFunction &MF = DAG.getMachineFunction(); 9348 MachineFrameInfo &MFI = MF.getFrameInfo(); 9349 EVT LocVT = VA.getLocVT(); 9350 EVT ValVT = VA.getValVT(); 9351 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9352 if (ValVT.isScalableVector()) { 9353 // When the value is a scalable vector, we save the pointer which points to 9354 // the scalable vector value in the stack. The ValVT will be the pointer 9355 // type, instead of the scalable vector type. 9356 ValVT = LocVT; 9357 } 9358 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9359 /*IsImmutable=*/true); 9360 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9361 SDValue Val; 9362 9363 ISD::LoadExtType ExtType; 9364 switch (VA.getLocInfo()) { 9365 default: 9366 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9367 case CCValAssign::Full: 9368 case CCValAssign::Indirect: 9369 case CCValAssign::BCvt: 9370 ExtType = ISD::NON_EXTLOAD; 9371 break; 9372 } 9373 Val = DAG.getExtLoad( 9374 ExtType, DL, LocVT, Chain, FIN, 9375 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9376 return Val; 9377 } 9378 9379 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9380 const CCValAssign &VA, const SDLoc &DL) { 9381 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9382 "Unexpected VA"); 9383 MachineFunction &MF = DAG.getMachineFunction(); 9384 MachineFrameInfo &MFI = MF.getFrameInfo(); 9385 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9386 9387 if (VA.isMemLoc()) { 9388 // f64 is passed on the stack. 9389 int FI = 9390 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9391 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9392 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9393 MachinePointerInfo::getFixedStack(MF, FI)); 9394 } 9395 9396 assert(VA.isRegLoc() && "Expected register VA assignment"); 9397 9398 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9399 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9400 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9401 SDValue Hi; 9402 if (VA.getLocReg() == RISCV::X17) { 9403 // Second half of f64 is passed on the stack. 9404 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9405 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9406 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9407 MachinePointerInfo::getFixedStack(MF, FI)); 9408 } else { 9409 // Second half of f64 is passed in another GPR. 9410 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9411 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9412 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9413 } 9414 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9415 } 9416 9417 // FastCC has less than 1% performance improvement for some particular 9418 // benchmark. But theoretically, it may has benenfit for some cases. 9419 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9420 unsigned ValNo, MVT ValVT, MVT LocVT, 9421 CCValAssign::LocInfo LocInfo, 9422 ISD::ArgFlagsTy ArgFlags, CCState &State, 9423 bool IsFixed, bool IsRet, Type *OrigTy, 9424 const RISCVTargetLowering &TLI, 9425 Optional<unsigned> FirstMaskArgument) { 9426 9427 // X5 and X6 might be used for save-restore libcall. 9428 static const MCPhysReg GPRList[] = { 9429 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9430 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9431 RISCV::X29, RISCV::X30, RISCV::X31}; 9432 9433 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9434 if (unsigned Reg = State.AllocateReg(GPRList)) { 9435 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9436 return false; 9437 } 9438 } 9439 9440 if (LocVT == MVT::f16) { 9441 static const MCPhysReg FPR16List[] = { 9442 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9443 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9444 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9445 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9446 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9447 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9448 return false; 9449 } 9450 } 9451 9452 if (LocVT == MVT::f32) { 9453 static const MCPhysReg FPR32List[] = { 9454 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9455 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9456 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9457 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9458 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9459 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9460 return false; 9461 } 9462 } 9463 9464 if (LocVT == MVT::f64) { 9465 static const MCPhysReg FPR64List[] = { 9466 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9467 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9468 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9469 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9470 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9471 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9472 return false; 9473 } 9474 } 9475 9476 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9477 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9478 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9479 return false; 9480 } 9481 9482 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9483 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9484 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9485 return false; 9486 } 9487 9488 if (LocVT.isVector()) { 9489 if (unsigned Reg = 9490 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9491 // Fixed-length vectors are located in the corresponding scalable-vector 9492 // container types. 9493 if (ValVT.isFixedLengthVector()) 9494 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9495 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9496 } else { 9497 // Try and pass the address via a "fast" GPR. 9498 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9499 LocInfo = CCValAssign::Indirect; 9500 LocVT = TLI.getSubtarget().getXLenVT(); 9501 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9502 } else if (ValVT.isFixedLengthVector()) { 9503 auto StackAlign = 9504 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9505 unsigned StackOffset = 9506 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9507 State.addLoc( 9508 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9509 } else { 9510 // Can't pass scalable vectors on the stack. 9511 return true; 9512 } 9513 } 9514 9515 return false; 9516 } 9517 9518 return true; // CC didn't match. 9519 } 9520 9521 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9522 CCValAssign::LocInfo LocInfo, 9523 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9524 9525 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9526 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9527 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9528 static const MCPhysReg GPRList[] = { 9529 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9530 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9531 if (unsigned Reg = State.AllocateReg(GPRList)) { 9532 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9533 return false; 9534 } 9535 } 9536 9537 if (LocVT == MVT::f32) { 9538 // Pass in STG registers: F1, ..., F6 9539 // fs0 ... fs5 9540 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9541 RISCV::F18_F, RISCV::F19_F, 9542 RISCV::F20_F, RISCV::F21_F}; 9543 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9544 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9545 return false; 9546 } 9547 } 9548 9549 if (LocVT == MVT::f64) { 9550 // Pass in STG registers: D1, ..., D6 9551 // fs6 ... fs11 9552 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9553 RISCV::F24_D, RISCV::F25_D, 9554 RISCV::F26_D, RISCV::F27_D}; 9555 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9556 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9557 return false; 9558 } 9559 } 9560 9561 report_fatal_error("No registers left in GHC calling convention"); 9562 return true; 9563 } 9564 9565 // Transform physical registers into virtual registers. 9566 SDValue RISCVTargetLowering::LowerFormalArguments( 9567 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9568 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9569 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9570 9571 MachineFunction &MF = DAG.getMachineFunction(); 9572 9573 switch (CallConv) { 9574 default: 9575 report_fatal_error("Unsupported calling convention"); 9576 case CallingConv::C: 9577 case CallingConv::Fast: 9578 break; 9579 case CallingConv::GHC: 9580 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9581 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9582 report_fatal_error( 9583 "GHC calling convention requires the F and D instruction set extensions"); 9584 } 9585 9586 const Function &Func = MF.getFunction(); 9587 if (Func.hasFnAttribute("interrupt")) { 9588 if (!Func.arg_empty()) 9589 report_fatal_error( 9590 "Functions with the interrupt attribute cannot have arguments!"); 9591 9592 StringRef Kind = 9593 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9594 9595 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9596 report_fatal_error( 9597 "Function interrupt attribute argument not supported!"); 9598 } 9599 9600 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9601 MVT XLenVT = Subtarget.getXLenVT(); 9602 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9603 // Used with vargs to acumulate store chains. 9604 std::vector<SDValue> OutChains; 9605 9606 // Assign locations to all of the incoming arguments. 9607 SmallVector<CCValAssign, 16> ArgLocs; 9608 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9609 9610 if (CallConv == CallingConv::GHC) 9611 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9612 else 9613 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9614 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9615 : CC_RISCV); 9616 9617 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9618 CCValAssign &VA = ArgLocs[i]; 9619 SDValue ArgValue; 9620 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9621 // case. 9622 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9623 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9624 else if (VA.isRegLoc()) 9625 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9626 else 9627 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9628 9629 if (VA.getLocInfo() == CCValAssign::Indirect) { 9630 // If the original argument was split and passed by reference (e.g. i128 9631 // on RV32), we need to load all parts of it here (using the same 9632 // address). Vectors may be partly split to registers and partly to the 9633 // stack, in which case the base address is partly offset and subsequent 9634 // stores are relative to that. 9635 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9636 MachinePointerInfo())); 9637 unsigned ArgIndex = Ins[i].OrigArgIndex; 9638 unsigned ArgPartOffset = Ins[i].PartOffset; 9639 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9640 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9641 CCValAssign &PartVA = ArgLocs[i + 1]; 9642 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9643 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9644 if (PartVA.getValVT().isScalableVector()) 9645 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9646 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9647 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9648 MachinePointerInfo())); 9649 ++i; 9650 } 9651 continue; 9652 } 9653 InVals.push_back(ArgValue); 9654 } 9655 9656 if (IsVarArg) { 9657 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9658 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9659 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9660 MachineFrameInfo &MFI = MF.getFrameInfo(); 9661 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9662 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9663 9664 // Offset of the first variable argument from stack pointer, and size of 9665 // the vararg save area. For now, the varargs save area is either zero or 9666 // large enough to hold a0-a7. 9667 int VaArgOffset, VarArgsSaveSize; 9668 9669 // If all registers are allocated, then all varargs must be passed on the 9670 // stack and we don't need to save any argregs. 9671 if (ArgRegs.size() == Idx) { 9672 VaArgOffset = CCInfo.getNextStackOffset(); 9673 VarArgsSaveSize = 0; 9674 } else { 9675 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9676 VaArgOffset = -VarArgsSaveSize; 9677 } 9678 9679 // Record the frame index of the first variable argument 9680 // which is a value necessary to VASTART. 9681 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9682 RVFI->setVarArgsFrameIndex(FI); 9683 9684 // If saving an odd number of registers then create an extra stack slot to 9685 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9686 // offsets to even-numbered registered remain 2*XLEN-aligned. 9687 if (Idx % 2) { 9688 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9689 VarArgsSaveSize += XLenInBytes; 9690 } 9691 9692 // Copy the integer registers that may have been used for passing varargs 9693 // to the vararg save area. 9694 for (unsigned I = Idx; I < ArgRegs.size(); 9695 ++I, VaArgOffset += XLenInBytes) { 9696 const Register Reg = RegInfo.createVirtualRegister(RC); 9697 RegInfo.addLiveIn(ArgRegs[I], Reg); 9698 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9699 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9700 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9701 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9702 MachinePointerInfo::getFixedStack(MF, FI)); 9703 cast<StoreSDNode>(Store.getNode()) 9704 ->getMemOperand() 9705 ->setValue((Value *)nullptr); 9706 OutChains.push_back(Store); 9707 } 9708 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9709 } 9710 9711 // All stores are grouped in one node to allow the matching between 9712 // the size of Ins and InVals. This only happens for vararg functions. 9713 if (!OutChains.empty()) { 9714 OutChains.push_back(Chain); 9715 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 9716 } 9717 9718 return Chain; 9719 } 9720 9721 /// isEligibleForTailCallOptimization - Check whether the call is eligible 9722 /// for tail call optimization. 9723 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 9724 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 9725 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 9726 const SmallVector<CCValAssign, 16> &ArgLocs) const { 9727 9728 auto &Callee = CLI.Callee; 9729 auto CalleeCC = CLI.CallConv; 9730 auto &Outs = CLI.Outs; 9731 auto &Caller = MF.getFunction(); 9732 auto CallerCC = Caller.getCallingConv(); 9733 9734 // Exception-handling functions need a special set of instructions to 9735 // indicate a return to the hardware. Tail-calling another function would 9736 // probably break this. 9737 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 9738 // should be expanded as new function attributes are introduced. 9739 if (Caller.hasFnAttribute("interrupt")) 9740 return false; 9741 9742 // Do not tail call opt if the stack is used to pass parameters. 9743 if (CCInfo.getNextStackOffset() != 0) 9744 return false; 9745 9746 // Do not tail call opt if any parameters need to be passed indirectly. 9747 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9748 // passed indirectly. So the address of the value will be passed in a 9749 // register, or if not available, then the address is put on the stack. In 9750 // order to pass indirectly, space on the stack often needs to be allocated 9751 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9752 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9753 // are passed CCValAssign::Indirect. 9754 for (auto &VA : ArgLocs) 9755 if (VA.getLocInfo() == CCValAssign::Indirect) 9756 return false; 9757 9758 // Do not tail call opt if either caller or callee uses struct return 9759 // semantics. 9760 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9761 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9762 if (IsCallerStructRet || IsCalleeStructRet) 9763 return false; 9764 9765 // Externally-defined functions with weak linkage should not be 9766 // tail-called. The behaviour of branch instructions in this situation (as 9767 // used for tail calls) is implementation-defined, so we cannot rely on the 9768 // linker replacing the tail call with a return. 9769 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9770 const GlobalValue *GV = G->getGlobal(); 9771 if (GV->hasExternalWeakLinkage()) 9772 return false; 9773 } 9774 9775 // The callee has to preserve all registers the caller needs to preserve. 9776 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9777 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9778 if (CalleeCC != CallerCC) { 9779 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9780 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9781 return false; 9782 } 9783 9784 // Byval parameters hand the function a pointer directly into the stack area 9785 // we want to reuse during a tail call. Working around this *is* possible 9786 // but less efficient and uglier in LowerCall. 9787 for (auto &Arg : Outs) 9788 if (Arg.Flags.isByVal()) 9789 return false; 9790 9791 return true; 9792 } 9793 9794 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9795 return DAG.getDataLayout().getPrefTypeAlign( 9796 VT.getTypeForEVT(*DAG.getContext())); 9797 } 9798 9799 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9800 // and output parameter nodes. 9801 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9802 SmallVectorImpl<SDValue> &InVals) const { 9803 SelectionDAG &DAG = CLI.DAG; 9804 SDLoc &DL = CLI.DL; 9805 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9806 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9807 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9808 SDValue Chain = CLI.Chain; 9809 SDValue Callee = CLI.Callee; 9810 bool &IsTailCall = CLI.IsTailCall; 9811 CallingConv::ID CallConv = CLI.CallConv; 9812 bool IsVarArg = CLI.IsVarArg; 9813 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9814 MVT XLenVT = Subtarget.getXLenVT(); 9815 9816 MachineFunction &MF = DAG.getMachineFunction(); 9817 9818 // Analyze the operands of the call, assigning locations to each operand. 9819 SmallVector<CCValAssign, 16> ArgLocs; 9820 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9821 9822 if (CallConv == CallingConv::GHC) 9823 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9824 else 9825 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9826 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9827 : CC_RISCV); 9828 9829 // Check if it's really possible to do a tail call. 9830 if (IsTailCall) 9831 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9832 9833 if (IsTailCall) 9834 ++NumTailCalls; 9835 else if (CLI.CB && CLI.CB->isMustTailCall()) 9836 report_fatal_error("failed to perform tail call elimination on a call " 9837 "site marked musttail"); 9838 9839 // Get a count of how many bytes are to be pushed on the stack. 9840 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9841 9842 // Create local copies for byval args 9843 SmallVector<SDValue, 8> ByValArgs; 9844 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9845 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9846 if (!Flags.isByVal()) 9847 continue; 9848 9849 SDValue Arg = OutVals[i]; 9850 unsigned Size = Flags.getByValSize(); 9851 Align Alignment = Flags.getNonZeroByValAlign(); 9852 9853 int FI = 9854 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9855 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9856 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9857 9858 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9859 /*IsVolatile=*/false, 9860 /*AlwaysInline=*/false, IsTailCall, 9861 MachinePointerInfo(), MachinePointerInfo()); 9862 ByValArgs.push_back(FIPtr); 9863 } 9864 9865 if (!IsTailCall) 9866 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9867 9868 // Copy argument values to their designated locations. 9869 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9870 SmallVector<SDValue, 8> MemOpChains; 9871 SDValue StackPtr; 9872 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9873 CCValAssign &VA = ArgLocs[i]; 9874 SDValue ArgValue = OutVals[i]; 9875 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9876 9877 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9878 bool IsF64OnRV32DSoftABI = 9879 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9880 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9881 SDValue SplitF64 = DAG.getNode( 9882 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9883 SDValue Lo = SplitF64.getValue(0); 9884 SDValue Hi = SplitF64.getValue(1); 9885 9886 Register RegLo = VA.getLocReg(); 9887 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9888 9889 if (RegLo == RISCV::X17) { 9890 // Second half of f64 is passed on the stack. 9891 // Work out the address of the stack slot. 9892 if (!StackPtr.getNode()) 9893 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9894 // Emit the store. 9895 MemOpChains.push_back( 9896 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9897 } else { 9898 // Second half of f64 is passed in another GPR. 9899 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9900 Register RegHigh = RegLo + 1; 9901 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9902 } 9903 continue; 9904 } 9905 9906 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9907 // as any other MemLoc. 9908 9909 // Promote the value if needed. 9910 // For now, only handle fully promoted and indirect arguments. 9911 if (VA.getLocInfo() == CCValAssign::Indirect) { 9912 // Store the argument in a stack slot and pass its address. 9913 Align StackAlign = 9914 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9915 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9916 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9917 // If the original argument was split (e.g. i128), we need 9918 // to store the required parts of it here (and pass just one address). 9919 // Vectors may be partly split to registers and partly to the stack, in 9920 // which case the base address is partly offset and subsequent stores are 9921 // relative to that. 9922 unsigned ArgIndex = Outs[i].OrigArgIndex; 9923 unsigned ArgPartOffset = Outs[i].PartOffset; 9924 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9925 // Calculate the total size to store. We don't have access to what we're 9926 // actually storing other than performing the loop and collecting the 9927 // info. 9928 SmallVector<std::pair<SDValue, SDValue>> Parts; 9929 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9930 SDValue PartValue = OutVals[i + 1]; 9931 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9932 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9933 EVT PartVT = PartValue.getValueType(); 9934 if (PartVT.isScalableVector()) 9935 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9936 StoredSize += PartVT.getStoreSize(); 9937 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9938 Parts.push_back(std::make_pair(PartValue, Offset)); 9939 ++i; 9940 } 9941 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9942 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9943 MemOpChains.push_back( 9944 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9945 MachinePointerInfo::getFixedStack(MF, FI))); 9946 for (const auto &Part : Parts) { 9947 SDValue PartValue = Part.first; 9948 SDValue PartOffset = Part.second; 9949 SDValue Address = 9950 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9951 MemOpChains.push_back( 9952 DAG.getStore(Chain, DL, PartValue, Address, 9953 MachinePointerInfo::getFixedStack(MF, FI))); 9954 } 9955 ArgValue = SpillSlot; 9956 } else { 9957 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9958 } 9959 9960 // Use local copy if it is a byval arg. 9961 if (Flags.isByVal()) 9962 ArgValue = ByValArgs[j++]; 9963 9964 if (VA.isRegLoc()) { 9965 // Queue up the argument copies and emit them at the end. 9966 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9967 } else { 9968 assert(VA.isMemLoc() && "Argument not register or memory"); 9969 assert(!IsTailCall && "Tail call not allowed if stack is used " 9970 "for passing parameters"); 9971 9972 // Work out the address of the stack slot. 9973 if (!StackPtr.getNode()) 9974 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9975 SDValue Address = 9976 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9977 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9978 9979 // Emit the store. 9980 MemOpChains.push_back( 9981 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9982 } 9983 } 9984 9985 // Join the stores, which are independent of one another. 9986 if (!MemOpChains.empty()) 9987 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9988 9989 SDValue Glue; 9990 9991 // Build a sequence of copy-to-reg nodes, chained and glued together. 9992 for (auto &Reg : RegsToPass) { 9993 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9994 Glue = Chain.getValue(1); 9995 } 9996 9997 // Validate that none of the argument registers have been marked as 9998 // reserved, if so report an error. Do the same for the return address if this 9999 // is not a tailcall. 10000 validateCCReservedRegs(RegsToPass, MF); 10001 if (!IsTailCall && 10002 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10003 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10004 MF.getFunction(), 10005 "Return address register required, but has been reserved."}); 10006 10007 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10008 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10009 // split it and then direct call can be matched by PseudoCALL. 10010 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10011 const GlobalValue *GV = S->getGlobal(); 10012 10013 unsigned OpFlags = RISCVII::MO_CALL; 10014 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10015 OpFlags = RISCVII::MO_PLT; 10016 10017 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10018 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10019 unsigned OpFlags = RISCVII::MO_CALL; 10020 10021 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10022 nullptr)) 10023 OpFlags = RISCVII::MO_PLT; 10024 10025 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10026 } 10027 10028 // The first call operand is the chain and the second is the target address. 10029 SmallVector<SDValue, 8> Ops; 10030 Ops.push_back(Chain); 10031 Ops.push_back(Callee); 10032 10033 // Add argument registers to the end of the list so that they are 10034 // known live into the call. 10035 for (auto &Reg : RegsToPass) 10036 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10037 10038 if (!IsTailCall) { 10039 // Add a register mask operand representing the call-preserved registers. 10040 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10041 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10042 assert(Mask && "Missing call preserved mask for calling convention"); 10043 Ops.push_back(DAG.getRegisterMask(Mask)); 10044 } 10045 10046 // Glue the call to the argument copies, if any. 10047 if (Glue.getNode()) 10048 Ops.push_back(Glue); 10049 10050 // Emit the call. 10051 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10052 10053 if (IsTailCall) { 10054 MF.getFrameInfo().setHasTailCall(); 10055 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10056 } 10057 10058 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10059 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10060 Glue = Chain.getValue(1); 10061 10062 // Mark the end of the call, which is glued to the call itself. 10063 Chain = DAG.getCALLSEQ_END(Chain, 10064 DAG.getConstant(NumBytes, DL, PtrVT, true), 10065 DAG.getConstant(0, DL, PtrVT, true), 10066 Glue, DL); 10067 Glue = Chain.getValue(1); 10068 10069 // Assign locations to each value returned by this call. 10070 SmallVector<CCValAssign, 16> RVLocs; 10071 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10072 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10073 10074 // Copy all of the result registers out of their specified physreg. 10075 for (auto &VA : RVLocs) { 10076 // Copy the value out 10077 SDValue RetValue = 10078 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10079 // Glue the RetValue to the end of the call sequence 10080 Chain = RetValue.getValue(1); 10081 Glue = RetValue.getValue(2); 10082 10083 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10084 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10085 SDValue RetValue2 = 10086 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10087 Chain = RetValue2.getValue(1); 10088 Glue = RetValue2.getValue(2); 10089 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10090 RetValue2); 10091 } 10092 10093 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10094 10095 InVals.push_back(RetValue); 10096 } 10097 10098 return Chain; 10099 } 10100 10101 bool RISCVTargetLowering::CanLowerReturn( 10102 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10103 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10104 SmallVector<CCValAssign, 16> RVLocs; 10105 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10106 10107 Optional<unsigned> FirstMaskArgument; 10108 if (Subtarget.hasVInstructions()) 10109 FirstMaskArgument = preAssignMask(Outs); 10110 10111 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10112 MVT VT = Outs[i].VT; 10113 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10114 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10115 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10116 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10117 *this, FirstMaskArgument)) 10118 return false; 10119 } 10120 return true; 10121 } 10122 10123 SDValue 10124 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10125 bool IsVarArg, 10126 const SmallVectorImpl<ISD::OutputArg> &Outs, 10127 const SmallVectorImpl<SDValue> &OutVals, 10128 const SDLoc &DL, SelectionDAG &DAG) const { 10129 const MachineFunction &MF = DAG.getMachineFunction(); 10130 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10131 10132 // Stores the assignment of the return value to a location. 10133 SmallVector<CCValAssign, 16> RVLocs; 10134 10135 // Info about the registers and stack slot. 10136 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10137 *DAG.getContext()); 10138 10139 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10140 nullptr, CC_RISCV); 10141 10142 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10143 report_fatal_error("GHC functions return void only"); 10144 10145 SDValue Glue; 10146 SmallVector<SDValue, 4> RetOps(1, Chain); 10147 10148 // Copy the result values into the output registers. 10149 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10150 SDValue Val = OutVals[i]; 10151 CCValAssign &VA = RVLocs[i]; 10152 assert(VA.isRegLoc() && "Can only return in registers!"); 10153 10154 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10155 // Handle returning f64 on RV32D with a soft float ABI. 10156 assert(VA.isRegLoc() && "Expected return via registers"); 10157 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10158 DAG.getVTList(MVT::i32, MVT::i32), Val); 10159 SDValue Lo = SplitF64.getValue(0); 10160 SDValue Hi = SplitF64.getValue(1); 10161 Register RegLo = VA.getLocReg(); 10162 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10163 Register RegHi = RegLo + 1; 10164 10165 if (STI.isRegisterReservedByUser(RegLo) || 10166 STI.isRegisterReservedByUser(RegHi)) 10167 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10168 MF.getFunction(), 10169 "Return value register required, but has been reserved."}); 10170 10171 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10172 Glue = Chain.getValue(1); 10173 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10174 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10175 Glue = Chain.getValue(1); 10176 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10177 } else { 10178 // Handle a 'normal' return. 10179 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10180 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10181 10182 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10183 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10184 MF.getFunction(), 10185 "Return value register required, but has been reserved."}); 10186 10187 // Guarantee that all emitted copies are stuck together. 10188 Glue = Chain.getValue(1); 10189 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10190 } 10191 } 10192 10193 RetOps[0] = Chain; // Update chain. 10194 10195 // Add the glue node if we have it. 10196 if (Glue.getNode()) { 10197 RetOps.push_back(Glue); 10198 } 10199 10200 unsigned RetOpc = RISCVISD::RET_FLAG; 10201 // Interrupt service routines use different return instructions. 10202 const Function &Func = DAG.getMachineFunction().getFunction(); 10203 if (Func.hasFnAttribute("interrupt")) { 10204 if (!Func.getReturnType()->isVoidTy()) 10205 report_fatal_error( 10206 "Functions with the interrupt attribute must have void return type!"); 10207 10208 MachineFunction &MF = DAG.getMachineFunction(); 10209 StringRef Kind = 10210 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10211 10212 if (Kind == "user") 10213 RetOpc = RISCVISD::URET_FLAG; 10214 else if (Kind == "supervisor") 10215 RetOpc = RISCVISD::SRET_FLAG; 10216 else 10217 RetOpc = RISCVISD::MRET_FLAG; 10218 } 10219 10220 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10221 } 10222 10223 void RISCVTargetLowering::validateCCReservedRegs( 10224 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10225 MachineFunction &MF) const { 10226 const Function &F = MF.getFunction(); 10227 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10228 10229 if (llvm::any_of(Regs, [&STI](auto Reg) { 10230 return STI.isRegisterReservedByUser(Reg.first); 10231 })) 10232 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10233 F, "Argument register required, but has been reserved."}); 10234 } 10235 10236 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10237 return CI->isTailCall(); 10238 } 10239 10240 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10241 #define NODE_NAME_CASE(NODE) \ 10242 case RISCVISD::NODE: \ 10243 return "RISCVISD::" #NODE; 10244 // clang-format off 10245 switch ((RISCVISD::NodeType)Opcode) { 10246 case RISCVISD::FIRST_NUMBER: 10247 break; 10248 NODE_NAME_CASE(RET_FLAG) 10249 NODE_NAME_CASE(URET_FLAG) 10250 NODE_NAME_CASE(SRET_FLAG) 10251 NODE_NAME_CASE(MRET_FLAG) 10252 NODE_NAME_CASE(CALL) 10253 NODE_NAME_CASE(SELECT_CC) 10254 NODE_NAME_CASE(BR_CC) 10255 NODE_NAME_CASE(BuildPairF64) 10256 NODE_NAME_CASE(SplitF64) 10257 NODE_NAME_CASE(TAIL) 10258 NODE_NAME_CASE(MULHSU) 10259 NODE_NAME_CASE(SLLW) 10260 NODE_NAME_CASE(SRAW) 10261 NODE_NAME_CASE(SRLW) 10262 NODE_NAME_CASE(DIVW) 10263 NODE_NAME_CASE(DIVUW) 10264 NODE_NAME_CASE(REMUW) 10265 NODE_NAME_CASE(ROLW) 10266 NODE_NAME_CASE(RORW) 10267 NODE_NAME_CASE(CLZW) 10268 NODE_NAME_CASE(CTZW) 10269 NODE_NAME_CASE(FSLW) 10270 NODE_NAME_CASE(FSRW) 10271 NODE_NAME_CASE(FSL) 10272 NODE_NAME_CASE(FSR) 10273 NODE_NAME_CASE(FMV_H_X) 10274 NODE_NAME_CASE(FMV_X_ANYEXTH) 10275 NODE_NAME_CASE(FMV_W_X_RV64) 10276 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10277 NODE_NAME_CASE(FCVT_X) 10278 NODE_NAME_CASE(FCVT_XU) 10279 NODE_NAME_CASE(FCVT_W_RV64) 10280 NODE_NAME_CASE(FCVT_WU_RV64) 10281 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10282 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10283 NODE_NAME_CASE(READ_CYCLE_WIDE) 10284 NODE_NAME_CASE(GREV) 10285 NODE_NAME_CASE(GREVW) 10286 NODE_NAME_CASE(GORC) 10287 NODE_NAME_CASE(GORCW) 10288 NODE_NAME_CASE(SHFL) 10289 NODE_NAME_CASE(SHFLW) 10290 NODE_NAME_CASE(UNSHFL) 10291 NODE_NAME_CASE(UNSHFLW) 10292 NODE_NAME_CASE(BFP) 10293 NODE_NAME_CASE(BFPW) 10294 NODE_NAME_CASE(BCOMPRESS) 10295 NODE_NAME_CASE(BCOMPRESSW) 10296 NODE_NAME_CASE(BDECOMPRESS) 10297 NODE_NAME_CASE(BDECOMPRESSW) 10298 NODE_NAME_CASE(VMV_V_X_VL) 10299 NODE_NAME_CASE(VFMV_V_F_VL) 10300 NODE_NAME_CASE(VMV_X_S) 10301 NODE_NAME_CASE(VMV_S_X_VL) 10302 NODE_NAME_CASE(VFMV_S_F_VL) 10303 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10304 NODE_NAME_CASE(READ_VLENB) 10305 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10306 NODE_NAME_CASE(VSLIDEUP_VL) 10307 NODE_NAME_CASE(VSLIDE1UP_VL) 10308 NODE_NAME_CASE(VSLIDEDOWN_VL) 10309 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10310 NODE_NAME_CASE(VID_VL) 10311 NODE_NAME_CASE(VFNCVT_ROD_VL) 10312 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10313 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10314 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10315 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10316 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10317 NODE_NAME_CASE(VECREDUCE_AND_VL) 10318 NODE_NAME_CASE(VECREDUCE_OR_VL) 10319 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10320 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10321 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10322 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10323 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10324 NODE_NAME_CASE(ADD_VL) 10325 NODE_NAME_CASE(AND_VL) 10326 NODE_NAME_CASE(MUL_VL) 10327 NODE_NAME_CASE(OR_VL) 10328 NODE_NAME_CASE(SDIV_VL) 10329 NODE_NAME_CASE(SHL_VL) 10330 NODE_NAME_CASE(SREM_VL) 10331 NODE_NAME_CASE(SRA_VL) 10332 NODE_NAME_CASE(SRL_VL) 10333 NODE_NAME_CASE(SUB_VL) 10334 NODE_NAME_CASE(UDIV_VL) 10335 NODE_NAME_CASE(UREM_VL) 10336 NODE_NAME_CASE(XOR_VL) 10337 NODE_NAME_CASE(SADDSAT_VL) 10338 NODE_NAME_CASE(UADDSAT_VL) 10339 NODE_NAME_CASE(SSUBSAT_VL) 10340 NODE_NAME_CASE(USUBSAT_VL) 10341 NODE_NAME_CASE(FADD_VL) 10342 NODE_NAME_CASE(FSUB_VL) 10343 NODE_NAME_CASE(FMUL_VL) 10344 NODE_NAME_CASE(FDIV_VL) 10345 NODE_NAME_CASE(FNEG_VL) 10346 NODE_NAME_CASE(FABS_VL) 10347 NODE_NAME_CASE(FSQRT_VL) 10348 NODE_NAME_CASE(FMA_VL) 10349 NODE_NAME_CASE(FCOPYSIGN_VL) 10350 NODE_NAME_CASE(SMIN_VL) 10351 NODE_NAME_CASE(SMAX_VL) 10352 NODE_NAME_CASE(UMIN_VL) 10353 NODE_NAME_CASE(UMAX_VL) 10354 NODE_NAME_CASE(FMINNUM_VL) 10355 NODE_NAME_CASE(FMAXNUM_VL) 10356 NODE_NAME_CASE(MULHS_VL) 10357 NODE_NAME_CASE(MULHU_VL) 10358 NODE_NAME_CASE(FP_TO_SINT_VL) 10359 NODE_NAME_CASE(FP_TO_UINT_VL) 10360 NODE_NAME_CASE(SINT_TO_FP_VL) 10361 NODE_NAME_CASE(UINT_TO_FP_VL) 10362 NODE_NAME_CASE(FP_EXTEND_VL) 10363 NODE_NAME_CASE(FP_ROUND_VL) 10364 NODE_NAME_CASE(VWMUL_VL) 10365 NODE_NAME_CASE(VWMULU_VL) 10366 NODE_NAME_CASE(VWMULSU_VL) 10367 NODE_NAME_CASE(VWADD_VL) 10368 NODE_NAME_CASE(VWADDU_VL) 10369 NODE_NAME_CASE(VWSUB_VL) 10370 NODE_NAME_CASE(VWSUBU_VL) 10371 NODE_NAME_CASE(VWADD_W_VL) 10372 NODE_NAME_CASE(VWADDU_W_VL) 10373 NODE_NAME_CASE(VWSUB_W_VL) 10374 NODE_NAME_CASE(VWSUBU_W_VL) 10375 NODE_NAME_CASE(SETCC_VL) 10376 NODE_NAME_CASE(VSELECT_VL) 10377 NODE_NAME_CASE(VP_MERGE_VL) 10378 NODE_NAME_CASE(VMAND_VL) 10379 NODE_NAME_CASE(VMOR_VL) 10380 NODE_NAME_CASE(VMXOR_VL) 10381 NODE_NAME_CASE(VMCLR_VL) 10382 NODE_NAME_CASE(VMSET_VL) 10383 NODE_NAME_CASE(VRGATHER_VX_VL) 10384 NODE_NAME_CASE(VRGATHER_VV_VL) 10385 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10386 NODE_NAME_CASE(VSEXT_VL) 10387 NODE_NAME_CASE(VZEXT_VL) 10388 NODE_NAME_CASE(VCPOP_VL) 10389 NODE_NAME_CASE(VLE_VL) 10390 NODE_NAME_CASE(VSE_VL) 10391 NODE_NAME_CASE(READ_CSR) 10392 NODE_NAME_CASE(WRITE_CSR) 10393 NODE_NAME_CASE(SWAP_CSR) 10394 } 10395 // clang-format on 10396 return nullptr; 10397 #undef NODE_NAME_CASE 10398 } 10399 10400 /// getConstraintType - Given a constraint letter, return the type of 10401 /// constraint it is for this target. 10402 RISCVTargetLowering::ConstraintType 10403 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10404 if (Constraint.size() == 1) { 10405 switch (Constraint[0]) { 10406 default: 10407 break; 10408 case 'f': 10409 return C_RegisterClass; 10410 case 'I': 10411 case 'J': 10412 case 'K': 10413 return C_Immediate; 10414 case 'A': 10415 return C_Memory; 10416 case 'S': // A symbolic address 10417 return C_Other; 10418 } 10419 } else { 10420 if (Constraint == "vr" || Constraint == "vm") 10421 return C_RegisterClass; 10422 } 10423 return TargetLowering::getConstraintType(Constraint); 10424 } 10425 10426 std::pair<unsigned, const TargetRegisterClass *> 10427 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10428 StringRef Constraint, 10429 MVT VT) const { 10430 // First, see if this is a constraint that directly corresponds to a 10431 // RISCV register class. 10432 if (Constraint.size() == 1) { 10433 switch (Constraint[0]) { 10434 case 'r': 10435 // TODO: Support fixed vectors up to XLen for P extension? 10436 if (VT.isVector()) 10437 break; 10438 return std::make_pair(0U, &RISCV::GPRRegClass); 10439 case 'f': 10440 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10441 return std::make_pair(0U, &RISCV::FPR16RegClass); 10442 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10443 return std::make_pair(0U, &RISCV::FPR32RegClass); 10444 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10445 return std::make_pair(0U, &RISCV::FPR64RegClass); 10446 break; 10447 default: 10448 break; 10449 } 10450 } else if (Constraint == "vr") { 10451 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10452 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10453 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10454 return std::make_pair(0U, RC); 10455 } 10456 } else if (Constraint == "vm") { 10457 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10458 return std::make_pair(0U, &RISCV::VMV0RegClass); 10459 } 10460 10461 // Clang will correctly decode the usage of register name aliases into their 10462 // official names. However, other frontends like `rustc` do not. This allows 10463 // users of these frontends to use the ABI names for registers in LLVM-style 10464 // register constraints. 10465 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10466 .Case("{zero}", RISCV::X0) 10467 .Case("{ra}", RISCV::X1) 10468 .Case("{sp}", RISCV::X2) 10469 .Case("{gp}", RISCV::X3) 10470 .Case("{tp}", RISCV::X4) 10471 .Case("{t0}", RISCV::X5) 10472 .Case("{t1}", RISCV::X6) 10473 .Case("{t2}", RISCV::X7) 10474 .Cases("{s0}", "{fp}", RISCV::X8) 10475 .Case("{s1}", RISCV::X9) 10476 .Case("{a0}", RISCV::X10) 10477 .Case("{a1}", RISCV::X11) 10478 .Case("{a2}", RISCV::X12) 10479 .Case("{a3}", RISCV::X13) 10480 .Case("{a4}", RISCV::X14) 10481 .Case("{a5}", RISCV::X15) 10482 .Case("{a6}", RISCV::X16) 10483 .Case("{a7}", RISCV::X17) 10484 .Case("{s2}", RISCV::X18) 10485 .Case("{s3}", RISCV::X19) 10486 .Case("{s4}", RISCV::X20) 10487 .Case("{s5}", RISCV::X21) 10488 .Case("{s6}", RISCV::X22) 10489 .Case("{s7}", RISCV::X23) 10490 .Case("{s8}", RISCV::X24) 10491 .Case("{s9}", RISCV::X25) 10492 .Case("{s10}", RISCV::X26) 10493 .Case("{s11}", RISCV::X27) 10494 .Case("{t3}", RISCV::X28) 10495 .Case("{t4}", RISCV::X29) 10496 .Case("{t5}", RISCV::X30) 10497 .Case("{t6}", RISCV::X31) 10498 .Default(RISCV::NoRegister); 10499 if (XRegFromAlias != RISCV::NoRegister) 10500 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10501 10502 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10503 // TableGen record rather than the AsmName to choose registers for InlineAsm 10504 // constraints, plus we want to match those names to the widest floating point 10505 // register type available, manually select floating point registers here. 10506 // 10507 // The second case is the ABI name of the register, so that frontends can also 10508 // use the ABI names in register constraint lists. 10509 if (Subtarget.hasStdExtF()) { 10510 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10511 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10512 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10513 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10514 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10515 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10516 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10517 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10518 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10519 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10520 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10521 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10522 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10523 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10524 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10525 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10526 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10527 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10528 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10529 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10530 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10531 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10532 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10533 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10534 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10535 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10536 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10537 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10538 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10539 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10540 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10541 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10542 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10543 .Default(RISCV::NoRegister); 10544 if (FReg != RISCV::NoRegister) { 10545 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10546 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10547 unsigned RegNo = FReg - RISCV::F0_F; 10548 unsigned DReg = RISCV::F0_D + RegNo; 10549 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10550 } 10551 if (VT == MVT::f32 || VT == MVT::Other) 10552 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10553 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10554 unsigned RegNo = FReg - RISCV::F0_F; 10555 unsigned HReg = RISCV::F0_H + RegNo; 10556 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10557 } 10558 } 10559 } 10560 10561 if (Subtarget.hasVInstructions()) { 10562 Register VReg = StringSwitch<Register>(Constraint.lower()) 10563 .Case("{v0}", RISCV::V0) 10564 .Case("{v1}", RISCV::V1) 10565 .Case("{v2}", RISCV::V2) 10566 .Case("{v3}", RISCV::V3) 10567 .Case("{v4}", RISCV::V4) 10568 .Case("{v5}", RISCV::V5) 10569 .Case("{v6}", RISCV::V6) 10570 .Case("{v7}", RISCV::V7) 10571 .Case("{v8}", RISCV::V8) 10572 .Case("{v9}", RISCV::V9) 10573 .Case("{v10}", RISCV::V10) 10574 .Case("{v11}", RISCV::V11) 10575 .Case("{v12}", RISCV::V12) 10576 .Case("{v13}", RISCV::V13) 10577 .Case("{v14}", RISCV::V14) 10578 .Case("{v15}", RISCV::V15) 10579 .Case("{v16}", RISCV::V16) 10580 .Case("{v17}", RISCV::V17) 10581 .Case("{v18}", RISCV::V18) 10582 .Case("{v19}", RISCV::V19) 10583 .Case("{v20}", RISCV::V20) 10584 .Case("{v21}", RISCV::V21) 10585 .Case("{v22}", RISCV::V22) 10586 .Case("{v23}", RISCV::V23) 10587 .Case("{v24}", RISCV::V24) 10588 .Case("{v25}", RISCV::V25) 10589 .Case("{v26}", RISCV::V26) 10590 .Case("{v27}", RISCV::V27) 10591 .Case("{v28}", RISCV::V28) 10592 .Case("{v29}", RISCV::V29) 10593 .Case("{v30}", RISCV::V30) 10594 .Case("{v31}", RISCV::V31) 10595 .Default(RISCV::NoRegister); 10596 if (VReg != RISCV::NoRegister) { 10597 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10598 return std::make_pair(VReg, &RISCV::VMRegClass); 10599 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10600 return std::make_pair(VReg, &RISCV::VRRegClass); 10601 for (const auto *RC : 10602 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10603 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10604 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10605 return std::make_pair(VReg, RC); 10606 } 10607 } 10608 } 10609 } 10610 10611 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10612 } 10613 10614 unsigned 10615 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10616 // Currently only support length 1 constraints. 10617 if (ConstraintCode.size() == 1) { 10618 switch (ConstraintCode[0]) { 10619 case 'A': 10620 return InlineAsm::Constraint_A; 10621 default: 10622 break; 10623 } 10624 } 10625 10626 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10627 } 10628 10629 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10630 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10631 SelectionDAG &DAG) const { 10632 // Currently only support length 1 constraints. 10633 if (Constraint.length() == 1) { 10634 switch (Constraint[0]) { 10635 case 'I': 10636 // Validate & create a 12-bit signed immediate operand. 10637 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10638 uint64_t CVal = C->getSExtValue(); 10639 if (isInt<12>(CVal)) 10640 Ops.push_back( 10641 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10642 } 10643 return; 10644 case 'J': 10645 // Validate & create an integer zero operand. 10646 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10647 if (C->getZExtValue() == 0) 10648 Ops.push_back( 10649 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10650 return; 10651 case 'K': 10652 // Validate & create a 5-bit unsigned immediate operand. 10653 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10654 uint64_t CVal = C->getZExtValue(); 10655 if (isUInt<5>(CVal)) 10656 Ops.push_back( 10657 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10658 } 10659 return; 10660 case 'S': 10661 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10662 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10663 GA->getValueType(0))); 10664 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10665 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10666 BA->getValueType(0))); 10667 } 10668 return; 10669 default: 10670 break; 10671 } 10672 } 10673 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10674 } 10675 10676 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10677 Instruction *Inst, 10678 AtomicOrdering Ord) const { 10679 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10680 return Builder.CreateFence(Ord); 10681 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10682 return Builder.CreateFence(AtomicOrdering::Release); 10683 return nullptr; 10684 } 10685 10686 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10687 Instruction *Inst, 10688 AtomicOrdering Ord) const { 10689 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10690 return Builder.CreateFence(AtomicOrdering::Acquire); 10691 return nullptr; 10692 } 10693 10694 TargetLowering::AtomicExpansionKind 10695 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10696 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10697 // point operations can't be used in an lr/sc sequence without breaking the 10698 // forward-progress guarantee. 10699 if (AI->isFloatingPointOperation()) 10700 return AtomicExpansionKind::CmpXChg; 10701 10702 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10703 if (Size == 8 || Size == 16) 10704 return AtomicExpansionKind::MaskedIntrinsic; 10705 return AtomicExpansionKind::None; 10706 } 10707 10708 static Intrinsic::ID 10709 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10710 if (XLen == 32) { 10711 switch (BinOp) { 10712 default: 10713 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10714 case AtomicRMWInst::Xchg: 10715 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 10716 case AtomicRMWInst::Add: 10717 return Intrinsic::riscv_masked_atomicrmw_add_i32; 10718 case AtomicRMWInst::Sub: 10719 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 10720 case AtomicRMWInst::Nand: 10721 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 10722 case AtomicRMWInst::Max: 10723 return Intrinsic::riscv_masked_atomicrmw_max_i32; 10724 case AtomicRMWInst::Min: 10725 return Intrinsic::riscv_masked_atomicrmw_min_i32; 10726 case AtomicRMWInst::UMax: 10727 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 10728 case AtomicRMWInst::UMin: 10729 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 10730 } 10731 } 10732 10733 if (XLen == 64) { 10734 switch (BinOp) { 10735 default: 10736 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10737 case AtomicRMWInst::Xchg: 10738 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 10739 case AtomicRMWInst::Add: 10740 return Intrinsic::riscv_masked_atomicrmw_add_i64; 10741 case AtomicRMWInst::Sub: 10742 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 10743 case AtomicRMWInst::Nand: 10744 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 10745 case AtomicRMWInst::Max: 10746 return Intrinsic::riscv_masked_atomicrmw_max_i64; 10747 case AtomicRMWInst::Min: 10748 return Intrinsic::riscv_masked_atomicrmw_min_i64; 10749 case AtomicRMWInst::UMax: 10750 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 10751 case AtomicRMWInst::UMin: 10752 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 10753 } 10754 } 10755 10756 llvm_unreachable("Unexpected XLen\n"); 10757 } 10758 10759 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10760 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10761 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10762 unsigned XLen = Subtarget.getXLen(); 10763 Value *Ordering = 10764 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10765 Type *Tys[] = {AlignedAddr->getType()}; 10766 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10767 AI->getModule(), 10768 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10769 10770 if (XLen == 64) { 10771 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10772 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10773 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10774 } 10775 10776 Value *Result; 10777 10778 // Must pass the shift amount needed to sign extend the loaded value prior 10779 // to performing a signed comparison for min/max. ShiftAmt is the number of 10780 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10781 // is the number of bits to left+right shift the value in order to 10782 // sign-extend. 10783 if (AI->getOperation() == AtomicRMWInst::Min || 10784 AI->getOperation() == AtomicRMWInst::Max) { 10785 const DataLayout &DL = AI->getModule()->getDataLayout(); 10786 unsigned ValWidth = 10787 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10788 Value *SextShamt = 10789 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10790 Result = Builder.CreateCall(LrwOpScwLoop, 10791 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10792 } else { 10793 Result = 10794 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10795 } 10796 10797 if (XLen == 64) 10798 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10799 return Result; 10800 } 10801 10802 TargetLowering::AtomicExpansionKind 10803 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10804 AtomicCmpXchgInst *CI) const { 10805 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10806 if (Size == 8 || Size == 16) 10807 return AtomicExpansionKind::MaskedIntrinsic; 10808 return AtomicExpansionKind::None; 10809 } 10810 10811 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10812 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10813 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10814 unsigned XLen = Subtarget.getXLen(); 10815 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10816 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10817 if (XLen == 64) { 10818 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10819 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10820 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10821 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10822 } 10823 Type *Tys[] = {AlignedAddr->getType()}; 10824 Function *MaskedCmpXchg = 10825 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10826 Value *Result = Builder.CreateCall( 10827 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10828 if (XLen == 64) 10829 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10830 return Result; 10831 } 10832 10833 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10834 return false; 10835 } 10836 10837 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10838 EVT VT) const { 10839 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10840 return false; 10841 10842 switch (FPVT.getSimpleVT().SimpleTy) { 10843 case MVT::f16: 10844 return Subtarget.hasStdExtZfh(); 10845 case MVT::f32: 10846 return Subtarget.hasStdExtF(); 10847 case MVT::f64: 10848 return Subtarget.hasStdExtD(); 10849 default: 10850 return false; 10851 } 10852 } 10853 10854 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 10855 // If we are using the small code model, we can reduce size of jump table 10856 // entry to 4 bytes. 10857 if (Subtarget.is64Bit() && !isPositionIndependent() && 10858 getTargetMachine().getCodeModel() == CodeModel::Small) { 10859 return MachineJumpTableInfo::EK_Custom32; 10860 } 10861 return TargetLowering::getJumpTableEncoding(); 10862 } 10863 10864 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 10865 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 10866 unsigned uid, MCContext &Ctx) const { 10867 assert(Subtarget.is64Bit() && !isPositionIndependent() && 10868 getTargetMachine().getCodeModel() == CodeModel::Small); 10869 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 10870 } 10871 10872 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10873 EVT VT) const { 10874 VT = VT.getScalarType(); 10875 10876 if (!VT.isSimple()) 10877 return false; 10878 10879 switch (VT.getSimpleVT().SimpleTy) { 10880 case MVT::f16: 10881 return Subtarget.hasStdExtZfh(); 10882 case MVT::f32: 10883 return Subtarget.hasStdExtF(); 10884 case MVT::f64: 10885 return Subtarget.hasStdExtD(); 10886 default: 10887 break; 10888 } 10889 10890 return false; 10891 } 10892 10893 Register RISCVTargetLowering::getExceptionPointerRegister( 10894 const Constant *PersonalityFn) const { 10895 return RISCV::X10; 10896 } 10897 10898 Register RISCVTargetLowering::getExceptionSelectorRegister( 10899 const Constant *PersonalityFn) const { 10900 return RISCV::X11; 10901 } 10902 10903 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10904 // Return false to suppress the unnecessary extensions if the LibCall 10905 // arguments or return value is f32 type for LP64 ABI. 10906 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10907 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10908 return false; 10909 10910 return true; 10911 } 10912 10913 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10914 if (Subtarget.is64Bit() && Type == MVT::i32) 10915 return true; 10916 10917 return IsSigned; 10918 } 10919 10920 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10921 SDValue C) const { 10922 // Check integral scalar types. 10923 if (VT.isScalarInteger()) { 10924 // Omit the optimization if the sub target has the M extension and the data 10925 // size exceeds XLen. 10926 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10927 return false; 10928 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10929 // Break the MUL to a SLLI and an ADD/SUB. 10930 const APInt &Imm = ConstNode->getAPIntValue(); 10931 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10932 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10933 return true; 10934 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10935 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10936 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10937 (Imm - 8).isPowerOf2())) 10938 return true; 10939 // Omit the following optimization if the sub target has the M extension 10940 // and the data size >= XLen. 10941 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10942 return false; 10943 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10944 // a pair of LUI/ADDI. 10945 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10946 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10947 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10948 (1 - ImmS).isPowerOf2()) 10949 return true; 10950 } 10951 } 10952 } 10953 10954 return false; 10955 } 10956 10957 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10958 const SDValue &AddNode, const SDValue &ConstNode) const { 10959 // Let the DAGCombiner decide for vectors. 10960 EVT VT = AddNode.getValueType(); 10961 if (VT.isVector()) 10962 return true; 10963 10964 // Let the DAGCombiner decide for larger types. 10965 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10966 return true; 10967 10968 // It is worse if c1 is simm12 while c1*c2 is not. 10969 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10970 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10971 const APInt &C1 = C1Node->getAPIntValue(); 10972 const APInt &C2 = C2Node->getAPIntValue(); 10973 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10974 return false; 10975 10976 // Default to true and let the DAGCombiner decide. 10977 return true; 10978 } 10979 10980 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10981 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10982 bool *Fast) const { 10983 if (!VT.isVector()) 10984 return false; 10985 10986 EVT ElemVT = VT.getVectorElementType(); 10987 if (Alignment >= ElemVT.getStoreSize()) { 10988 if (Fast) 10989 *Fast = true; 10990 return true; 10991 } 10992 10993 return false; 10994 } 10995 10996 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10997 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10998 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10999 bool IsABIRegCopy = CC.hasValue(); 11000 EVT ValueVT = Val.getValueType(); 11001 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11002 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11003 // and cast to f32. 11004 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11005 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11006 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11007 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11008 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11009 Parts[0] = Val; 11010 return true; 11011 } 11012 11013 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11014 LLVMContext &Context = *DAG.getContext(); 11015 EVT ValueEltVT = ValueVT.getVectorElementType(); 11016 EVT PartEltVT = PartVT.getVectorElementType(); 11017 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11018 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11019 if (PartVTBitSize % ValueVTBitSize == 0) { 11020 assert(PartVTBitSize >= ValueVTBitSize); 11021 // If the element types are different, bitcast to the same element type of 11022 // PartVT first. 11023 // Give an example here, we want copy a <vscale x 1 x i8> value to 11024 // <vscale x 4 x i16>. 11025 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11026 // subvector, then we can bitcast to <vscale x 4 x i16>. 11027 if (ValueEltVT != PartEltVT) { 11028 if (PartVTBitSize > ValueVTBitSize) { 11029 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11030 assert(Count != 0 && "The number of element should not be zero."); 11031 EVT SameEltTypeVT = 11032 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11033 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11034 DAG.getUNDEF(SameEltTypeVT), Val, 11035 DAG.getVectorIdxConstant(0, DL)); 11036 } 11037 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11038 } else { 11039 Val = 11040 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11041 Val, DAG.getVectorIdxConstant(0, DL)); 11042 } 11043 Parts[0] = Val; 11044 return true; 11045 } 11046 } 11047 return false; 11048 } 11049 11050 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11051 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11052 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11053 bool IsABIRegCopy = CC.hasValue(); 11054 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11055 SDValue Val = Parts[0]; 11056 11057 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11058 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11059 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11060 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11061 return Val; 11062 } 11063 11064 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11065 LLVMContext &Context = *DAG.getContext(); 11066 SDValue Val = Parts[0]; 11067 EVT ValueEltVT = ValueVT.getVectorElementType(); 11068 EVT PartEltVT = PartVT.getVectorElementType(); 11069 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11070 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11071 if (PartVTBitSize % ValueVTBitSize == 0) { 11072 assert(PartVTBitSize >= ValueVTBitSize); 11073 EVT SameEltTypeVT = ValueVT; 11074 // If the element types are different, convert it to the same element type 11075 // of PartVT. 11076 // Give an example here, we want copy a <vscale x 1 x i8> value from 11077 // <vscale x 4 x i16>. 11078 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11079 // then we can extract <vscale x 1 x i8>. 11080 if (ValueEltVT != PartEltVT) { 11081 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11082 assert(Count != 0 && "The number of element should not be zero."); 11083 SameEltTypeVT = 11084 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11085 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11086 } 11087 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11088 DAG.getVectorIdxConstant(0, DL)); 11089 return Val; 11090 } 11091 } 11092 return SDValue(); 11093 } 11094 11095 SDValue 11096 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11097 SelectionDAG &DAG, 11098 SmallVectorImpl<SDNode *> &Created) const { 11099 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11100 if (isIntDivCheap(N->getValueType(0), Attr)) 11101 return SDValue(N, 0); // Lower SDIV as SDIV 11102 11103 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11104 "Unexpected divisor!"); 11105 11106 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11107 if (!Subtarget.hasStdExtZbt()) 11108 return SDValue(); 11109 11110 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11111 // Besides, more critical path instructions will be generated when dividing 11112 // by 2. So we keep using the original DAGs for these cases. 11113 unsigned Lg2 = Divisor.countTrailingZeros(); 11114 if (Lg2 == 1 || Lg2 >= 12) 11115 return SDValue(); 11116 11117 // fold (sdiv X, pow2) 11118 EVT VT = N->getValueType(0); 11119 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11120 return SDValue(); 11121 11122 SDLoc DL(N); 11123 SDValue N0 = N->getOperand(0); 11124 SDValue Zero = DAG.getConstant(0, DL, VT); 11125 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11126 11127 // Add (N0 < 0) ? Pow2 - 1 : 0; 11128 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11129 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11130 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11131 11132 Created.push_back(Cmp.getNode()); 11133 Created.push_back(Add.getNode()); 11134 Created.push_back(Sel.getNode()); 11135 11136 // Divide by pow2. 11137 SDValue SRA = 11138 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11139 11140 // If we're dividing by a positive value, we're done. Otherwise, we must 11141 // negate the result. 11142 if (Divisor.isNonNegative()) 11143 return SRA; 11144 11145 Created.push_back(SRA.getNode()); 11146 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11147 } 11148 11149 #define GET_REGISTER_MATCHER 11150 #include "RISCVGenAsmMatcher.inc" 11151 11152 Register 11153 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11154 const MachineFunction &MF) const { 11155 Register Reg = MatchRegisterAltName(RegName); 11156 if (Reg == RISCV::NoRegister) 11157 Reg = MatchRegisterName(RegName); 11158 if (Reg == RISCV::NoRegister) 11159 report_fatal_error( 11160 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11161 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11162 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11163 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11164 StringRef(RegName) + "\".")); 11165 return Reg; 11166 } 11167 11168 namespace llvm { 11169 namespace RISCVVIntrinsicsTable { 11170 11171 #define GET_RISCVVIntrinsicsTable_IMPL 11172 #include "RISCVGenSearchableTables.inc" 11173 11174 } // namespace RISCVVIntrinsicsTable 11175 11176 } // namespace llvm 11177